diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..d38162800 --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +**/xtscancodes.js diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 000000000..10e15cec3 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,54 @@ +{ + "env": { + "browser": true, + "es2020": true + }, + "parserOptions": { + "sourceType": "module", + "ecmaVersion": 2020 + }, + "extends": "eslint:recommended", + "rules": { + // Unsafe or confusing stuff that we forbid + + "no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": true }], + "no-constant-condition": ["error", { "checkLoops": false }], + "no-var": "error", + "no-useless-constructor": "error", + "object-shorthand": ["error", "methods", { "avoidQuotes": true }], + "prefer-arrow-callback": "error", + "arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": false } ], + "arrow-parens": ["error", "as-needed", { "requireForBlockBody": true }], + "arrow-spacing": ["error"], + "no-confusing-arrow": ["error", { "allowParens": true }], + + // Enforced coding style + + "brace-style": ["error", "1tbs", { "allowSingleLine": true }], + "indent": ["error", 4, { "SwitchCase": 1, + "VariableDeclarator": "first", + "FunctionDeclaration": { "parameters": "first" }, + "FunctionExpression": { "parameters": "first" }, + "CallExpression": { "arguments": "first" }, + "ArrayExpression": "first", + "ObjectExpression": "first", + "ImportDeclaration": "first", + "ignoreComments": true }], + "comma-spacing": ["error"], + "comma-style": ["error"], + "curly": ["error", "multi-line"], + "func-call-spacing": ["error"], + "func-names": ["error"], + "func-style": ["error", "declaration", { "allowArrowFunctions": true }], + "key-spacing": ["error"], + "keyword-spacing": ["error"], + "no-trailing-spaces": ["error"], + "semi": ["error"], + "space-before-blocks": ["error"], + "space-before-function-paren": ["error", { "anonymous": "always", + "named": "never", + "asyncArrow": "always" }], + "switch-colon-spacing": ["error"], + "camelcase": ["error", { allow: ["^XK_", "^XF86XK_"] }], + } +} diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000..94ac6f8dc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,34 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Client (please complete the following information):** + - OS: [e.g. iOS] + - Browser: [e.g. chrome, safari] + - Browser version: [e.g. 22] + +**Server (please complete the following information):** + - noVNC version: [e.g. 1.0.0 or git commit id] + - VNC server: [e.g. QEMU, TigerVNC] + - WebSocket proxy: [e.g. websockify] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..cbd35aa75 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Question or discussion + url: https://groups.google.com/forum/?fromgroups#!forum/novnc + about: Ask a question or start a discussion diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000..066b2d920 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 000000000..a11d3d0a5 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,97 @@ +name: Publish + +on: + push: + pull_request: + release: + types: [published] + +jobs: + npm: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: | + GITREV=$(git rev-parse --short HEAD) + echo $GITREV + sed -i "s/^\(.*\"version\".*\)\"\([^\"]\+\)\"\(.*\)\$/\1\"\2-g$GITREV\"\3/" package.json + if: github.event_name != 'release' + - uses: actions/setup-node@v4 + with: + # Needs to be explicitly specified for auth to work + registry-url: 'https://registry.npmjs.org' + - run: npm install + - uses: actions/upload-artifact@v4 + with: + name: npm + path: lib + - run: npm publish --access public + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + if: | + github.repository == 'novnc/noVNC' && + github.event_name == 'release' && + !github.event.release.prerelease + - run: npm publish --access public --tag beta + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + if: | + github.repository == 'novnc/noVNC' && + github.event_name == 'release' && + github.event.release.prerelease + - run: npm publish --access public --tag dev + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + if: | + github.repository == 'novnc/noVNC' && + github.event_name == 'push' && + github.event.ref == 'refs/heads/master' + snap: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: | + GITREV=$(git rev-parse --short HEAD) + echo $GITREV + sed -i "s/^\(.*\"version\".*\)\"\([^\"]\+\)\"\(.*\)\$/\1\"\2-g$GITREV\"\3/" package.json + if: github.event_name != 'release' + - run: | + VERSION=$(grep '"version"' package.json | cut -d '"' -f 4) + echo $VERSION + sed -i "s/^version:.*/version: '$VERSION'/" snap/snapcraft.yaml + - uses: snapcore/action-build@v1 + id: snapcraft + - uses: actions/upload-artifact@v4 + with: + name: snap + path: ${{ steps.snapcraft.outputs.snap }} + - uses: snapcore/action-publish@v1 + with: + snap: ${{ steps.snapcraft.outputs.snap }} + release: stable + env: + SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_LOGIN }} + if: | + github.repository == 'novnc/noVNC' && + github.event_name == 'release' && + !github.event.release.prerelease + - uses: snapcore/action-publish@v1 + with: + snap: ${{ steps.snapcraft.outputs.snap }} + release: beta + env: + SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_LOGIN }} + if: | + github.repository == 'novnc/noVNC' && + github.event_name == 'release' && + github.event.release.prerelease + - uses: snapcore/action-publish@v1 + with: + snap: ${{ steps.snapcraft.outputs.snap }} + release: edge + env: + SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_LOGIN }} + if: | + github.repository == 'novnc/noVNC' && + github.event_name == 'push' && + github.event.ref == 'refs/heads/master' diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 000000000..540bb9907 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,19 @@ +name: Lint + +on: [push, pull_request] + +jobs: + eslint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + - run: npm update + - run: npm run lint + html: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + - run: npm update + - run: git ls-tree --name-only -r HEAD | grep -E "[.](html|css)$" | xargs ./utils/validate diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..b72195b52 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,28 @@ +name: Test + +on: [push, pull_request] + +jobs: + test: + strategy: + matrix: + os: + - ubuntu-latest + - windows-latest + browser: + - ChromeHeadless + - FirefoxHeadless + include: + - os: macos-latest + browser: Safari + - os: windows-latest + browser: EdgeHeadless + fail-fast: false + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + - run: npm update + - run: npm run test + env: + TEST_BROWSER_NAME: ${{ matrix.browser }} diff --git a/.github/workflows/translate.yml b/.github/workflows/translate.yml new file mode 100644 index 000000000..a4da9cbfa --- /dev/null +++ b/.github/workflows/translate.yml @@ -0,0 +1,15 @@ +name: Translate + +on: [push, pull_request] + +jobs: + translate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + - run: npm update + - run: sudo apt-get install gettext + - run: make -C po update-pot + - run: make -C po update-po + - run: make -C po update-js diff --git a/.npmignore b/.npmignore deleted file mode 100644 index c335c3382..000000000 --- a/.npmignore +++ /dev/null @@ -1,37 +0,0 @@ -# infra JS -/build/ -/node_modules/ -/tests/ -/utils/ -/recordings/ -/vendor/sinon.js - -# noVNC application files -/app -/vendor/browser-es-module-loader -/vendor/promise.js -/vnc.html -/vnc_lite.html - -# raw translation files -/po - -# config files -/.travis.yml -/karma.conf.js - -# various other files -/.gitmodules -.* -*~ -*.swp -*.swo - -# documentation (except licenses) -/docs/notes -/docs/links -/docs/release.txt -/docs/rfb_notes -/docs/*.pdf -/docs/flash_policy.txt -/CONTRIBUTING.md diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 1ccde9b0e..000000000 --- a/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -language: node_js -sudo: false -cache: - directories: - - node_modules -node_js: -- '6.1' -env: - matrix: - - TEST_BROWSER_NAME=chrome TEST_BROWSER_OS='Windows 10,Linux,OS X 10.11' - - TEST_BROWSER_NAME=firefox TEST_BROWSER_OS='Windows 10,Linux,OS X 10.11' - - TEST_BROWSER_NAME='internet explorer' TEST_BROWSER_OS='Windows 10' - - TEST_BROWSER_NAME=safari TEST_BROWSER_OS='OS X 10.11' -before_script: npm install -g karma-cli -addons: - sauce_connect: - username: "directxman12" - jwt: - secure: "d3ekMYslpn6R4f0ajtRMt9SUFmNGDiItHpqaXC5T4KI0KMEsxgvEOfJot5PiFFJWg1DSpJZH6oaW2UxGZ3duJLZrXIEd/JePY8a6NtT35BNgiDPgcp+eu2Bu3rhrSNg7/HEsD1ma+JeUTnv18Ai5oMFfCCQJx2J6osIxyl/ZVxA=" -stages: -- test -- name: deploy - if: tag is PRESENT -jobs: - include: - - stage: deploy - script: skip - before_script: skip - deploy: - provider: npm - email: directxman12+npm@gmail.com - api_key: - secure: cIidkFmvkdmdwWsqBpxyPUCzBqgK8LhPiNxTrIfhwbUunMsJep9MiiBJtv8poVYG2Y4yfiZmqGn4nfetUdc/LDctd73j+/EM4Z/NUDexVAhJ+9/qCogvpJsSQ96VQo7yBceW4E1fBM3WCU0kcGToYIVSSrwvvRDtJfeYJf2Qqw0= - on: - tags: true - repo: novnc/noVNC - - diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 000000000..e8fb12404 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,13 @@ +maintainers: +- Samuel Mannehed for Cendio AB (@samhed) +- Pierre Ossman for Cendio AB (@CendioOssman) +maintainersEmeritus: +- Joel Martin (@kanaka) +- Solly Ross (@directxman12) +- @astrand +contributors: +# There are a bunch of people that should be here. +# If you want to be on this list, feel free send a PR +# to add yourself. +- jalf +- NTT corp. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 2d2e68cf4..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,42 +0,0 @@ -How to contribute to noVNC -========================== - -We accept code via pull requests on GitHub. There are several guidelines that -we expect contributors submitting code requests to follow. If you have issues -following any of these guidelines, feel free to drop us a line by leaving a -comment in the code request or sending us an email. - -Contributing Guidelines ------------------------ - -* While we don't have an official coding style guide, please try to follow - the general coding style of the existing code. -** Use four spaces instead of tabs -** prefix private variables and functions with an `_` - -* Please try to include unit tests for your code. For instance, if you - introduce a new encoding, add a test to `tests/test.rfb.js` under the - "Encoding Handlers" section (basically, input a small pattern in your - encoding and make sure the pattern gets displayed correctly). If you - fix a bug, try to add a unit test that would have caught that bug - (if possible -- some bugs, especially visual ones, are hard to test for). - -* Squash your commits down in to a clean commit history. For instance, there - should not be "cleanup" commits where you fix issues in previous commits in - the same pull request. Before you go to commit, use `git rebase -i` to - squash these changes into the relevant commits. For instance, a good commit - history might look like "Added support for FOO encoding, Added support for - BAR message, Placed Button in UI to Trigger BAR" (where each comma denotes - a separate commit). - -* Add both a title and description to your commit, if possible. Place more - detail on what you did in the description. - -Running the unit tests ----------------------- - -We use Karma to run our tests. You can launch karma manually, or simply -run `npm test`. The Karma debug page will display the tests in normal -mocha form, if you need it. - -Thanks, and happy coding! diff --git a/LICENSE.txt b/LICENSE.txt index ab95798ee..37efdcdba 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,5 @@ -noVNC is Copyright (C) 2011 Joel Martin +noVNC is Copyright (C) 2022 The noVNC Authors +(./AUTHORS) The noVNC core library files are licensed under the MPL 2.0 (Mozilla Public License 2.0). The noVNC core library is composed of the @@ -41,10 +42,6 @@ licenses (all MPL 2.0 compatible): vendor/pako/ : MIT - vendor/browser-es-module-loader: MIT - - vendor/promise.js : MIT - Any other files not mentioned above are typically marked with a copyright/license header at the top of the file. The default noVNC license is MPL-2.0. @@ -52,22 +49,14 @@ license is MPL-2.0. The following license texts are included: docs/LICENSE.MPL-2.0 - docs/LICENSE.LGPL-3 and - docs/LICENSE.GPL-3 docs/LICENSE.OFL-1.1 docs/LICENSE.BSD-3-Clause (New BSD) docs/LICENSE.BSD-2-Clause (Simplified BSD / FreeBSD) - docs/LICENSE.zlib - docs/LICENSE.Apache-2.0 vendor/pako/LICENSE (MIT) Or alternatively the license texts may be found here: http://www.mozilla.org/MPL/2.0/ - http://www.gnu.org/licenses/lgpl.html and - http://www.gnu.org/licenses/gpl.html http://scripts.sil.org/OFL http://en.wikipedia.org/wiki/BSD_licenses - http://www.gzip.org/zlib/zlib_license.html - http://www.apache.org/licenses/LICENSE-2.0.html https://opensource.org/licenses/MIT diff --git a/README.md b/README.md index 916483571..a771cb438 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ -## noVNC: HTML5 VNC Client +## noVNC: HTML VNC Client Library and Application -[![Build Status](https://travis-ci.org/novnc/noVNC.svg?branch=master)](https://travis-ci.org/novnc/noVNC) +[![Test Status](https://github.com/novnc/noVNC/workflows/Test/badge.svg)](https://github.com/novnc/noVNC/actions?query=workflow%3ATest) +[![Lint Status](https://github.com/novnc/noVNC/workflows/Lint/badge.svg)](https://github.com/novnc/noVNC/actions?query=workflow%3ALint) ### Description -noVNC is a HTML5 VNC client that runs well in any modern browser including -mobile browsers (iOS and Android). +noVNC is both a HTML VNC client JavaScript library and an application built on +top of that library. noVNC runs well in any modern browser including mobile +browsers (iOS and Android). Many companies, projects and products have integrated noVNC including [OpenStack](http://www.openstack.org), @@ -15,6 +17,18 @@ Many companies, projects and products have integrated noVNC including [the Projects and Companies wiki page](https://github.com/novnc/noVNC/wiki/Projects-and-companies-using-noVNC) for a more complete list with additional info and links. +### Table of Contents + +- [News/help/contact](#newshelpcontact) +- [Features](#features) +- [Screenshots](#screenshots) +- [Browser Requirements](#browser-requirements) +- [Server Requirements](#server-requirements) +- [Quick Start](#quick-start) +- [Installation from Snap Package](#installation-from-snap-package) +- [Integration and Deployment](#integration-and-deployment) +- [Authors/Contributors](#authorscontributors) + ### News/help/contact The project website is found at [novnc.com](http://novnc.com). @@ -25,10 +39,17 @@ If you are a noVNC developer/integrator/user (or want to be) please join the [noVNC discussion group](https://groups.google.com/forum/?fromgroups#!forum/novnc). Bugs and feature requests can be submitted via -[github issues](https://github.com/novnc/noVNC/issues). +[github issues](https://github.com/novnc/noVNC/issues). If you have questions +about using noVNC then please first use the +[discussion group](https://groups.google.com/forum/?fromgroups#!forum/novnc). +We also have a [wiki](https://github.com/novnc/noVNC/wiki/) with lots of +helpful information. + If you are looking for a place to start contributing to noVNC, a good place to start would be the issues that are marked as ["patchwelcome"](https://github.com/novnc/noVNC/issues?labels=patchwelcome). +Please check our +[contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) though. If you want to show appreciation for noVNC you could donate to a great non- profits such as: @@ -44,15 +65,18 @@ Please tweet [@noVNC](http://www.twitter.com/noVNC) if you do. ### Features * Supports all modern browsers including mobile (iOS, Android) -* Supported VNC encodings: raw, copyrect, rre, hextile, tight, tightPNG -* WebSocket SSL/TLS encryption (i.e. "wss://") support -* 24-bit true color and 8 bit colour mapped -* Supports desktop resize notification/pseudo-encoding -* Local or remote cursor -* Clipboard copy/paste -* Clipping or scolling modes for large remote screens -* Easy site integration and theming (3 example themes included) -* Licensed under the [MPL 2.0](http://www.mozilla.org/MPL/2.0/) +* Supported authentication methods: none, classical VNC, RealVNC's + RSA-AES, Tight, VeNCrypt Plain, XVP, Apple's Diffie-Hellman, + UltraVNC's MSLogonII +* Supported VNC encodings: raw, copyrect, rre, hextile, tight, tightPNG, + ZRLE, JPEG +* Supports scaling, clipping and resizing the desktop +* Local cursor rendering +* Clipboard copy/paste with full Unicode support +* Translations +* Touch gestures for emulating common mouse actions +* Licensed mainly under the [MPL 2.0](http://www.mozilla.org/MPL/2.0/), see + [the license document](LICENSE.txt) for details ### Screenshots @@ -67,83 +91,140 @@ See more screenshots ### Browser Requirements -* Chrome 49, Firefox 44, Safari 10, Opera 36, IE 11, Edge 12, etc. +noVNC uses many modern web technologies so a formal requirement list is +not available. However these are the minimum versions we are currently +aware of: -* HTML5 Canvas, WebSockets and Typed Arrays, etc. - -* Fast Javascript Engine: this is not strictly a requirement, but without a - fast Javascript engine, noVNC might be painfully slow. - -* See the more detailed -[browser compatibility wiki page](https://github.com/novnc/noVNC/wiki/Browser-support). +* Chrome 64, Firefox 79, Safari 13.4, Opera 51, Edge 79 ### Server Requirements -Unless you are using a VNC server with support for WebSockets connections (such -as [x11vnc/libvncserver](http://libvncserver.sourceforge.net/), -[QEMU](http://www.qemu.org/), or -[MobileVNC](http://www.smartlab.at/mobilevnc/)), you need to use a -WebSockets to TCP socket proxy. There is a python proxy included -('websockify'). +noVNC follows the standard VNC protocol, but unlike other VNC clients it does +require WebSockets support. Many servers include support (e.g. +[x11vnc/libvncserver](http://libvncserver.sourceforge.net/), +[QEMU](http://www.qemu.org/), and +[MobileVNC](http://www.smartlab.at/mobilevnc/)), but for the others you need to +use a WebSockets to TCP socket proxy. noVNC has a sister project +[websockify](https://github.com/novnc/websockify) that provides a simple such +proxy. ### Quick Start -* Use the launch script to start a mini-webserver and the WebSockets proxy - (websockify). The `--vnc` option is used to specify the location of a running - VNC server: +* Use the `novnc_proxy` script to automatically download and start websockify, which + includes a mini-webserver and the WebSockets proxy. The `--vnc` option is + used to specify the location of a running VNC server: + + `./utils/novnc_proxy --vnc localhost:5901` + +* If you don't need to expose the web server to public internet, you can + bind to localhost: + + `./utils/novnc_proxy --vnc localhost:5901 --listen localhost:6081` + +* Point your browser to the cut-and-paste URL that is output by the `novnc_proxy` + script. Hit the Connect button, enter a password if the VNC server has one + configured, and enjoy! + +### Installation from Snap Package +Running the command below will install the latest release of noVNC from Snap: + +`sudo snap install novnc` + +#### Running noVNC from Snap Directly + +You can run the Snap-package installed novnc directly with, for example: - `./utils/launch.sh --vnc localhost:5901` +`novnc --listen 6081 --vnc localhost:5901 # /snap/bin/novnc if /snap/bin is not in your PATH` -* Point your browser to the cut-and-paste URL that is output by the launch - script. Enter a password if the VNC server has one configured. Hit the - Connect button and enjoy! +If you want to use certificate files, due to standard Snap confinement restrictions you need to have them in the /home/\/snap/novnc/current/ directory. If your username is jsmith an example command would be: + + `novnc --listen 8443 --cert ~jsmith/snap/novnc/current/self.crt --key ~jsmith/snap/novnc/current/self.key --vnc ubuntu.example.com:5901` +#### Running noVNC from Snap as a Service (Daemon) +The Snap package also has the capability to run a 'novnc' service which can be +configured to listen on multiple ports connecting to multiple VNC servers +(effectively a service runing multiple instances of novnc). +Instructions (with example values): -### Other Pages +List current services (out-of-box this will be blank): -* [Modules/API](https://github.com/novnc/noVNC/blob/master/docs/API.md) - The library - modules and their Javascript API. +``` +sudo snap get novnc services +Key Value +services.n6080 {...} +services.n6081 {...} +``` -* [Integration](https://github.com/novnc/noVNC/wiki/Integration) - Get noVNC - to work in existing projects. +Create a new service that listens on port 6082 and connects to the VNC server +running on port 5902 on localhost: -* [Troubleshooting](https://github.com/novnc/noVNC/wiki/Troubleshooting) - How - to troubleshoot problems. +`sudo snap set novnc services.n6082.listen=6082 services.n6082.vnc=localhost:5902` -* [Encrypted Connections](https://github.com/novnc/websockify/wiki/Encrypted-Connections) - - Setup websockify so that you can use encrypted connections from noVNC. +(Any services you define with 'snap set' will be automatically started) +Note that the name of the service, 'n6082' in this example, can be anything +as long as it doesn't start with a number or contain spaces/special characters. -* [Advanced Usage](https://github.com/novnc/noVNC/wiki/Advanced-usage) - - Generating an SSL certificate, starting a VNC server, advanced websockify - usage, etc. +View the configuration of the service just created: -* [Testing](https://github.com/novnc/noVNC/wiki/Testing) - Run and write - tests. +``` +sudo snap get novnc services.n6082 +Key Value +services.n6082.listen 6082 +services.n6082.vnc localhost:5902 +``` -* [Translations](https://github.com/novnc/noVNC/wiki/Translations) - Add and - modify localization for JavaScript and HTML. +Disable a service (note that because of a limitation in Snap it's currently not +possible to unset config variables, setting them to blank values is the way +to disable a service): + +`sudo snap set novnc services.n6082.listen='' services.n6082.vnc=''` + +(Any services you set to blank with 'snap set' like this will be automatically stopped) + +Verify that the service is disabled (blank values): + +``` +sudo snap get novnc services.n6082 +Key Value +services.n6082.listen +services.n6082.vnc +``` + +### Integration and Deployment + +Please see our other documents for how to integrate noVNC in your own software, +or deploying the noVNC application in production environments: + +* [Embedding](docs/EMBEDDING.md) - For the noVNC application +* [Library](docs/LIBRARY.md) - For the noVNC JavaScript library ### Authors/Contributors +See [AUTHORS](AUTHORS) for a (full-ish) list of authors. If you're not on +that list and you think you should be, feel free to send a PR to fix that. + * Core team: - * [Joel Martin](https://github.com/kanaka) * [Samuel Mannehed](https://github.com/samhed) (Cendio) - * [Peter Åstrand](https://github.com/astrand) (Cendio) - * [Solly Ross](https://github.com/DirectXMan12) (Red Hat / OpenStack) * [Pierre Ossman](https://github.com/CendioOssman) (Cendio) +* Previous core contributors: + * [Joel Martin](https://github.com/kanaka) (Project founder) + * [Solly Ross](https://github.com/DirectXMan12) (Red Hat / OpenStack) + * Notable contributions: * UI and Icons : Pierre Ossman, Chris Gordon * Original Logo : Michael Sersen * tight encoding : Michael Tinglof (Mercuri.ca) + * RealVNC RSA AES authentication : USTC Vlab Team * Included libraries: - * as3crypto : Henri Torgemane (code.google.com/p/as3crypto) * base64 : Martijn Pieters (Digital Creations 2), Samuel Sieb (sieb.net) * DES : Dave Zimmerman (Widget Workshop), Jef Poskanzer (ACME Labs) * Pako : Vitaly Puzrin (https://github.com/nodeca/pako) -* [Contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) +Do you want to be on this list? Check out our +[contribution guide](https://github.com/novnc/noVNC/wiki/Contributing) and +start hacking! diff --git a/app/error-handler.js b/app/error-handler.js index e5a6adbe8..67b63720c 100644 --- a/app/error-handler.js +++ b/app/error-handler.js @@ -1,56 +1,79 @@ -// NB: this should *not* be included as a module until we have -// native support in the browsers, so that our error handler -// can catch script-loading errors. +/* + * noVNC: HTML5 VNC client + * Copyright (C) 2019 The noVNC Authors + * Licensed under MPL 2.0 (see LICENSE.txt) + * + * See README.md for usage and integration instructions. + */ +// Fallback for all uncought errors +function handleError(event, err) { + try { + const msg = document.getElementById('noVNC_fallback_errormsg'); -(function(){ - "use strict"; + // Work around Firefox bug: + // https://bugzilla.mozilla.org/show_bug.cgi?id=1685038 + if (event.message === "ResizeObserver loop completed with undelivered notifications.") { + return false; + } + + // Only show the initial error + if (msg.hasChildNodes()) { + return false; + } - // Fallback for all uncought errors - function handleError (event, err) { - try { - var msg = document.getElementById('noVNC_fallback_errormsg'); + let div = document.createElement("div"); + div.classList.add('noVNC_message'); + div.appendChild(document.createTextNode(event.message)); + msg.appendChild(div); - // Only show the initial error - if (msg.hasChildNodes()) { - return false; + if (event.filename) { + div = document.createElement("div"); + div.className = 'noVNC_location'; + let text = event.filename; + if (event.lineno !== undefined) { + text += ":" + event.lineno; + if (event.colno !== undefined) { + text += ":" + event.colno; + } } + div.appendChild(document.createTextNode(text)); + msg.appendChild(div); + } - var div = document.createElement("div"); - div.classList.add('noVNC_message'); - div.appendChild(document.createTextNode(event.message)); + if (err && err.stack) { + div = document.createElement("div"); + div.className = 'noVNC_stack'; + div.appendChild(document.createTextNode(err.stack)); msg.appendChild(div); + } - if (event.filename) { - div = document.createElement("div"); - div.className = 'noVNC_location'; - var text = event.filename; - if (event.lineno !== undefined) { - text += ":" + event.lineno; - if (event.colno !== undefined) { - text += ":" + event.colno; - } - } - div.appendChild(document.createTextNode(text)); - msg.appendChild(div); - } + document.getElementById('noVNC_fallback_error') + .classList.add("noVNC_open"); - if (err && (err.stack !== undefined)) { - div = document.createElement("div"); - div.className = 'noVNC_stack'; - div.appendChild(document.createTextNode(err.stack)); - msg.appendChild(div); - } + } catch (exc) { + document.write("noVNC encountered an error."); + } - document.getElementById('noVNC_fallback_error') - .classList.add("noVNC_open"); - } catch (exc) { - document.write("noVNC encountered an error."); - } - // Don't return true since this would prevent the error - // from being printed to the browser console. - return false; + // Try to disable keyboard interaction, best effort + try { + // Remove focus from the currently focused element in order to + // prevent keyboard interaction from continuing + if (document.activeElement) { document.activeElement.blur(); } + + // Don't let any element be focusable when showing the error + let keyboardFocusable = 'a[href], button, input, textarea, select, details, [tabindex]'; + document.querySelectorAll(keyboardFocusable).forEach((elem) => { + elem.setAttribute("tabindex", "-1"); + }); + } catch (exc) { + // Do nothing } - window.addEventListener('error', function (evt) { handleError(evt, evt.error); }); - window.addEventListener('unhandledrejection', function (evt) { handleError(evt.reason, evt.reason); }); -})(); + + // Don't return true since this would prevent the error + // from being printed to the browser console. + return false; +} + +window.addEventListener('error', evt => handleError(evt, evt.error)); +window.addEventListener('unhandledrejection', evt => handleError(evt.reason, evt.reason)); diff --git a/app/images/icons/Makefile b/app/images/icons/Makefile index be564b43b..03eaed071 100644 --- a/app/images/icons/Makefile +++ b/app/images/icons/Makefile @@ -1,42 +1,42 @@ -ICONS := \ - novnc-16x16.png \ - novnc-24x24.png \ - novnc-32x32.png \ - novnc-48x48.png \ - novnc-64x64.png - -ANDROID_LAUNCHER := \ - novnc-48x48.png \ - novnc-72x72.png \ - novnc-96x96.png \ - novnc-144x144.png \ - novnc-192x192.png - -IPHONE_LAUNCHER := \ - novnc-60x60.png \ - novnc-120x120.png - -IPAD_LAUNCHER := \ - novnc-76x76.png \ - novnc-152x152.png - -ALL_ICONS := $(ICONS) $(ANDROID_LAUNCHER) $(IPHONE_LAUNCHER) $(IPAD_LAUNCHER) +BROWSER_SIZES := 16 24 32 48 64 +#ANDROID_SIZES := 72 96 144 192 +# FIXME: The ICO is limited to 8 icons due to a Chrome bug: +# https://bugs.chromium.org/p/chromium/issues/detail?id=1381393 +ANDROID_SIZES := 96 144 192 +WEB_ICON_SIZES := $(BROWSER_SIZES) $(ANDROID_SIZES) + +#IOS_1X_SIZES := 20 29 40 76 # No such devices exist anymore +IOS_2X_SIZES := 40 58 80 120 152 167 +IOS_3X_SIZES := 60 87 120 180 +ALL_IOS_SIZES := $(IOS_1X_SIZES) $(IOS_2X_SIZES) $(IOS_3X_SIZES) + +ALL_ICONS := \ + $(ALL_IOS_SIZES:%=novnc-ios-%.png) \ + novnc.ico all: $(ALL_ICONS) -novnc-16x16.png: novnc-icon-sm.svg - convert -density 90 \ - -background transparent "$<" "$@" -novnc-24x24.png: novnc-icon-sm.svg - convert -density 135 \ - -background transparent "$<" "$@" -novnc-32x32.png: novnc-icon-sm.svg - convert -density 180 \ - -background transparent "$<" "$@" +# Our testing shows that the ICO file need to be sorted in largest to +# smallest to get the apporpriate behviour +WEB_ICON_SIZES_REVERSE := $(shell echo $(WEB_ICON_SIZES) | tr ' ' '\n' | sort -nr | tr '\n' ' ') +WEB_BASE_ICONS := $(WEB_ICON_SIZES_REVERSE:%=novnc-%.png) +.INTERMEDIATE: $(WEB_BASE_ICONS) +novnc.ico: $(WEB_BASE_ICONS) + convert $(WEB_BASE_ICONS) "$@" + +# General conversion novnc-%.png: novnc-icon.svg - convert -density $$[`echo $* | cut -d x -f 1` * 90 / 48] \ - -background transparent "$<" "$@" + convert -depth 8 -background transparent \ + -size $*x$* "$(lastword $^)" "$@" + +# iOS icons use their own SVG +novnc-ios-%.png: novnc-ios-icon.svg + convert -depth 8 -background transparent \ + -size $*x$* "$(lastword $^)" "$@" + +# The smallest sizes are generated using a different SVG +novnc-16.png novnc-24.png novnc-32.png: novnc-icon-sm.svg clean: rm -f *.png diff --git a/app/images/icons/novnc-120x120.png b/app/images/icons/novnc-120x120.png deleted file mode 100644 index 40823efba..000000000 Binary files a/app/images/icons/novnc-120x120.png and /dev/null differ diff --git a/app/images/icons/novnc-144x144.png b/app/images/icons/novnc-144x144.png deleted file mode 100644 index eee71f11c..000000000 Binary files a/app/images/icons/novnc-144x144.png and /dev/null differ diff --git a/app/images/icons/novnc-152x152.png b/app/images/icons/novnc-152x152.png deleted file mode 100644 index 0694b2de3..000000000 Binary files a/app/images/icons/novnc-152x152.png and /dev/null differ diff --git a/app/images/icons/novnc-16x16.png b/app/images/icons/novnc-16x16.png deleted file mode 100644 index 42108f409..000000000 Binary files a/app/images/icons/novnc-16x16.png and /dev/null differ diff --git a/app/images/icons/novnc-192x192.png b/app/images/icons/novnc-192x192.png deleted file mode 100644 index ef9201f43..000000000 Binary files a/app/images/icons/novnc-192x192.png and /dev/null differ diff --git a/app/images/icons/novnc-24x24.png b/app/images/icons/novnc-24x24.png deleted file mode 100644 index 110613594..000000000 Binary files a/app/images/icons/novnc-24x24.png and /dev/null differ diff --git a/app/images/icons/novnc-32x32.png b/app/images/icons/novnc-32x32.png deleted file mode 100644 index ff00dc305..000000000 Binary files a/app/images/icons/novnc-32x32.png and /dev/null differ diff --git a/app/images/icons/novnc-48x48.png b/app/images/icons/novnc-48x48.png deleted file mode 100644 index f24cd6cc9..000000000 Binary files a/app/images/icons/novnc-48x48.png and /dev/null differ diff --git a/app/images/icons/novnc-60x60.png b/app/images/icons/novnc-60x60.png deleted file mode 100644 index 06b0d609a..000000000 Binary files a/app/images/icons/novnc-60x60.png and /dev/null differ diff --git a/app/images/icons/novnc-64x64.png b/app/images/icons/novnc-64x64.png deleted file mode 100644 index 6d0fb3418..000000000 Binary files a/app/images/icons/novnc-64x64.png and /dev/null differ diff --git a/app/images/icons/novnc-72x72.png b/app/images/icons/novnc-72x72.png deleted file mode 100644 index 23163a22d..000000000 Binary files a/app/images/icons/novnc-72x72.png and /dev/null differ diff --git a/app/images/icons/novnc-76x76.png b/app/images/icons/novnc-76x76.png deleted file mode 100644 index aef61c480..000000000 Binary files a/app/images/icons/novnc-76x76.png and /dev/null differ diff --git a/app/images/icons/novnc-96x96.png b/app/images/icons/novnc-96x96.png deleted file mode 100644 index 1a77c53f4..000000000 Binary files a/app/images/icons/novnc-96x96.png and /dev/null differ diff --git a/app/images/icons/novnc-ios-120.png b/app/images/icons/novnc-ios-120.png new file mode 100644 index 000000000..8da7bab3d Binary files /dev/null and b/app/images/icons/novnc-ios-120.png differ diff --git a/app/images/icons/novnc-ios-152.png b/app/images/icons/novnc-ios-152.png new file mode 100644 index 000000000..60b2bcef5 Binary files /dev/null and b/app/images/icons/novnc-ios-152.png differ diff --git a/app/images/icons/novnc-ios-167.png b/app/images/icons/novnc-ios-167.png new file mode 100644 index 000000000..98fade2e2 Binary files /dev/null and b/app/images/icons/novnc-ios-167.png differ diff --git a/app/images/icons/novnc-ios-180.png b/app/images/icons/novnc-ios-180.png new file mode 100644 index 000000000..5d24df70a Binary files /dev/null and b/app/images/icons/novnc-ios-180.png differ diff --git a/app/images/icons/novnc-ios-40.png b/app/images/icons/novnc-ios-40.png new file mode 100644 index 000000000..cf14894da Binary files /dev/null and b/app/images/icons/novnc-ios-40.png differ diff --git a/app/images/icons/novnc-ios-58.png b/app/images/icons/novnc-ios-58.png new file mode 100644 index 000000000..f6dfbebd2 Binary files /dev/null and b/app/images/icons/novnc-ios-58.png differ diff --git a/app/images/icons/novnc-ios-60.png b/app/images/icons/novnc-ios-60.png new file mode 100644 index 000000000..8cda29530 Binary files /dev/null and b/app/images/icons/novnc-ios-60.png differ diff --git a/app/images/icons/novnc-ios-80.png b/app/images/icons/novnc-ios-80.png new file mode 100644 index 000000000..6c417c47e Binary files /dev/null and b/app/images/icons/novnc-ios-80.png differ diff --git a/app/images/icons/novnc-ios-87.png b/app/images/icons/novnc-ios-87.png new file mode 100644 index 000000000..4377d874b Binary files /dev/null and b/app/images/icons/novnc-ios-87.png differ diff --git a/app/images/icons/novnc-ios-icon.svg b/app/images/icons/novnc-ios-icon.svg new file mode 100644 index 000000000..009452ac6 --- /dev/null +++ b/app/images/icons/novnc-ios-icon.svg @@ -0,0 +1,183 @@ + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/images/icons/novnc.ico b/app/images/icons/novnc.ico new file mode 100644 index 000000000..c3bc58e38 Binary files /dev/null and b/app/images/icons/novnc.ico differ diff --git a/app/images/mouse_left.svg b/app/images/mouse_left.svg deleted file mode 100644 index ce4cca41c..000000000 --- a/app/images/mouse_left.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/app/images/mouse_middle.svg b/app/images/mouse_middle.svg deleted file mode 100644 index 6603425cb..000000000 --- a/app/images/mouse_middle.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/app/images/mouse_none.svg b/app/images/mouse_none.svg deleted file mode 100644 index 3e0f838a7..000000000 --- a/app/images/mouse_none.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/app/images/mouse_right.svg b/app/images/mouse_right.svg deleted file mode 100644 index f4bad7679..000000000 --- a/app/images/mouse_right.svg +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/app/images/windows.svg b/app/images/windows.svg new file mode 100644 index 000000000..ad5eec36e --- /dev/null +++ b/app/images/windows.svg @@ -0,0 +1,65 @@ + + + +image/svg+xml + + + \ No newline at end of file diff --git a/app/locale/README b/app/locale/README new file mode 100644 index 000000000..ca4f548bc --- /dev/null +++ b/app/locale/README @@ -0,0 +1 @@ +DO NOT MODIFY THE FILES IN THIS FOLDER, THEY ARE AUTOMATICALLY GENERATED FROM THE PO-FILES. diff --git a/app/locale/cs.json b/app/locale/cs.json new file mode 100644 index 000000000..589145ef3 --- /dev/null +++ b/app/locale/cs.json @@ -0,0 +1,71 @@ +{ + "Connecting...": "Připojení...", + "Disconnecting...": "Odpojení...", + "Reconnecting...": "Obnova připojení...", + "Internal error": "Vnitřní chyba", + "Must set host": "Hostitel musí být nastavení", + "Connected (encrypted) to ": "Připojení (šifrované) k ", + "Connected (unencrypted) to ": "Připojení (nešifrované) k ", + "Something went wrong, connection is closed": "Něco se pokazilo, odpojeno", + "Failed to connect to server": "Chyba připojení k serveru", + "Disconnected": "Odpojeno", + "New connection has been rejected with reason: ": "Nové připojení bylo odmítnuto s odůvodněním: ", + "New connection has been rejected": "Nové připojení bylo odmítnuto", + "Password is required": "Je vyžadováno heslo", + "noVNC encountered an error:": "noVNC narazilo na chybu:", + "Hide/Show the control bar": "Skrýt/zobrazit ovládací panel", + "Move/Drag Viewport": "Přesunout/přetáhnout výřez", + "viewport drag": "přesun výřezu", + "Active Mouse Button": "Aktivní tlačítka myši", + "No mousebutton": "Žádné", + "Left mousebutton": "Levé tlačítko myši", + "Middle mousebutton": "Prostřední tlačítko myši", + "Right mousebutton": "Pravé tlačítko myši", + "Keyboard": "Klávesnice", + "Show Keyboard": "Zobrazit klávesnici", + "Extra keys": "Extra klávesy", + "Show Extra Keys": "Zobrazit extra klávesy", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Přepnout Ctrl", + "Alt": "Alt", + "Toggle Alt": "Přepnout Alt", + "Send Tab": "Odeslat tabulátor", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Odeslat Esc", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Poslat Ctrl-Alt-Del", + "Shutdown/Reboot": "Vypnutí/Restart", + "Shutdown/Reboot...": "Vypnutí/Restart...", + "Power": "Napájení", + "Shutdown": "Vypnout", + "Reboot": "Restart", + "Reset": "Reset", + "Clipboard": "Schránka", + "Clear": "Vymazat", + "Fullscreen": "Celá obrazovka", + "Settings": "Nastavení", + "Shared Mode": "Sdílený režim", + "View Only": "Pouze prohlížení", + "Clip to Window": "Přizpůsobit oknu", + "Scaling Mode:": "Přizpůsobení velikosti", + "None": "Žádné", + "Local Scaling": "Místní", + "Remote Resizing": "Vzdálené", + "Advanced": "Pokročilé", + "Repeater ID:": "ID opakovače", + "WebSocket": "WebSocket", + "Encrypt": "Šifrování:", + "Host:": "Hostitel:", + "Port:": "Port:", + "Path:": "Cesta", + "Automatic Reconnect": "Automatická obnova připojení", + "Reconnect Delay (ms):": "Zpoždění připojení (ms)", + "Show Dot when No Cursor": "Tečka místo chybějícího kurzoru myši", + "Logging:": "Logování:", + "Disconnect": "Odpojit", + "Connect": "Připojit", + "Password:": "Heslo", + "Send Password": "Odeslat heslo", + "Cancel": "Zrušit" +} \ No newline at end of file diff --git a/app/locale/de.json b/app/locale/de.json index ea56e6d72..62e73360f 100644 --- a/app/locale/de.json +++ b/app/locale/de.json @@ -1,13 +1,16 @@ { "Connecting...": "Verbinden...", + "Disconnecting...": "Verbindung trennen...", + "Reconnecting...": "Verbindung wiederherstellen...", + "Internal error": "Interner Fehler", + "Must set host": "Richten Sie den Server ein", "Connected (encrypted) to ": "Verbunden mit (verschlüsselt) ", "Connected (unencrypted) to ": "Verbunden mit (unverschlüsselt) ", - "Disconnecting...": "Verbindung trennen...", + "Something went wrong, connection is closed": "Etwas lief schief, Verbindung wurde getrennt", "Disconnected": "Verbindung zum Server getrennt", - "Must set host": "Richten Sie den Server ein", - "Reconnecting...": "Verbindung wiederherstellen...", + "New connection has been rejected with reason: ": "Verbindung wurde aus folgendem Grund abgelehnt: ", + "New connection has been rejected": "Verbindung wurde abgelehnt", "Password is required": "Passwort ist erforderlich", - "Disconnect timeout": "Zeitüberschreitung beim Trennen", "noVNC encountered an error:": "Ein Fehler ist aufgetreten:", "Hide/Show the control bar": "Kontrollleiste verstecken/anzeigen", "Move/Drag Viewport": "Ansichtsfenster verschieben/ziehen", @@ -47,10 +50,8 @@ "Scaling Mode:": "Skalierungsmodus:", "None": "Keiner", "Local Scaling": "Lokales skalieren", - "Local Downscaling": "Lokales herunterskalieren", "Remote Resizing": "Serverseitiges skalieren", "Advanced": "Erweitert", - "Local Cursor": "Lokaler Mauszeiger", "Repeater ID:": "Repeater ID:", "WebSocket": "WebSocket", "Encrypt": "Verschlüsselt", diff --git a/app/locale/el.json b/app/locale/el.json index d6fd86f14..11e7c99cc 100644 --- a/app/locale/el.json +++ b/app/locale/el.json @@ -2,14 +2,14 @@ "Connecting...": "Συνδέεται...", "Disconnecting...": "Aποσυνδέεται...", "Reconnecting...": "Επανασυνδέεται...", - "Internal error": "Εσωτερικό λάθος", + "Internal error": "Εσωτερικό σφάλμα", "Must set host": "Πρέπει να οριστεί ο διακομιστής", "Connected (encrypted) to ": "Συνδέθηκε (κρυπτογραφημένα) με το ", "Connected (unencrypted) to ": "Συνδέθηκε (μη κρυπτογραφημένα) με το ", - "Something went wrong, connection is closed": "Κάτι πήγε στραβά, η σύνδεση έκλεισε", + "Something went wrong, connection is closed": "Κάτι πήγε στραβά, η σύνδεση διακόπηκε", "Disconnected": "Αποσυνδέθηκε", "New connection has been rejected with reason: ": "Η νέα σύνδεση απορρίφθηκε με αιτιολογία: ", - "New connection has been rejected": "Η νέα σύνδεση απορρίφθηκε", + "New connection has been rejected": "Η νέα σύνδεση απορρίφθηκε ", "Password is required": "Απαιτείται ο κωδικός πρόσβασης", "noVNC encountered an error:": "το noVNC αντιμετώπισε ένα σφάλμα:", "Hide/Show the control bar": "Απόκρυψη/Εμφάνιση γραμμής ελέγχου", diff --git a/app/locale/es.json b/app/locale/es.json new file mode 100644 index 000000000..b9e663a3d --- /dev/null +++ b/app/locale/es.json @@ -0,0 +1,68 @@ +{ + "Connecting...": "Conectando...", + "Connected (encrypted) to ": "Conectado (con encriptación) a", + "Connected (unencrypted) to ": "Conectado (sin encriptación) a", + "Disconnecting...": "Desconectando...", + "Disconnected": "Desconectado", + "Must set host": "Se debe configurar el host", + "Reconnecting...": "Reconectando...", + "Password is required": "La contraseña es obligatoria", + "Disconnect timeout": "Tiempo de desconexión agotado", + "noVNC encountered an error:": "noVNC ha encontrado un error:", + "Hide/Show the control bar": "Ocultar/Mostrar la barra de control", + "Move/Drag Viewport": "Mover/Arrastrar la ventana", + "viewport drag": "Arrastrar la ventana", + "Active Mouse Button": "Botón activo del ratón", + "No mousebutton": "Ningún botón del ratón", + "Left mousebutton": "Botón izquierdo del ratón", + "Middle mousebutton": "Botón central del ratón", + "Right mousebutton": "Botón derecho del ratón", + "Keyboard": "Teclado", + "Show Keyboard": "Mostrar teclado", + "Extra keys": "Teclas adicionales", + "Show Extra Keys": "Mostrar Teclas Adicionales", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Pulsar/Soltar Ctrl", + "Alt": "Alt", + "Toggle Alt": "Pulsar/Soltar Alt", + "Send Tab": "Enviar Tabulación", + "Tab": "Tabulación", + "Esc": "Esc", + "Send Escape": "Enviar Escape", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Enviar Ctrl+Alt+Del", + "Shutdown/Reboot": "Apagar/Reiniciar", + "Shutdown/Reboot...": "Apagar/Reiniciar...", + "Power": "Encender", + "Shutdown": "Apagar", + "Reboot": "Reiniciar", + "Reset": "Restablecer", + "Clipboard": "Portapapeles", + "Clear": "Vaciar", + "Fullscreen": "Pantalla Completa", + "Settings": "Configuraciones", + "Encrypt": "Encriptar", + "Shared Mode": "Modo Compartido", + "View Only": "Solo visualización", + "Clip to Window": "Recortar al tamaño de la ventana", + "Scaling Mode:": "Modo de escalado:", + "None": "Ninguno", + "Local Scaling": "Escalado Local", + "Local Downscaling": "Reducción de escala local", + "Remote Resizing": "Cambio de tamaño remoto", + "Advanced": "Avanzado", + "Local Cursor": "Cursor Local", + "Repeater ID:": "ID del Repetidor:", + "WebSocket": "WebSocket", + "Host:": "Host:", + "Port:": "Puerto:", + "Path:": "Ruta:", + "Automatic Reconnect": "Reconexión automática", + "Reconnect Delay (ms):": "Retraso en la reconexión (ms):", + "Logging:": "Registrando:", + "Disconnect": "Desconectar", + "Connect": "Conectar", + "Password:": "Contraseña:", + "Cancel": "Cancelar", + "Canvas not supported.": "Canvas no soportado." +} \ No newline at end of file diff --git a/app/locale/fr.json b/app/locale/fr.json new file mode 100644 index 000000000..22531f73b --- /dev/null +++ b/app/locale/fr.json @@ -0,0 +1,78 @@ +{ + "HTTPS is required for full functionality": "", + "Connecting...": "En cours de connexion...", + "Disconnecting...": "Déconnexion en cours...", + "Reconnecting...": "Reconnexion en cours...", + "Internal error": "Erreur interne", + "Must set host": "Doit définir l'hôte", + "Connected (encrypted) to ": "Connecté (chiffré) à ", + "Connected (unencrypted) to ": "Connecté (non chiffré) à ", + "Something went wrong, connection is closed": "Quelque chose s'est mal passé, la connexion a été fermée", + "Failed to connect to server": "Échec de connexion au serveur", + "Disconnected": "Déconnecté", + "New connection has been rejected with reason: ": "Une nouvelle connexion a été rejetée avec motif : ", + "New connection has been rejected": "Une nouvelle connexion a été rejetée", + "Credentials are required": "Les identifiants sont requis", + "noVNC encountered an error:": "noVNC a rencontré une erreur :", + "Hide/Show the control bar": "Masquer/Afficher la barre de contrôle", + "Drag": "Faire glisser", + "Move/Drag Viewport": "Déplacer/faire glisser le Viewport", + "Keyboard": "Clavier", + "Show Keyboard": "Afficher le clavier", + "Extra keys": "Touches supplémentaires", + "Show Extra Keys": "Afficher les touches supplémentaires", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Basculer Ctrl", + "Alt": "Alt", + "Toggle Alt": "Basculer Alt", + "Toggle Windows": "Basculer Windows", + "Windows": "Windows", + "Send Tab": "Envoyer l'onglet", + "Tab": "l'onglet", + "Esc": "Esc", + "Send Escape": "Envoyer Escape", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Envoyer Ctrl-Alt-Del", + "Shutdown/Reboot": "Arrêter/Redémarrer", + "Shutdown/Reboot...": "Arrêter/Redémarrer...", + "Power": "Alimentation", + "Shutdown": "Arrêter", + "Reboot": "Redémarrer", + "Reset": "Réinitialiser", + "Clipboard": "Presse-papiers", + "Edit clipboard content in the textarea below.": "", + "Settings": "Paramètres", + "Shared Mode": "Mode partagé", + "View Only": "Afficher uniquement", + "Clip to Window": "Clip à fenêtre", + "Scaling Mode:": "Mode mise à l'échelle :", + "None": "Aucun", + "Local Scaling": "Mise à l'échelle locale", + "Remote Resizing": "Redimensionnement à distance", + "Advanced": "Avancé", + "Quality:": "Qualité :", + "Compression level:": "Niveau de compression :", + "Repeater ID:": "ID Répéteur :", + "WebSocket": "WebSocket", + "Encrypt": "Chiffrer", + "Host:": "Hôte :", + "Port:": "Port :", + "Path:": "Chemin :", + "Automatic Reconnect": "Reconnecter automatiquemen", + "Reconnect Delay (ms):": "Délai de reconnexion (ms) :", + "Show Dot when No Cursor": "Afficher le point lorsqu'il n'y a pas de curseur", + "Logging:": "Se connecter :", + "Version:": "Version :", + "Disconnect": "Déconnecter", + "Connect": "Connecter", + "Server identity": "", + "The server has provided the following identifying information:": "", + "Fingerprint:": "", + "Please verify that the information is correct and press \"Approve\". Otherwise press \"Reject\".": "", + "Approve": "", + "Reject": "", + "Username:": "Nom d'utilisateur :", + "Password:": "Mot de passe :", + "Send Credentials": "Envoyer les identifiants", + "Cancel": "Annuler" +} \ No newline at end of file diff --git a/app/locale/it.json b/app/locale/it.json new file mode 100644 index 000000000..6fd25702b --- /dev/null +++ b/app/locale/it.json @@ -0,0 +1,72 @@ +{ + "Connecting...": "Connessione in corso...", + "Disconnecting...": "Disconnessione...", + "Reconnecting...": "Riconnessione...", + "Internal error": "Errore interno", + "Must set host": "Devi impostare l'host", + "Connected (encrypted) to ": "Connesso (crittografato) a ", + "Connected (unencrypted) to ": "Connesso (non crittografato) a", + "Something went wrong, connection is closed": "Qualcosa è andato storto, la connessione è stata chiusa", + "Failed to connect to server": "Impossibile connettersi al server", + "Disconnected": "Disconnesso", + "New connection has been rejected with reason: ": "La nuova connessione è stata rifiutata con motivo: ", + "New connection has been rejected": "La nuova connessione è stata rifiutata", + "Credentials are required": "Le credenziali sono obbligatorie", + "noVNC encountered an error:": "noVNC ha riscontrato un errore:", + "Hide/Show the control bar": "Nascondi/Mostra la barra di controllo", + "Drag": "", + "Move/Drag Viewport": "", + "Keyboard": "Tastiera", + "Show Keyboard": "Mostra tastiera", + "Extra keys": "Tasti Aggiuntivi", + "Show Extra Keys": "Mostra Tasti Aggiuntivi", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Tieni premuto Ctrl", + "Alt": "Alt", + "Toggle Alt": "Tieni premuto Alt", + "Toggle Windows": "Tieni premuto Windows", + "Windows": "Windows", + "Send Tab": "Invia Tab", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Invia Esc", + "Ctrl+Alt+Del": "Ctrl+Alt+Canc", + "Send Ctrl-Alt-Del": "Invia Ctrl-Alt-Canc", + "Shutdown/Reboot": "Spegnimento/Riavvio", + "Shutdown/Reboot...": "Spegnimento/Riavvio...", + "Power": "Alimentazione", + "Shutdown": "Spegnimento", + "Reboot": "Riavvio", + "Reset": "Reset", + "Clipboard": "Clipboard", + "Clear": "Pulisci", + "Fullscreen": "Schermo intero", + "Settings": "Impostazioni", + "Shared Mode": "Modalità condivisa", + "View Only": "Sola Visualizzazione", + "Clip to Window": "", + "Scaling Mode:": "Modalità di ridimensionamento:", + "None": "Nessuna", + "Local Scaling": "Ridimensionamento Locale", + "Remote Resizing": "Ridimensionamento Remoto", + "Advanced": "Avanzate", + "Quality:": "Qualità:", + "Compression level:": "Livello Compressione:", + "Repeater ID:": "ID Ripetitore:", + "WebSocket": "WebSocket", + "Encrypt": "Crittografa", + "Host:": "Host:", + "Port:": "Porta:", + "Path:": "Percorso:", + "Automatic Reconnect": "Riconnessione Automatica", + "Reconnect Delay (ms):": "Ritardo Riconnessione (ms):", + "Show Dot when No Cursor": "Mostra Punto quando Nessun Cursore", + "Logging:": "", + "Version:": "Versione:", + "Disconnect": "Disconnetti", + "Connect": "Connetti", + "Username:": "Utente:", + "Password:": "Password:", + "Send Credentials": "Invia Credenziale", + "Cancel": "Annulla" +} \ No newline at end of file diff --git a/app/locale/ja.json b/app/locale/ja.json new file mode 100644 index 000000000..43fc5bf38 --- /dev/null +++ b/app/locale/ja.json @@ -0,0 +1,72 @@ +{ + "Connecting...": "接続しています...", + "Disconnecting...": "切断しています...", + "Reconnecting...": "再接続しています...", + "Internal error": "内部エラー", + "Must set host": "ホストを設定する必要があります", + "Connected (encrypted) to ": "接続しました (暗号化済み): ", + "Connected (unencrypted) to ": "接続しました (暗号化されていません): ", + "Something went wrong, connection is closed": "何らかの問題で、接続が閉じられました", + "Failed to connect to server": "サーバーへの接続に失敗しました", + "Disconnected": "切断しました", + "New connection has been rejected with reason: ": "新規接続は次の理由で拒否されました: ", + "New connection has been rejected": "新規接続は拒否されました", + "Credentials are required": "資格情報が必要です", + "noVNC encountered an error:": "noVNC でエラーが発生しました:", + "Hide/Show the control bar": "コントロールバーを隠す/表示する", + "Drag": "ドラッグ", + "Move/Drag Viewport": "ビューポートを移動/ドラッグ", + "Keyboard": "キーボード", + "Show Keyboard": "キーボードを表示", + "Extra keys": "追加キー", + "Show Extra Keys": "追加キーを表示", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Ctrl キーを切り替え", + "Alt": "Alt", + "Toggle Alt": "Alt キーを切り替え", + "Toggle Windows": "Windows キーを切り替え", + "Windows": "Windows", + "Send Tab": "Tab キーを送信", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Escape キーを送信", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Ctrl-Alt-Del を送信", + "Shutdown/Reboot": "シャットダウン/再起動", + "Shutdown/Reboot...": "シャットダウン/再起動...", + "Power": "電源", + "Shutdown": "シャットダウン", + "Reboot": "再起動", + "Reset": "リセット", + "Clipboard": "クリップボード", + "Clear": "クリア", + "Fullscreen": "全画面表示", + "Settings": "設定", + "Shared Mode": "共有モード", + "View Only": "表示のみ", + "Clip to Window": "ウィンドウにクリップ", + "Scaling Mode:": "スケーリングモード:", + "None": "なし", + "Local Scaling": "ローカルスケーリング", + "Remote Resizing": "リモートでリサイズ", + "Advanced": "高度", + "Quality:": "品質:", + "Compression level:": "圧縮レベル:", + "Repeater ID:": "リピーター ID:", + "WebSocket": "WebSocket", + "Encrypt": "暗号化", + "Host:": "ホスト:", + "Port:": "ポート:", + "Path:": "パス:", + "Automatic Reconnect": "自動再接続", + "Reconnect Delay (ms):": "再接続する遅延 (ミリ秒):", + "Show Dot when No Cursor": "カーソルがないときにドットを表示", + "Logging:": "ロギング:", + "Version:": "バージョン:", + "Disconnect": "切断", + "Connect": "接続", + "Username:": "ユーザー名:", + "Password:": "パスワード:", + "Send Credentials": "資格情報を送信", + "Cancel": "キャンセル" +} \ No newline at end of file diff --git a/app/locale/ko.json b/app/locale/ko.json new file mode 100644 index 000000000..e4ecddcfd --- /dev/null +++ b/app/locale/ko.json @@ -0,0 +1,70 @@ +{ + "Connecting...": "연결중...", + "Disconnecting...": "연결 해제중...", + "Reconnecting...": "재연결중...", + "Internal error": "내부 오류", + "Must set host": "호스트는 설정되어야 합니다.", + "Connected (encrypted) to ": "다음과 (암호화되어) 연결되었습니다:", + "Connected (unencrypted) to ": "다음과 (암호화 없이) 연결되었습니다:", + "Something went wrong, connection is closed": "무언가 잘못되었습니다, 연결이 닫혔습니다.", + "Failed to connect to server": "서버에 연결하지 못했습니다.", + "Disconnected": "연결이 해제되었습니다.", + "New connection has been rejected with reason: ": "새 연결이 다음 이유로 거부되었습니다:", + "New connection has been rejected": "새 연결이 거부되었습니다.", + "Password is required": "비밀번호가 필요합니다.", + "noVNC encountered an error:": "noVNC에 오류가 발생했습니다:", + "Hide/Show the control bar": "컨트롤 바 숨기기/보이기", + "Move/Drag Viewport": "움직이기/드래그 뷰포트", + "viewport drag": "뷰포트 드래그", + "Active Mouse Button": "마우스 버튼 활성화", + "No mousebutton": "마우스 버튼 없음", + "Left mousebutton": "왼쪽 마우스 버튼", + "Middle mousebutton": "중간 마우스 버튼", + "Right mousebutton": "오른쪽 마우스 버튼", + "Keyboard": "키보드", + "Show Keyboard": "키보드 보이기", + "Extra keys": "기타 키들", + "Show Extra Keys": "기타 키들 보이기", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Ctrl 켜기/끄기", + "Alt": "Alt", + "Toggle Alt": "Alt 켜기/끄기", + "Send Tab": "Tab 보내기", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Esc 보내기", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Ctrl+Alt+Del 보내기", + "Shutdown/Reboot": "셧다운/리붓", + "Shutdown/Reboot...": "셧다운/리붓...", + "Power": "전원", + "Shutdown": "셧다운", + "Reboot": "리붓", + "Reset": "리셋", + "Clipboard": "클립보드", + "Clear": "지우기", + "Fullscreen": "전체화면", + "Settings": "설정", + "Shared Mode": "공유 모드", + "View Only": "보기 전용", + "Clip to Window": "창에 클립", + "Scaling Mode:": "스케일링 모드:", + "None": "없음", + "Local Scaling": "로컬 스케일링", + "Remote Resizing": "원격 크기 조절", + "Advanced": "고급", + "Repeater ID:": "중계 ID", + "WebSocket": "웹소켓", + "Encrypt": "암호화", + "Host:": "호스트:", + "Port:": "포트:", + "Path:": "위치:", + "Automatic Reconnect": "자동 재연결", + "Reconnect Delay (ms):": "재연결 지연 시간 (ms)", + "Logging:": "로깅", + "Disconnect": "연결 해제", + "Connect": "연결", + "Password:": "비밀번호:", + "Send Password": "비밀번호 전송", + "Cancel": "취소" +} \ No newline at end of file diff --git a/app/locale/nl.json b/app/locale/nl.json index 85313d6ce..0cdcc92a9 100644 --- a/app/locale/nl.json +++ b/app/locale/nl.json @@ -1,13 +1,17 @@ { "Connecting...": "Verbinden...", + "Disconnecting...": "Verbinding verbreken...", + "Reconnecting...": "Opnieuw verbinding maken...", + "Internal error": "Interne fout", + "Must set host": "Host moeten worden ingesteld", "Connected (encrypted) to ": "Verbonden (versleuteld) met ", "Connected (unencrypted) to ": "Verbonden (onversleuteld) met ", - "Disconnecting...": "Verbinding verbreken...", + "Something went wrong, connection is closed": "Er iets fout gelopen, verbinding werd verbroken", + "Failed to connect to server": "Verbinding maken met server is mislukt", "Disconnected": "Verbinding verbroken", - "Must set host": "Host moeten worden ingesteld", - "Reconnecting...": "Opnieuw verbinding maken...", + "New connection has been rejected with reason: ": "Nieuwe verbinding is geweigerd omwille van de volgende reden: ", + "New connection has been rejected": "Nieuwe verbinding is geweigerd", "Password is required": "Wachtwoord is vereist", - "Disconnect timeout": "Timeout tijdens verbreken van verbinding", "noVNC encountered an error:": "noVNC heeft een fout bemerkt:", "Hide/Show the control bar": "Verberg/Toon de bedieningsbalk", "Move/Drag Viewport": "Verplaats/Versleep Kijkvenster", @@ -22,9 +26,11 @@ "Extra keys": "Extra toetsen", "Show Extra Keys": "Toon Extra Toetsen", "Ctrl": "Ctrl", - "Toggle Ctrl": "Ctrl aan/uitzetten", + "Toggle Ctrl": "Ctrl omschakelen", "Alt": "Alt", - "Toggle Alt": "Alt aan/uitzetten", + "Toggle Alt": "Alt omschakelen", + "Toggle Windows": "Windows omschakelen", + "Windows": "Windows", "Send Tab": "Tab Sturen", "Tab": "Tab", "Esc": "Esc", @@ -47,10 +53,8 @@ "Scaling Mode:": "Schaalmodus:", "None": "Geen", "Local Scaling": "Lokaal Schalen", - "Local Downscaling": "Lokaal Neerschalen", "Remote Resizing": "Op Afstand Formaat Wijzigen", "Advanced": "Geavanceerd", - "Local Cursor": "Lokale Cursor", "Repeater ID:": "Repeater ID:", "WebSocket": "WebSocket", "Encrypt": "Versleutelen", @@ -59,10 +63,11 @@ "Path:": "Pad:", "Automatic Reconnect": "Automatisch Opnieuw Verbinden", "Reconnect Delay (ms):": "Vertraging voor Opnieuw Verbinden (ms):", + "Show Dot when No Cursor": "Geef stip weer indien geen cursor", "Logging:": "Logmeldingen:", "Disconnect": "Verbinding verbreken", "Connect": "Verbinden", "Password:": "Wachtwoord:", - "Cancel": "Annuleren", - "Canvas not supported.": "Canvas wordt niet ondersteund." + "Send Password": "Verzend Wachtwoord:", + "Cancel": "Annuleren" } \ No newline at end of file diff --git a/app/locale/pl.json b/app/locale/pl.json index 3033163c8..006ac7a55 100644 --- a/app/locale/pl.json +++ b/app/locale/pl.json @@ -1,13 +1,16 @@ { "Connecting...": "Łączenie...", + "Disconnecting...": "Rozłączanie...", + "Reconnecting...": "Łączenie...", + "Internal error": "Błąd wewnętrzny", + "Must set host": "Host i port są wymagane", "Connected (encrypted) to ": "Połączenie (szyfrowane) z ", "Connected (unencrypted) to ": "Połączenie (nieszyfrowane) z ", - "Disconnecting...": "Rozłączanie...", + "Something went wrong, connection is closed": "Coś poszło źle, połączenie zostało zamknięte", "Disconnected": "Rozłączony", - "Must set host": "Host i port są wymagane", - "Reconnecting...": "Łączenie...", + "New connection has been rejected with reason: ": "Nowe połączenie zostało odrzucone z powodu: ", + "New connection has been rejected": "Nowe połączenie zostało odrzucone", "Password is required": "Hasło jest wymagane", - "Disconnect timeout": "Timeout rozłączenia", "noVNC encountered an error:": "noVNC napotkało błąd:", "Hide/Show the control bar": "Pokaż/Ukryj pasek ustawień", "Move/Drag Viewport": "Ruszaj/Przeciągaj Viewport", @@ -47,10 +50,8 @@ "Scaling Mode:": "Tryb Skalowania:", "None": "Brak", "Local Scaling": "Skalowanie lokalne", - "Local Downscaling": "Downscaling lokalny", "Remote Resizing": "Skalowanie zdalne", "Advanced": "Zaawansowane", - "Local Cursor": "Lokalny kursor", "Repeater ID:": "ID Repeatera:", "WebSocket": "WebSocket", "Encrypt": "Szyfrowanie", diff --git a/app/locale/pt_BR.json b/app/locale/pt_BR.json new file mode 100644 index 000000000..aa130f764 --- /dev/null +++ b/app/locale/pt_BR.json @@ -0,0 +1,72 @@ +{ + "Connecting...": "Conectando...", + "Disconnecting...": "Desconectando...", + "Reconnecting...": "Reconectando...", + "Internal error": "Erro interno", + "Must set host": "É necessário definir o host", + "Connected (encrypted) to ": "Conectado (com criptografia) a ", + "Connected (unencrypted) to ": "Conectado (sem criptografia) a ", + "Something went wrong, connection is closed": "Algo deu errado. A conexão foi encerrada.", + "Failed to connect to server": "Falha ao conectar-se ao servidor", + "Disconnected": "Desconectado", + "New connection has been rejected with reason: ": "A nova conexão foi rejeitada pelo motivo: ", + "New connection has been rejected": "A nova conexão foi rejeitada", + "Credentials are required": "Credenciais são obrigatórias", + "noVNC encountered an error:": "O noVNC encontrou um erro:", + "Hide/Show the control bar": "Esconder/mostrar a barra de controles", + "Drag": "Arrastar", + "Move/Drag Viewport": "Mover/arrastar a janela", + "Keyboard": "Teclado", + "Show Keyboard": "Mostrar teclado", + "Extra keys": "Teclas adicionais", + "Show Extra Keys": "Mostar teclas adicionais", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Pressionar/soltar Ctrl", + "Alt": "Alt", + "Toggle Alt": "Pressionar/soltar Alt", + "Toggle Windows": "Pressionar/soltar Windows", + "Windows": "Windows", + "Send Tab": "Enviar Tab", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Enviar Esc", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Enviar Ctrl-Alt-Del", + "Shutdown/Reboot": "Desligar/reiniciar", + "Shutdown/Reboot...": "Desligar/reiniciar...", + "Power": "Ligar", + "Shutdown": "Desligar", + "Reboot": "Reiniciar", + "Reset": "Reiniciar (forçado)", + "Clipboard": "Área de transferência", + "Clear": "Limpar", + "Fullscreen": "Tela cheia", + "Settings": "Configurações", + "Shared Mode": "Modo compartilhado", + "View Only": "Apenas visualizar", + "Clip to Window": "Recortar à janela", + "Scaling Mode:": "Modo de dimensionamento:", + "None": "Nenhum", + "Local Scaling": "Local", + "Remote Resizing": "Remoto", + "Advanced": "Avançado", + "Quality:": "Qualidade:", + "Compression level:": "Nível de compressão:", + "Repeater ID:": "ID do repetidor:", + "WebSocket": "WebSocket", + "Encrypt": "Criptografar", + "Host:": "Host:", + "Port:": "Porta:", + "Path:": "Caminho:", + "Automatic Reconnect": "Reconexão automática", + "Reconnect Delay (ms):": "Atraso da reconexão (ms)", + "Show Dot when No Cursor": "Mostrar ponto quando não há cursor", + "Logging:": "Registros:", + "Version:": "Versão:", + "Disconnect": "Desconectar", + "Connect": "Conectar", + "Username:": "Nome de usuário:", + "Password:": "Senha:", + "Send Credentials": "Enviar credenciais", + "Cancel": "Cancelar" +} \ No newline at end of file diff --git a/app/locale/ru.json b/app/locale/ru.json new file mode 100644 index 000000000..cab97396e --- /dev/null +++ b/app/locale/ru.json @@ -0,0 +1,72 @@ +{ + "Connecting...": "Подключение...", + "Disconnecting...": "Отключение...", + "Reconnecting...": "Переподключение...", + "Internal error": "Внутренняя ошибка", + "Must set host": "Задайте имя сервера или IP", + "Connected (encrypted) to ": "Подключено (с шифрованием) к ", + "Connected (unencrypted) to ": "Подключено (без шифрования) к ", + "Something went wrong, connection is closed": "Что-то пошло не так, подключение разорвано", + "Failed to connect to server": "Ошибка подключения к серверу", + "Disconnected": "Отключено", + "New connection has been rejected with reason: ": "Новое соединение отклонено по причине: ", + "New connection has been rejected": "Новое соединение отклонено", + "Credentials are required": "Требуются учетные данные", + "noVNC encountered an error:": "Ошибка noVNC: ", + "Hide/Show the control bar": "Скрыть/Показать контрольную панель", + "Drag": "Переместить", + "Move/Drag Viewport": "Переместить окно", + "Keyboard": "Клавиатура", + "Show Keyboard": "Показать клавиатуру", + "Extra keys": "Дополнительные Кнопки", + "Show Extra Keys": "Показать Дополнительные Кнопки", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Переключение нажатия Ctrl", + "Alt": "Alt", + "Toggle Alt": "Переключение нажатия Alt", + "Toggle Windows": "Переключение вкладок", + "Windows": "Вкладка", + "Send Tab": "Передать нажатие Tab", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "Передать нажатие Escape", + "Ctrl+Alt+Del": "Ctrl+Alt+Del", + "Send Ctrl-Alt-Del": "Передать нажатие Ctrl-Alt-Del", + "Shutdown/Reboot": "Выключить/Перезагрузить", + "Shutdown/Reboot...": "Выключить/Перезагрузить...", + "Power": "Питание", + "Shutdown": "Выключить", + "Reboot": "Перезагрузить", + "Reset": "Сброс", + "Clipboard": "Буфер обмена", + "Clear": "Очистить", + "Fullscreen": "Во весь экран", + "Settings": "Настройки", + "Shared Mode": "Общий режим", + "View Only": "Только Просмотр", + "Clip to Window": "В окно", + "Scaling Mode:": "Масштаб:", + "None": "Нет", + "Local Scaling": "Локльный масштаб", + "Remote Resizing": "Удаленная перенастройка размера", + "Advanced": "Дополнительно", + "Quality:": "Качество", + "Compression level:": "Уровень Сжатия", + "Repeater ID:": "Идентификатор ID:", + "WebSocket": "WebSocket", + "Encrypt": "Шифрование", + "Host:": "Сервер:", + "Port:": "Порт:", + "Path:": "Путь:", + "Automatic Reconnect": "Автоматическое переподключение", + "Reconnect Delay (ms):": "Задержка переподключения (мс):", + "Show Dot when No Cursor": "Показать точку вместо курсора", + "Logging:": "Лог:", + "Version:": "Версия", + "Disconnect": "Отключение", + "Connect": "Подключение", + "Username:": "Имя Пользователя", + "Password:": "Пароль:", + "Send Credentials": "Передача Учетных Данных", + "Cancel": "Выход" +} \ No newline at end of file diff --git a/app/locale/sv.json b/app/locale/sv.json index cfd8867c6..077ef42c8 100644 --- a/app/locale/sv.json +++ b/app/locale/sv.json @@ -1,22 +1,22 @@ { + "HTTPS is required for full functionality": "HTTPS krävs för full funktionalitet", "Connecting...": "Ansluter...", + "Disconnecting...": "Kopplar ner...", + "Reconnecting...": "Återansluter...", + "Internal error": "Internt fel", + "Must set host": "Du måste specifiera en värd", "Connected (encrypted) to ": "Ansluten (krypterat) till ", "Connected (unencrypted) to ": "Ansluten (okrypterat) till ", - "Disconnecting...": "Kopplar ner...", + "Something went wrong, connection is closed": "Något gick fel, anslutningen avslutades", + "Failed to connect to server": "Misslyckades att ansluta till servern", "Disconnected": "Frånkopplad", - "Must set host": "Du måste specifiera en värd", - "Reconnecting...": "Återansluter...", - "Password is required": "Lösenord krävs", - "Disconnect timeout": "Det tog för lång tid att koppla ner", + "New connection has been rejected with reason: ": "Ny anslutning har blivit nekad med följande skäl: ", + "New connection has been rejected": "Ny anslutning har blivit nekad", + "Credentials are required": "Användaruppgifter krävs", "noVNC encountered an error:": "noVNC stötte på ett problem:", "Hide/Show the control bar": "Göm/Visa kontrollbaren", + "Drag": "Dra", "Move/Drag Viewport": "Flytta/Dra Vyn", - "viewport drag": "dra vy", - "Active Mouse Button": "Aktiv musknapp", - "No mousebutton": "Ingen musknapp", - "Left mousebutton": "Vänster musknapp", - "Middle mousebutton": "Mitten-musknapp", - "Right mousebutton": "Höger musknapp", "Keyboard": "Tangentbord", "Show Keyboard": "Visa Tangentbord", "Extra keys": "Extraknappar", @@ -25,6 +25,8 @@ "Toggle Ctrl": "Växla Ctrl", "Alt": "Alt", "Toggle Alt": "Växla Alt", + "Toggle Windows": "Växla Windows", + "Windows": "Windows", "Send Tab": "Skicka Tab", "Tab": "Tab", "Esc": "Esc", @@ -38,8 +40,8 @@ "Reboot": "Boota om", "Reset": "Återställ", "Clipboard": "Urklipp", - "Clear": "Rensa", - "Fullscreen": "Fullskärm", + "Edit clipboard content in the textarea below.": "Redigera urklippets innehåll i fältet nedan.", + "Full Screen": "Fullskärm", "Settings": "Inställningar", "Shared Mode": "Delat Läge", "View Only": "Endast Visning", @@ -47,10 +49,10 @@ "Scaling Mode:": "Skalningsläge:", "None": "Ingen", "Local Scaling": "Lokal Skalning", - "Local Downscaling": "Lokal Nedskalning", "Remote Resizing": "Ändra Storlek", "Advanced": "Avancerat", - "Local Cursor": "Lokal Muspekare", + "Quality:": "Kvalitet:", + "Compression level:": "Kompressionsnivå:", "Repeater ID:": "Repeater-ID:", "WebSocket": "WebSocket", "Encrypt": "Kryptera", @@ -59,10 +61,20 @@ "Path:": "Sökväg:", "Automatic Reconnect": "Automatisk Återanslutning", "Reconnect Delay (ms):": "Fördröjning (ms):", + "Show Dot when No Cursor": "Visa prick när ingen muspekare finns", "Logging:": "Loggning:", + "Version:": "Version:", "Disconnect": "Koppla från", "Connect": "Anslut", + "Server identity": "Server-identitet", + "The server has provided the following identifying information:": "Servern har gett följande identifierande information:", + "Fingerprint:": "Fingeravtryck:", + "Please verify that the information is correct and press \"Approve\". Otherwise press \"Reject\".": "Kontrollera att informationen är korrekt och tryck sedan \"Godkänn\". Tryck annars \"Neka\".", + "Approve": "Godkänn", + "Reject": "Neka", + "Credentials": "Användaruppgifter", + "Username:": "Användarnamn:", "Password:": "Lösenord:", - "Cancel": "Avbryt", - "Canvas not supported.": "Canvas stöds ej" + "Send Credentials": "Skicka Användaruppgifter", + "Cancel": "Avbryt" } \ No newline at end of file diff --git a/app/locale/tr.json b/app/locale/tr.json new file mode 100644 index 000000000..451c1b8a6 --- /dev/null +++ b/app/locale/tr.json @@ -0,0 +1,69 @@ +{ + "Connecting...": "Bağlanıyor...", + "Disconnecting...": "Bağlantı kesiliyor...", + "Reconnecting...": "Yeniden bağlantı kuruluyor...", + "Internal error": "İç hata", + "Must set host": "Sunucuyu kur", + "Connected (encrypted) to ": "Bağlı (şifrelenmiş)", + "Connected (unencrypted) to ": "Bağlandı (şifrelenmemiş)", + "Something went wrong, connection is closed": "Bir şeyler ters gitti, bağlantı kesildi", + "Disconnected": "Bağlantı kesildi", + "New connection has been rejected with reason: ": "Bağlantı aşağıdaki nedenlerden dolayı reddedildi: ", + "New connection has been rejected": "Bağlantı reddedildi", + "Password is required": "Şifre gerekli", + "noVNC encountered an error:": "Bir hata oluştu:", + "Hide/Show the control bar": "Denetim masasını Gizle/Göster", + "Move/Drag Viewport": "Görünümü Taşı/Sürükle", + "viewport drag": "Görüntü penceresini sürükle", + "Active Mouse Button": "Aktif Fare Düğmesi", + "No mousebutton": "Fare düğmesi yok", + "Left mousebutton": "Farenin sol düğmesi", + "Middle mousebutton": "Farenin orta düğmesi", + "Right mousebutton": "Farenin sağ düğmesi", + "Keyboard": "Klavye", + "Show Keyboard": "Klavye Düzenini Göster", + "Extra keys": "Ekstra tuşlar", + "Show Extra Keys": "Ekstra tuşları göster", + "Ctrl": "Ctrl", + "Toggle Ctrl": "Ctrl Değiştir ", + "Alt": "Alt", + "Toggle Alt": "Alt Değiştir", + "Send Tab": "Sekme Gönder", + "Tab": "Sekme", + "Esc": "Esc", + "Send Escape": "Boşluk Gönder", + "Ctrl+Alt+Del": "Ctrl + Alt + Del", + "Send Ctrl-Alt-Del": "Ctrl-Alt-Del Gönder", + "Shutdown/Reboot": "Kapat/Yeniden Başlat", + "Shutdown/Reboot...": "Kapat/Yeniden Başlat...", + "Power": "Güç", + "Shutdown": "Kapat", + "Reboot": "Yeniden Başlat", + "Reset": "Sıfırla", + "Clipboard": "Pano", + "Clear": "Temizle", + "Fullscreen": "Tam Ekran", + "Settings": "Ayarlar", + "Shared Mode": "Paylaşım Modu", + "View Only": "Sadece Görüntüle", + "Clip to Window": "Pencereye Tıkla", + "Scaling Mode:": "Ölçekleme Modu:", + "None": "Bilinmeyen", + "Local Scaling": "Yerel Ölçeklendirme", + "Remote Resizing": "Uzaktan Yeniden Boyutlandırma", + "Advanced": "Gelişmiş", + "Repeater ID:": "Tekralayıcı ID:", + "WebSocket": "WebSocket", + "Encrypt": "Şifrele", + "Host:": "Ana makine:", + "Port:": "Port:", + "Path:": "Yol:", + "Automatic Reconnect": "Otomatik Yeniden Bağlan", + "Reconnect Delay (ms):": "Yeniden Bağlanma Süreci (ms):", + "Logging:": "Giriş yapılıyor:", + "Disconnect": "Bağlantıyı Kes", + "Connect": "Bağlan", + "Password:": "Parola:", + "Cancel": "Vazgeç", + "Canvas not supported.": "Tuval desteklenmiyor." +} \ No newline at end of file diff --git a/app/locale/zh_CN.json b/app/locale/zh_CN.json new file mode 100644 index 000000000..f0aea9af3 --- /dev/null +++ b/app/locale/zh_CN.json @@ -0,0 +1,69 @@ +{ + "Connecting...": "连接中...", + "Disconnecting...": "正在断开连接...", + "Reconnecting...": "重新连接中...", + "Internal error": "内部错误", + "Must set host": "请提供主机名", + "Connected (encrypted) to ": "已连接到(加密)", + "Connected (unencrypted) to ": "已连接到(未加密)", + "Something went wrong, connection is closed": "发生错误,连接已关闭", + "Failed to connect to server": "无法连接到服务器", + "Disconnected": "已断开连接", + "New connection has been rejected with reason: ": "连接被拒绝,原因:", + "New connection has been rejected": "连接被拒绝", + "Password is required": "请提供密码", + "noVNC encountered an error:": "noVNC 遇到一个错误:", + "Hide/Show the control bar": "显示/隐藏控制栏", + "Move/Drag Viewport": "拖放显示范围", + "viewport drag": "显示范围拖放", + "Active Mouse Button": "启动鼠标按鍵", + "No mousebutton": "禁用鼠标按鍵", + "Left mousebutton": "鼠标左鍵", + "Middle mousebutton": "鼠标中鍵", + "Right mousebutton": "鼠标右鍵", + "Keyboard": "键盘", + "Show Keyboard": "显示键盘", + "Extra keys": "额外按键", + "Show Extra Keys": "显示额外按键", + "Ctrl": "Ctrl", + "Toggle Ctrl": "切换 Ctrl", + "Alt": "Alt", + "Toggle Alt": "切换 Alt", + "Send Tab": "发送 Tab 键", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "发送 Escape 键", + "Ctrl+Alt+Del": "Ctrl-Alt-Del", + "Send Ctrl-Alt-Del": "发送 Ctrl-Alt-Del 键", + "Shutdown/Reboot": "关机/重新启动", + "Shutdown/Reboot...": "关机/重新启动...", + "Power": "电源", + "Shutdown": "关机", + "Reboot": "重新启动", + "Reset": "重置", + "Clipboard": "剪贴板", + "Clear": "清除", + "Fullscreen": "全屏", + "Settings": "设置", + "Shared Mode": "分享模式", + "View Only": "仅查看", + "Clip to Window": "限制/裁切窗口大小", + "Scaling Mode:": "缩放模式:", + "None": "无", + "Local Scaling": "本地缩放", + "Remote Resizing": "远程调整大小", + "Advanced": "高级", + "Repeater ID:": "中继站 ID", + "WebSocket": "WebSocket", + "Encrypt": "加密", + "Host:": "主机:", + "Port:": "端口:", + "Path:": "路径:", + "Automatic Reconnect": "自动重新连接", + "Reconnect Delay (ms):": "重新连接间隔 (ms):", + "Logging:": "日志级别:", + "Disconnect": "中断连接", + "Connect": "连接", + "Password:": "密码:", + "Cancel": "取消" +} \ No newline at end of file diff --git a/app/locale/zh_TW.json b/app/locale/zh_TW.json new file mode 100644 index 000000000..8ddf813f0 --- /dev/null +++ b/app/locale/zh_TW.json @@ -0,0 +1,69 @@ +{ + "Connecting...": "連線中...", + "Disconnecting...": "正在中斷連線...", + "Reconnecting...": "重新連線中...", + "Internal error": "內部錯誤", + "Must set host": "請提供主機資訊", + "Connected (encrypted) to ": "已加密連線到", + "Connected (unencrypted) to ": "未加密連線到", + "Something went wrong, connection is closed": "發生錯誤,連線已關閉", + "Failed to connect to server": "無法連線到伺服器", + "Disconnected": "連線已中斷", + "New connection has been rejected with reason: ": "連線被拒絕,原因:", + "New connection has been rejected": "連線被拒絕", + "Password is required": "請提供密碼", + "noVNC encountered an error:": "noVNC 遇到一個錯誤:", + "Hide/Show the control bar": "顯示/隱藏控制列", + "Move/Drag Viewport": "拖放顯示範圍", + "viewport drag": "顯示範圍拖放", + "Active Mouse Button": "啟用滑鼠按鍵", + "No mousebutton": "無滑鼠按鍵", + "Left mousebutton": "滑鼠左鍵", + "Middle mousebutton": "滑鼠中鍵", + "Right mousebutton": "滑鼠右鍵", + "Keyboard": "鍵盤", + "Show Keyboard": "顯示鍵盤", + "Extra keys": "額外按鍵", + "Show Extra Keys": "顯示額外按鍵", + "Ctrl": "Ctrl", + "Toggle Ctrl": "切換 Ctrl", + "Alt": "Alt", + "Toggle Alt": "切換 Alt", + "Send Tab": "送出 Tab 鍵", + "Tab": "Tab", + "Esc": "Esc", + "Send Escape": "送出 Escape 鍵", + "Ctrl+Alt+Del": "Ctrl-Alt-Del", + "Send Ctrl-Alt-Del": "送出 Ctrl-Alt-Del 快捷鍵", + "Shutdown/Reboot": "關機/重新啟動", + "Shutdown/Reboot...": "關機/重新啟動...", + "Power": "電源", + "Shutdown": "關機", + "Reboot": "重新啟動", + "Reset": "重設", + "Clipboard": "剪貼簿", + "Clear": "清除", + "Fullscreen": "全螢幕", + "Settings": "設定", + "Shared Mode": "分享模式", + "View Only": "僅檢視", + "Clip to Window": "限制/裁切視窗大小", + "Scaling Mode:": "縮放模式:", + "None": "無", + "Local Scaling": "本機縮放", + "Remote Resizing": "遠端調整大小", + "Advanced": "進階", + "Repeater ID:": "中繼站 ID", + "WebSocket": "WebSocket", + "Encrypt": "加密", + "Host:": "主機:", + "Port:": "連接埠:", + "Path:": "路徑:", + "Automatic Reconnect": "自動重新連線", + "Reconnect Delay (ms):": "重新連線間隔 (ms):", + "Logging:": "日誌級別:", + "Disconnect": "中斷連線", + "Connect": "連線", + "Password:": "密碼:", + "Cancel": "取消" +} \ No newline at end of file diff --git a/app/localization.js b/app/localization.js index 39c91f68c..7d7e6e6af 100644 --- a/app/localization.js +++ b/app/localization.js @@ -1,6 +1,6 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin + * Copyright (C) 2018 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) * * See README.md for usage and integration instructions. @@ -10,104 +10,140 @@ * Localization Utilities */ -export function Localizer() { - // Currently configured language - this.language = 'en'; +export class Localizer { + constructor() { + // Currently configured language + this.language = 'en'; - // Current dictionary of translations - this.dictionary = undefined; -} + // Current dictionary of translations + this._dictionary = undefined; + } -Localizer.prototype = { // Configure suitable language based on user preferences - setup: function (supportedLanguages) { - var userLanguages; - + async setup(supportedLanguages, baseURL) { this.language = 'en'; // Default: US English + this._dictionary = undefined; + this._setupLanguage(supportedLanguages); + await this._setupDictionary(baseURL); + } + + _setupLanguage(supportedLanguages) { /* * Navigator.languages only available in Chrome (32+) and FireFox (32+) * Fall back to navigator.language for other browsers */ + let userLanguages; if (typeof window.navigator.languages == 'object') { userLanguages = window.navigator.languages; } else { userLanguages = [navigator.language || navigator.userLanguage]; } - for (var i = 0;i < userLanguages.length;i++) { - var userLang = userLanguages[i]; - userLang = userLang.toLowerCase(); - userLang = userLang.replace("_", "-"); - userLang = userLang.split("-"); - - // Built-in default? - if ((userLang[0] === 'en') && - ((userLang[1] === undefined) || (userLang[1] === 'us'))) { - return; - } + for (let i = 0;i < userLanguages.length;i++) { + const userLang = userLanguages[i] + .toLowerCase() + .replace("_", "-") + .split("-"); // First pass: perfect match - for (var j = 0;j < supportedLanguages.length;j++) { - var supLang = supportedLanguages[j]; - supLang = supLang.toLowerCase(); - supLang = supLang.replace("_", "-"); - supLang = supLang.split("-"); + for (let j = 0; j < supportedLanguages.length; j++) { + const supLang = supportedLanguages[j] + .toLowerCase() + .replace("_", "-") + .split("-"); - if (userLang[0] !== supLang[0]) + if (userLang[0] !== supLang[0]) { continue; - if (userLang[1] !== supLang[1]) + } + if (userLang[1] !== supLang[1]) { continue; + } this.language = supportedLanguages[j]; return; } - // Second pass: fallback - for (var j = 0;j < supportedLanguages.length;j++) { - supLang = supportedLanguages[j]; - supLang = supLang.toLowerCase(); - supLang = supLang.replace("_", "-"); - supLang = supLang.split("-"); + // Second pass: English fallback + if (userLang[0] === 'en') { + return; + } + + // Third pass pass: other fallback + for (let j = 0;j < supportedLanguages.length;j++) { + const supLang = supportedLanguages[j] + .toLowerCase() + .replace("_", "-") + .split("-"); - if (userLang[0] !== supLang[0]) + if (userLang[0] !== supLang[0]) { continue; - if (supLang[1] !== undefined) + } + if (supLang[1] !== undefined) { continue; + } this.language = supportedLanguages[j]; return; } } - }, + } + + async _setupDictionary(baseURL) { + if (baseURL) { + if (!baseURL.endsWith("/")) { + baseURL = baseURL + "/"; + } + } else { + baseURL = ""; + } + + if (this.language === "en") { + return; + } + + let response = await fetch(baseURL + this.language + ".json"); + if (!response.ok) { + throw Error("" + response.status + " " + response.statusText); + } + + this._dictionary = await response.json(); + } // Retrieve localised text - get: function (id) { - if (typeof this.dictionary !== 'undefined' && this.dictionary[id]) { - return this.dictionary[id]; + get(id) { + if (typeof this._dictionary !== 'undefined' && + this._dictionary[id]) { + return this._dictionary[id]; } else { return id; } - }, + } // Traverses the DOM and translates relevant fields // See https://html.spec.whatwg.org/multipage/dom.html#attr-translate - translateDOM: function () { - var self = this; + translateDOM() { + const self = this; + function process(elem, enabled) { function isAnyOf(searchElement, items) { return items.indexOf(searchElement) !== -1; } + function translateString(str) { + // We assume surrounding whitespace, and whitespace around line + // breaks is just for source formatting + str = str.split("\n").map(s => s.trim()).join(" ").trim(); + return self.get(str); + } + function translateAttribute(elem, attr) { - var str = elem.getAttribute(attr); - str = self.get(str); + const str = translateString(elem.getAttribute(attr)); elem.setAttribute(attr, str); } function translateTextNode(node) { - var str = node.data.trim(); - str = self.get(str); + const str = translateString(node.data); node.data = str; } @@ -134,7 +170,7 @@ Localizer.prototype = { } if (elem.hasAttribute("label") && isAnyOf(elem.tagName, ["MENUITEM", "MENU", "OPTGROUP", - "OPTION", "TRACK"])) { + "OPTION", "TRACK"])) { translateAttribute(elem, "label"); } // FIXME: Should update "lang" @@ -147,13 +183,13 @@ Localizer.prototype = { } if (elem.hasAttribute("value") && elem.tagName === "INPUT" && - isAnyOf(elem.getAttribute("type"), ["reset", "button"])) { + isAnyOf(elem.getAttribute("type"), ["reset", "button", "submit"])) { translateAttribute(elem, "value"); } } - for (var i = 0;i < elem.childNodes.length;i++) { - var node = elem.childNodes[i]; + for (let i = 0; i < elem.childNodes.length; i++) { + const node = elem.childNodes[i]; if (node.nodeType === node.ELEMENT_NODE) { process(node, enabled); } else if (node.nodeType === node.TEXT_NODE && enabled) { @@ -163,8 +199,8 @@ Localizer.prototype = { } process(document.body, true); - }, -}; + } +} -export var l10n = new Localizer(); +export const l10n = new Localizer(); export default l10n.get.bind(l10n); diff --git a/app/styles/base.css b/app/styles/base.css index b8ce81bd0..f83ad4b93 100644 --- a/app/styles/base.css +++ b/app/styles/base.css @@ -1,8 +1,6 @@ /* * noVNC base CSS - * Copyright (C) 2012 Joel Martin - * Copyright (C) 2016 Samuel Mannehed for Cendio AB - * Copyright (C) 2016 Pierre Ossman for Cendio AB + * Copyright (C) 2019 The noVNC Authors * noVNC is licensed under the MPL 2.0 (see LICENSE.txt) * This file is licensed under the 2-Clause BSD license (see LICENSE.txt). */ @@ -21,10 +19,23 @@ * 10000: Max (used for polyfills) */ +/* + * State variables (set on :root): + * + * noVNC_loading: Page is still loading + * noVNC_connecting: Connecting to server + * noVNC_reconnecting: Re-establishing a connection + * noVNC_connected: Connected to server (most common state) + * noVNC_disconnecting: Disconnecting from server + */ + +:root { + font-family: sans-serif; +} + body { margin:0; padding:0; - font-family: Helvetica; /*Background image with light grey curve.*/ background-color:#494949; background-repeat:no-repeat; @@ -80,88 +91,6 @@ html { 50% { box-shadow: 60px 10px 0 rgba(255, 255, 255, 0); width: 10px; } } -/* ---------------------------------------- - * Input Elements - * ---------------------------------------- - */ - -input[type=input], input[type=password], input[type=number], -input:not([type]), textarea { - /* Disable default rendering */ - -webkit-appearance: none; - -moz-appearance: none; - background: none; - - margin: 2px; - padding: 2px; - border: 1px solid rgb(192, 192, 192); - border-radius: 5px; - color: black; - background: linear-gradient(to top, rgb(255, 255, 255) 80%, rgb(240, 240, 240)); -} - -input[type=button], input[type=submit], select { - /* Disable default rendering */ - -webkit-appearance: none; - -moz-appearance: none; - background: none; - - margin: 2px; - padding: 2px; - border: 1px solid rgb(192, 192, 192); - border-bottom-width: 2px; - border-radius: 5px; - color: black; - background: linear-gradient(to top, rgb(255, 255, 255), rgb(240, 240, 240)); - - /* This avoids it jumping around when :active */ - vertical-align: middle; -} - -input[type=button], input[type=submit] { - padding-left: 20px; - padding-right: 20px; -} - -option { - color: black; - background: white; -} - -input[type=input]:focus, input[type=password]:focus, -input:not([type]):focus, input[type=button]:focus, -input[type=submit]:focus, -textarea:focus, select:focus { - box-shadow: 0px 0px 3px rgba(74, 144, 217, 0.5); - border-color: rgb(74, 144, 217); - outline: none; -} - -input[type=button]::-moz-focus-inner, -input[type=submit]::-moz-focus-inner { - border: none; -} - -input[type=input]:disabled, input[type=password]:disabled, -input:not([type]):disabled, input[type=button]:disabled, -input[type=submit]:disabled, input[type=number]:disabled, -textarea:disabled, select:disabled { - color: rgb(128, 128, 128); - background: rgb(240, 240, 240); -} - -input[type=button]:active, input[type=submit]:active, -select:active { - border-bottom-width: 1px; - margin-top: 3px; -} - -:root:not(.noVNC_touch) input[type=button]:hover:not(:disabled), -:root:not(.noVNC_touch) input[type=submit]:hover:not(:disabled), -:root:not(.noVNC_touch) select:hover:not(:disabled) { - background: linear-gradient(to top, rgb(255, 255, 255), rgb(250, 250, 250)); -} - /* ---------------------------------------- * WebKit centering hacks * ---------------------------------------- @@ -188,13 +117,15 @@ select:active { pointer-events: auto; } .noVNC_vcenter { - display: flex; + display: flex !important; flex-direction: column; justify-content: center; position: fixed; top: 0; left: 0; height: 100%; + margin: 0 !important; + padding: 0 !important; pointer-events: none; } .noVNC_vcenter > * { @@ -218,13 +149,20 @@ select:active { #noVNC_fallback_error { z-index: 1000; visibility: hidden; + /* Put a dark background in front of everything but the error, + and don't let mouse events pass through */ + background: rgba(0, 0, 0, 0.8); + pointer-events: all; } #noVNC_fallback_error.noVNC_open { visibility: visible; } #noVNC_fallback_error > div { - max-width: 90%; + max-width: calc(100vw - 30px - 30px); + max-height: calc(100vh - 30px - 30px); + overflow: auto; + padding: 15px; transition: 0.5s ease-in-out; @@ -263,7 +201,6 @@ select:active { } #noVNC_fallback_error .noVNC_stack { - max-height: 50vh; padding: 10px; margin: 10px; font-size: 0.8em; @@ -307,6 +244,9 @@ select:active { background-color: rgb(110, 132, 163); border-radius: 0 10px 10px 0; + user-select: none; + -webkit-user-select: none; + -webkit-touch-callout: none; /* Disable iOS image long-press popup */ } #noVNC_control_bar.noVNC_open { box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); @@ -379,38 +319,50 @@ select:active { .noVNC_right #noVNC_control_bar.noVNC_open #noVNC_control_bar_handle:after { transform: none; } +/* Larger touch area for the handle, used when a touch screen is available */ #noVNC_control_bar_handle div { position: absolute; right: -35px; top: 0; width: 50px; - height: 50px; -} -:root:not(.noVNC_touch) #noVNC_control_bar_handle div { + height: 100%; display: none; } +@media (any-pointer: coarse) { + #noVNC_control_bar_handle div { + display: initial; + } +} .noVNC_right #noVNC_control_bar_handle div { left: -35px; right: auto; } -#noVNC_control_bar .noVNC_scroll { +#noVNC_control_bar > .noVNC_scroll { max-height: 100vh; /* Chrome is buggy with 100% */ overflow-x: hidden; overflow-y: auto; - padding: 0 10px 0 5px; + padding: 0 10px; } -.noVNC_right #noVNC_control_bar .noVNC_scroll { - padding: 0 5px 0 10px; + +#noVNC_control_bar > .noVNC_scroll > * { + display: block; + margin: 10px auto; } /* Control bar hint */ -#noVNC_control_bar_hint { +#noVNC_hint_anchor { position: fixed; - left: calc(100vw - 50px); + right: -50px; + left: auto; +} +#noVNC_control_bar_anchor.noVNC_right + #noVNC_hint_anchor { + left: -50px; right: auto; - top: 50%; - transform: translateY(-50%) scale(0); +} +#noVNC_control_bar_hint { + position: relative; + transform: scale(0); width: 100px; height: 50%; max-height: 600px; @@ -423,61 +375,65 @@ select:active { border-radius: 10px; transition-delay: 0s; } -#noVNC_control_bar_anchor.noVNC_right #noVNC_control_bar_hint{ - left: auto; - right: calc(100vw - 50px); -} #noVNC_control_bar_hint.noVNC_active { visibility: visible; opacity: 1; transition-delay: 0.2s; - transform: translateY(-50%) scale(1); + transform: scale(1); +} +#noVNC_control_bar_hint.noVNC_notransition { + transition: none !important; } -/* General button style */ -.noVNC_button { - display: block; +/* Control bar buttons */ +#noVNC_control_bar .noVNC_button { padding: 4px 4px; - margin: 10px 0; vertical-align: middle; border:1px solid rgba(255, 255, 255, 0.2); border-radius: 6px; + background-color: transparent; + background-image: unset; /* we don't want the gradiant from input.css */ } -.noVNC_button.noVNC_selected { +#noVNC_control_bar .noVNC_button.noVNC_selected { border-color: rgba(0, 0, 0, 0.8); - background: rgba(0, 0, 0, 0.5); + background-color: rgba(0, 0, 0, 0.5); } -.noVNC_button:disabled { - opacity: 0.4; +#noVNC_control_bar .noVNC_button.noVNC_selected:not(:disabled):hover { + border-color: rgba(0, 0, 0, 0.4); + background-color: rgba(0, 0, 0, 0.2); } -.noVNC_button:focus { - outline: none; +#noVNC_control_bar .noVNC_button:not(:disabled):hover { + background-color: rgba(255, 255, 255, 0.2); } -.noVNC_button:active { +#noVNC_control_bar .noVNC_button:not(:disabled):active { padding-top: 5px; padding-bottom: 3px; } -/* Android browsers don't properly update hover state if touch events - * are intercepted, but focus should be safe to display */ -:root:not(.noVNC_touch) .noVNC_button.noVNC_selected:hover, -.noVNC_button.noVNC_selected:focus { - border-color: rgba(0, 0, 0, 0.4); - background: rgba(0, 0, 0, 0.2); -} -:root:not(.noVNC_touch) .noVNC_button:hover, -.noVNC_button:focus { - background: rgba(255, 255, 255, 0.2); +#noVNC_control_bar .noVNC_button.noVNC_hidden { + display: none !important; } -.noVNC_button.noVNC_hidden { - display: none; + +/* Android browsers don't properly update hover state if touch events are + * intercepted, like they are when clicking on the remote screen. */ +@media (any-pointer: coarse) { + #noVNC_control_bar .noVNC_button:not(:disabled):hover { + background-color: transparent; + } + #noVNC_control_bar .noVNC_button.noVNC_selected:not(:disabled):hover { + border-color: rgba(0, 0, 0, 0.8); + background-color: rgba(0, 0, 0, 0.5); + } } + /* Panels */ .noVNC_panel { transform: translateX(25px); transition: 0.5s ease-in-out; + box-sizing: border-box; /* so max-width don't have to care about padding */ + max-width: calc(100vw - 75px - 25px); /* minus left and right margins */ max-height: 100vh; /* Chrome is buggy with 100% */ overflow-x: hidden; overflow-y: auto; @@ -509,6 +465,17 @@ select:active { transform: translateX(-75px); } +.noVNC_panel > * { + display: block; + margin: 10px auto; +} +.noVNC_panel > *:first-child { + margin-top: 0 !important; +} +.noVNC_panel > *:last-child { + margin-bottom: 0 !important; +} + .noVNC_panel hr { border: none; border-top: 1px solid rgb(192, 192, 192); @@ -517,6 +484,11 @@ select:active { .noVNC_panel label { display: block; white-space: nowrap; + margin: 5px; +} + +.noVNC_panel li { + margin: 5px; } .noVNC_panel .noVNC_heading { @@ -527,7 +499,6 @@ select:active { padding-right: 8px; color: white; font-size: 20px; - margin-bottom: 10px; white-space: nowrap; } .noVNC_panel .noVNC_heading img { @@ -568,6 +539,12 @@ select:active { font-size: 13px; } +.noVNC_logo + hr { + /* Remove all but top border */ + border: none; + border-top: 1px solid rgba(255, 255, 255, 0.2); +} + :root:not(.noVNC_connected) #noVNC_view_drag_button { display: none; } @@ -576,19 +553,26 @@ select:active { :root:not(.noVNC_connected) #noVNC_mobile_buttons { display: none; } -:root:not(.noVNC_touch) #noVNC_mobile_buttons { - display: none; +@media not all and (any-pointer: coarse) { + /* FIXME: The button for the virtual keyboard is the only button in this + group of "mobile buttons". It is bad to assume that no touch + devices have physical keyboards available. Hopefully we can get + a media query for this: + https://github.com/w3c/csswg-drafts/issues/3871 */ + :root.noVNC_connected #noVNC_mobile_buttons { + display: none; + } } /* Extra manual keys */ -:root:not(.noVNC_connected) #noVNC_extra_keys { +:root:not(.noVNC_connected) #noVNC_toggle_extra_keys_button { display: none; } #noVNC_modifiers { background-color: rgb(92, 92, 92); border: none; - padding: 0 10px; + padding: 10px; } /* Shutdown/Reboot */ @@ -609,13 +593,16 @@ select:active { :root:not(.noVNC_connected) #noVNC_clipboard_button { display: none; } -#noVNC_clipboard { - /* Full screen, minus padding and left and right margins */ - max-width: calc(100vw - 2*15px - 75px - 25px); -} #noVNC_clipboard_text { - width: 500px; + width: 360px; + min-width: 150px; + height: 160px; + min-height: 70px; + + box-sizing: border-box; max-width: 100%; + /* minus approximate height of title, height of subtitle, and margin */ + max-height: calc(100vh - 10em - 25px); } /* Settings */ @@ -623,7 +610,6 @@ select:active { } #noVNC_settings ul { list-style: none; - margin: 0px; padding: 0px; } #noVNC_setting_port { @@ -633,6 +619,16 @@ select:active { width: 100px; } +/* Version */ + +.noVNC_version_wrapper { + font-size: small; +} + +.noVNC_version { + margin-left: 1rem; +} + /* Connection Controls */ :root:not(.noVNC_connected) #noVNC_disconnect_button { display: none; @@ -665,7 +661,7 @@ select:active { justify-content: center; align-content: center; - line-height: 25px; + line-height: 1.6; word-wrap: break-word; color: #fff; @@ -739,36 +735,32 @@ select:active { font-size: calc(25vw - 30px); } } -#noVNC_connect_button { - cursor: pointer; - - padding: 10px; +#noVNC_connect_dlg div { + padding: 12px; - color: white; background-color: rgb(110, 132, 163); border-radius: 12px; - text-align: center; font-size: 20px; box-shadow: 6px 6px 0px rgba(0, 0, 0, 0.5); } -#noVNC_connect_button div { - margin: 2px; +#noVNC_connect_button { + width: 100%; padding: 5px 30px; - border: 1px solid rgb(83, 99, 122); - border-bottom-width: 2px; + + cursor: pointer; + + border-color: rgb(83, 99, 122); border-radius: 5px; + background: linear-gradient(to top, rgb(110, 132, 163), rgb(99, 119, 147)); + color: white; /* This avoids it jumping around when :active */ vertical-align: middle; } -#noVNC_connect_button div:active { - border-bottom-width: 1px; - margin-top: 3px; -} -:root:not(.noVNC_touch) #noVNC_connect_button div:hover { +#noVNC_connect_button:hover { background: linear-gradient(to top, rgb(110, 132, 163), rgb(105, 125, 155)); } @@ -777,25 +769,42 @@ select:active { height: 1.3em; } +/* ---------------------------------------- + * Server verification Dialog + * ---------------------------------------- + */ + +#noVNC_verify_server_dlg { + position: relative; + + transform: translateY(-50px); +} +#noVNC_verify_server_dlg.noVNC_open { + transform: translateY(0); +} +#noVNC_fingerprint_block { + margin: 10px; +} + /* ---------------------------------------- * Password Dialog * ---------------------------------------- */ -#noVNC_password_dlg { +#noVNC_credentials_dlg { position: relative; transform: translateY(-50px); } -#noVNC_password_dlg.noVNC_open { +#noVNC_credentials_dlg.noVNC_open { transform: translateY(0); } -#noVNC_password_dlg ul { - list-style: none; - margin: 0px; - padding: 0px; +#noVNC_username_block.noVNC_hidden, +#noVNC_password_block.noVNC_hidden { + display: none; } + /* ---------------------------------------- * Main Area * ---------------------------------------- @@ -803,7 +812,11 @@ select:active { /* Transition screen */ #noVNC_transition { - display: none; + transition: 0.5s ease-in-out; + + display: flex; + opacity: 0; + visibility: hidden; position: fixed; top: 0; @@ -824,7 +837,8 @@ select:active { :root.noVNC_connecting #noVNC_transition, :root.noVNC_disconnecting #noVNC_transition, :root.noVNC_reconnecting #noVNC_transition { - display: flex; + opacity: 1; + visibility: visible; } :root:not(.noVNC_reconnecting) #noVNC_cancel_reconnect_button { display: none; @@ -840,6 +854,12 @@ select:active { background-color: #313131; border-bottom-right-radius: 800px 600px; /*border-top-left-radius: 800px 600px;*/ + + /* If selection isn't disabled, long-pressing stuff in the sidebar + can accidentally select the container or the canvas. This can + happen when attempting to move the handle. */ + user-select: none; + -webkit-user-select: none; } #noVNC_keyboardinput { @@ -854,30 +874,6 @@ select:active { ime-mode: disabled; } -/* HTML5 Canvas */ -#noVNC_screen { - display: flex; - width: 100%; - height: 100%; - overflow: auto; - background-color: rgb(40, 40, 40); -} -:root:not(.noVNC_connected) #noVNC_screen { - display: none; -} - -/* Do not set width/height for VNC_canvas or incorrect - * scaling will occur. Canvas size depends on remote VNC - * settings and noVNC settings. */ -#noVNC_canvas { - margin: auto; - /* IE miscalculates width without this :( */ - flex-shrink: 0; -} -#noVNC_canvas:focus { - outline: none; -} - /*Default noVNC logo.*/ /* From: http://fonts.googleapis.com/css?family=Orbitron:700 */ @font-face { @@ -891,7 +887,7 @@ select:active { .noVNC_logo { color:yellow; font-family: 'Orbitron', 'OrbitronTTF', sans-serif; - line-height:90%; + line-height: 0.9; text-shadow: 0.1em 0.1em 0 black; } .noVNC_logo span{ diff --git a/app/styles/input.css b/app/styles/input.css new file mode 100644 index 000000000..dc345aabc --- /dev/null +++ b/app/styles/input.css @@ -0,0 +1,281 @@ +/* + * noVNC general input element CSS + * Copyright (C) 2022 The noVNC Authors + * noVNC is licensed under the MPL 2.0 (see LICENSE.txt) + * This file is licensed under the 2-Clause BSD license (see LICENSE.txt). + */ + +/* + * Common for all inputs + */ +input, input::file-selector-button, button, select, textarea { + /* Respect standard font settings */ + font: inherit; + + /* Disable default rendering */ + appearance: none; + background: none; + + padding: 5px; + border: 1px solid rgb(192, 192, 192); + border-radius: 5px; + color: black; + --bg-gradient: linear-gradient(to top, rgb(255, 255, 255) 80%, rgb(240, 240, 240)); + background-image: var(--bg-gradient); +} + +/* + * Buttons + */ +input[type=button], +input[type=color], +input[type=image], +input[type=reset], +input[type=submit], +input::file-selector-button, +button, +select { + border-bottom-width: 2px; + + /* This avoids it jumping around when :active */ + vertical-align: middle; + margin-top: 0; + + padding-left: 20px; + padding-right: 20px; + + /* Disable Chrome's touch tap highlight */ + -webkit-tap-highlight-color: transparent; +} + +/* + * Select dropdowns + */ +select { + --select-arrow: url('data:image/svg+xml;utf8, \ + \ + \ + '); + background-image: var(--select-arrow), var(--bg-gradient); + background-position: calc(100% - 7px), left top; + background-repeat: no-repeat; + padding-right: calc(2*7px + 8px); + padding-left: 7px; +} +/* FIXME: :active isn't set when the - -
- - Canvas not supported. - - -
- Results:
- - - - - - - - - - - - - - - - - diff --git a/tests/karma-test-main.js b/tests/karma-test-main.js deleted file mode 100644 index 657e3121c..000000000 --- a/tests/karma-test-main.js +++ /dev/null @@ -1,16 +0,0 @@ -var TEST_REGEXP = /test\..*\.js/; -var allTestFiles = []; -var extraFiles = ['/base/tests/assertions.js']; - -Object.keys(window.__karma__.files).forEach(function (file) { - if (TEST_REGEXP.test(file)) { - // TODO: normalize? - allTestFiles.push(file); - } -}); - -require.config({ - baseUrl: '/base', - deps: allTestFiles.concat(extraFiles), - callback: window.__karma__.start, -}); diff --git a/tests/playback-ui.js b/tests/playback-ui.js index 01ad241e9..b1f263ea8 100644 --- a/tests/playback-ui.js +++ b/tests/playback-ui.js @@ -1,12 +1,13 @@ +/* global VNC_frame_data, VNC_frame_encoding */ + import * as WebUtil from '../app/webutil.js'; import RecordingPlayer from './playback.js'; +import Base64 from '../core/base64.js'; -var frames = null; -var encoding = null; +let frames = null; function message(str) { - console.log(str); - var cell = document.getElementById('messages'); + const cell = document.getElementById('messages'); cell.textContent += str + "\n"; cell.scrollTop = cell.scrollHeight; } @@ -18,71 +19,116 @@ function loadFile() { return Promise.reject("Must specify data=FOO in query string."); } - message("Loading " + fname); + message("Loading " + fname + "..."); - return new Promise(function (resolve, reject) { - var script = document.createElement("script"); + return new Promise((resolve, reject) => { + const script = document.createElement("script"); script.onload = resolve; - script.onerror = reject; + script.onerror = () => { reject("Failed to load " + fname); }; document.body.appendChild(script); script.src = "../recordings/" + fname; }); } function enableUI() { - var iterations = WebUtil.getQueryVar('iterations', 3); + const iterations = WebUtil.getQueryVar('iterations', 3); document.getElementById('iterations').value = iterations; - var mode = WebUtil.getQueryVar('mode', 3); + const mode = WebUtil.getQueryVar('mode', 3); if (mode === 'realtime') { document.getElementById('mode2').checked = true; } else { document.getElementById('mode1').checked = true; } - message("VNC_frame_data.length: " + VNC_frame_data.length); + /* eslint-disable-next-line camelcase */ + message("Loaded " + VNC_frame_data.length + " frames"); const startButton = document.getElementById('startButton'); startButton.disabled = false; startButton.addEventListener('click', start); + message("Converting..."); + + /* eslint-disable-next-line camelcase */ frames = VNC_frame_data; - // Only present in older recordings - if (window.VNC_frame_encoding) + + let encoding; + + /* eslint-disable camelcase */ + if (window.VNC_frame_encoding) { + // Only present in older recordings encoding = VNC_frame_encoding; -} + /* eslint-enable camelcase */ + } else { + let frame = frames[0]; + let start = frame.indexOf('{', 1) + 1; + if (frame.slice(start, start+4) === 'UkZC') { + encoding = 'base64'; + } else { + encoding = 'binary'; + } + } -function IterationPlayer (iterations, frames, encoding) { - this._iterations = iterations; + for (let i = 0;i < frames.length;i++) { + let frame = frames[i]; - this._iteration = undefined; - this._player = undefined; + if (frame === "EOF") { + frames.splice(i); + break; + } - this._start_time = undefined; + let dataIdx = frame.indexOf('{', 1) + 1; - this._frames = frames; - this._encoding = encoding; + let time = parseInt(frame.slice(1, dataIdx - 1)); - this._state = 'running'; + let u8; + if (encoding === 'base64') { + u8 = Base64.decode(frame.slice(dataIdx)); + } else { + u8 = new Uint8Array(frame.length - dataIdx); + for (let j = 0; j < frame.length - dataIdx; j++) { + u8[j] = frame.charCodeAt(dataIdx + j); + } + } - this.onfinish = function() {}; - this.oniterationfinish = function() {}; - this.rfbdisconnected = function() {}; + frames[i] = { fromClient: frame[0] === '}', + timestamp: time, + data: u8 }; + } + + message("Ready"); } -IterationPlayer.prototype = { - start: function (mode) { +class IterationPlayer { + constructor(iterations, frames) { + this._iterations = iterations; + + this._iteration = undefined; + this._player = undefined; + + this._startTime = undefined; + + this._frames = frames; + + this._state = 'running'; + + this.onfinish = () => {}; + this.oniterationfinish = () => {}; + this.rfbdisconnected = () => {}; + } + + start(realtime) { this._iteration = 0; - this._start_time = (new Date()).getTime(); + this._startTime = (new Date()).getTime(); - this._realtime = mode.startsWith('realtime'); - this._trafficMgmt = !mode.endsWith('-no-mgmt'); + this._realtime = realtime; this._nextIteration(); - }, + } - _nextIteration: function () { - const player = new RecordingPlayer(this._frames, this._encoding, this._disconnected.bind(this)); + _nextIteration() { + const player = new RecordingPlayer(this._frames, this._disconnected.bind(this)); player.onfinish = this._iterationFinish.bind(this); if (this._state !== 'running') { return; } @@ -93,40 +139,43 @@ IterationPlayer.prototype = { return; } - player.run(this._realtime, this._trafficMgmt); - }, + player.run(this._realtime, false); + } - _finish: function () { + _finish() { const endTime = (new Date()).getTime(); - const totalDuration = endTime - this._start_time; + const totalDuration = endTime - this._startTime; - const evt = new Event('finish'); - evt.duration = totalDuration; - evt.iterations = this._iterations; + const evt = new CustomEvent('finish', + { detail: + { duration: totalDuration, + iterations: this._iterations } } ); this.onfinish(evt); - }, + } - _iterationFinish: function (duration) { - const evt = new Event('iterationfinish'); - evt.duration = duration; - evt.number = this._iteration; + _iterationFinish(duration) { + const evt = new CustomEvent('iterationfinish', + { detail: + { duration: duration, + number: this._iteration } } ); this.oniterationfinish(evt); this._nextIteration(); - }, + } - _disconnected: function (rfb, clean, frame) { + _disconnected(clean, frame) { if (!clean) { this._state = 'failed'; } - var evt = new Event('rfbdisconnected'); - evt.clean = clean; - evt.frame = frame; - + const evt = new CustomEvent('rfbdisconnected', + { detail: + { clean: clean, + frame: frame, + iteration: this._iteration } } ); this.onrfbdisconnected(evt); - }, -}; + } +} function start() { document.getElementById('startButton').value = "Running"; @@ -134,33 +183,36 @@ function start() { const iterations = document.getElementById('iterations').value; - var mode; + let realtime; if (document.getElementById('mode1').checked) { message(`Starting performance playback (fullspeed) [${iterations} iteration(s)]`); - mode = 'perftest'; + realtime = false; } else { message(`Starting realtime playback [${iterations} iteration(s)]`); - mode = 'realtime'; + realtime = true; } - const player = new IterationPlayer(iterations, frames, encoding); - player.oniterationfinish = function (evt) { - message(`Iteration ${evt.number} took ${evt.duration}ms`); + const player = new IterationPlayer(iterations, frames); + player.oniterationfinish = (evt) => { + message(`Iteration ${evt.detail.number} took ${evt.detail.duration}ms`); }; - player.onrfbdisconnected = function (evt) { - if (evt.reason) { - message(`noVNC sent disconnected during iteration ${evt.iteration} frame ${evt.frame}`); + player.onrfbdisconnected = (evt) => { + if (!evt.detail.clean) { + message(`noVNC sent disconnected during iteration ${evt.detail.iteration} frame ${evt.detail.frame}`); + + document.getElementById('startButton').disabled = false; + document.getElementById('startButton').value = "Start"; } }; - player.onfinish = function (evt) { - const iterTime = parseInt(evt.duration / evt.iterations, 10); - message(`${evt.iterations} iterations took ${evt.duration}ms (average ${iterTime}ms / iteration)`); + player.onfinish = (evt) => { + const iterTime = parseInt(evt.detail.duration / evt.detail.iterations, 10); + message(`${evt.detail.iterations} iterations took ${evt.detail.duration}ms (average ${iterTime}ms / iteration)`); document.getElementById('startButton').disabled = false; document.getElementById('startButton').value = "Start"; }; - player.start(mode); + player.start(realtime); } -loadFile().then(enableUI).catch(function (e) { message("Error loading recording: " + e); }); +loadFile().then(enableUI).catch(e => message("Error loading recording: " + e)); diff --git a/tests/playback.js b/tests/playback.js index c769e88fc..955df0ee3 100644 --- a/tests/playback.js +++ b/tests/playback.js @@ -1,38 +1,37 @@ /* * noVNC: HTML5 VNC client - * Copyright (C) 2012 Joel Martin + * Copyright (C) 2018 The noVNC Authors * Licensed under MPL 2.0 (see LICENSE.txt) */ import RFB from '../core/rfb.js'; import * as Log from '../core/util/logging.js'; -import Base64 from '../core/base64.js'; // Immediate polyfill -if (setImmediate === undefined) { - var _immediateIdCounter = 1; - var _immediateFuncs = {}; +if (window.setImmediate === undefined) { + let _immediateIdCounter = 1; + const _immediateFuncs = {}; - var setImmediate = function (func) { - var index = _immediateIdCounter++; + window.setImmediate = (func) => { + const index = _immediateIdCounter++; _immediateFuncs[index] = func; window.postMessage("noVNC immediate trigger:" + index, "*"); return index; }; - window.clearImmediate = function (id) { + window.clearImmediate = (id) => { _immediateFuncs[id]; }; - var _onMessage = function (event) { + window.addEventListener("message", (event) => { if ((typeof event.data !== "string") || (event.data.indexOf("noVNC immediate trigger:") !== 0)) { return; } - var index = event.data.slice("noVNC immediate trigger:".length); + const index = event.data.slice("noVNC immediate trigger:".length); - var callback = _immediateFuncs[index]; + const callback = _immediateFuncs[index]; if (callback === undefined) { return; } @@ -40,155 +39,133 @@ if (setImmediate === undefined) { delete _immediateFuncs[index]; callback(); - }; - window.addEventListener("message", _onMessage); + }); } -export default function RecordingPlayer (frames, encoding, disconnected) { - this._frames = frames; - this._encoding = encoding; +class FakeWebSocket { + constructor() { + this.binaryType = "arraybuffer"; + this.protocol = ""; + this.readyState = "open"; - this._disconnected = disconnected; + this.onerror = () => {}; + this.onmessage = () => {}; + this.onopen = () => {}; + } - if (this._encoding === undefined) { - let frame = this._frames[0]; - let start = frame.indexOf('{', 1) + 1; - if (frame.slice(start).startsWith('UkZC')) { - this._encoding = 'base64'; - } else { - this._encoding = 'binary'; - } + send() { } - this._rfb = undefined; - this._frame_length = this._frames.length; + close() { + } +} - this._frame_index = 0; - this._start_time = undefined; - this._realtime = true; - this._trafficManagement = true; +export default class RecordingPlayer { + constructor(frames, disconnected) { + this._frames = frames; - this._running = false; + this._disconnected = disconnected; - this.onfinish = function () {}; -} + this._rfb = undefined; + this._frameLength = this._frames.length; -RecordingPlayer.prototype = { - run: function (realtime, trafficManagement) { + this._frameIndex = 0; + this._startTime = undefined; + this._realtime = true; + this._trafficManagement = true; + + this._running = false; + + this.onfinish = () => {}; + } + + run(realtime, trafficManagement) { // initialize a new RFB - this._rfb = new RFB(document.getElementById('VNC_canvas'), 'wss://test'); + this._ws = new FakeWebSocket(); + this._rfb = new RFB(document.getElementById('VNC_screen'), this._ws); this._rfb.viewOnly = true; this._rfb.addEventListener("disconnect", this._handleDisconnect.bind(this)); - this._enablePlaybackMode(); + this._rfb.addEventListener("credentialsrequired", + this._handleCredentials.bind(this)); // reset the frame index and timer - this._frame_index = 0; - this._start_time = (new Date()).getTime(); + this._frameIndex = 0; + this._startTime = (new Date()).getTime(); this._realtime = realtime; this._trafficManagement = (trafficManagement === undefined) ? !realtime : trafficManagement; this._running = true; - this._queueNextPacket(); - }, - - // _enablePlaybackMode mocks out things not required for running playback - _enablePlaybackMode: function () { - this._rfb._sock.send = function (arr) {}; - this._rfb._sock.close = function () {}; - this._rfb._sock.flush = function () {}; - this._rfb._checkEvents = function () {}; - this._rfb._connect = function () { - this._sock.init('binary', 'ws'); - }; - }, - - _queueNextPacket: function () { + } + + _queueNextPacket() { if (!this._running) { return; } - var frame = this._frames[this._frame_index]; + let frame = this._frames[this._frameIndex]; // skip send frames - while (this._frame_index < this._frame_length && frame.charAt(0) === "}") { - this._frame_index++; - frame = this._frames[this._frame_index]; + while (this._frameIndex < this._frameLength && frame.fromClient) { + this._frameIndex++; + frame = this._frames[this._frameIndex]; } - if (frame === 'EOF') { - Log.Debug('Finished, found EOF'); - this._finish(); - return; - } - - if (this._frame_index >= this._frame_length) { + if (this._frameIndex >= this._frameLength) { Log.Debug('Finished, no more frames'); this._finish(); return; } if (this._realtime) { - let foffset = frame.slice(1, frame.indexOf('{', 1)); - let toffset = (new Date()).getTime() - this._start_time; - let delay = foffset - toffset; + const toffset = (new Date()).getTime() - this._startTime; + let delay = frame.timestamp - toffset; if (delay < 1) delay = 1; setTimeout(this._doPacket.bind(this), delay); } else { setImmediate(this._doPacket.bind(this)); } - }, + } - _doPacket: function () { + _doPacket() { // Avoid having excessive queue buildup in non-realtime mode if (this._trafficManagement && this._rfb._flushing) { - let player = this; - let orig = this._rfb._display.onflush; - this._rfb._display.onflush = function () { - player._rfb._display.onflush = orig; - player._rfb._onFlush(); - player._doPacket(); - }; + this._rfb.flush() + .then(() => { + this._doPacket(); + }); return; } - const frame = this._frames[this._frame_index]; - var start = frame.indexOf('{', 1) + 1; - if (this._encoding === 'base64') { - var u8 = Base64.decode(frame.slice(start)); - start = 0; - } else { - var u8 = new Uint8Array(frame.length - start); - for (let i = 0; i < frame.length - start; i++) { - u8[i] = frame.charCodeAt(start + i); - } - } + const frame = this._frames[this._frameIndex]; - this._rfb._sock._recv_message({'data': u8}); - this._frame_index++; + this._ws.onmessage({'data': frame.data}); + this._frameIndex++; this._queueNextPacket(); - }, + } _finish() { if (this._rfb._display.pending()) { - var player = this; - this._rfb._display.onflush = function () { - if (player._rfb._flushing) { - player._rfb._onFlush(); - } - player._finish(); - }; - this._rfb._display.flush(); + this._rfb._display.flush() + .then(() => { this._finish(); }); } else { this._running = false; - this.onfinish((new Date()).getTime() - this._start_time); + this._ws.onclose({code: 1000, reason: ""}); + delete this._rfb; + this.onfinish((new Date()).getTime() - this._startTime); } - }, + } - _handleDisconnect(rfb, clean) { + _handleDisconnect(evt) { this._running = false; - this._disconnected(rfb, clean, this._frame_index); + this._disconnected(evt.detail.clean, this._frameIndex); } -}; + + _handleCredentials(evt) { + this._rfb.sendCredentials({"username": "Foo", + "password": "Bar", + "target": "Baz"}); + } +} diff --git a/tests/test.base64.js b/tests/test.base64.js index cfee409c8..04bd207b7 100644 --- a/tests/test.base64.js +++ b/tests/test.base64.js @@ -1,34 +1,33 @@ -var assert = chai.assert; -var expect = chai.expect; +const expect = chai.expect; import Base64 from '../core/base64.js'; -describe('Base64 Tools', function() { +describe('Base64 Tools', function () { "use strict"; - var BIN_ARR = new Array(256); - for (var i = 0; i < 256; i++) { + const BIN_ARR = new Array(256); + for (let i = 0; i < 256; i++) { BIN_ARR[i] = i; } - var B64_STR = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="; + const B64_STR = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="; - describe('encode', function() { - it('should encode a binary string into Base64', function() { - var encoded = Base64.encode(BIN_ARR); + describe('encode', function () { + it('should encode a binary string into Base64', function () { + const encoded = Base64.encode(BIN_ARR); expect(encoded).to.equal(B64_STR); }); }); - describe('decode', function() { - it('should decode a Base64 string into a normal string', function() { - var decoded = Base64.decode(B64_STR); + describe('decode', function () { + it('should decode a Base64 string into a normal string', function () { + const decoded = Base64.decode(B64_STR); expect(decoded).to.deep.equal(BIN_ARR); }); - it('should throw an error if we have extra characters at the end of the string', function() { - expect(function () { Base64.decode(B64_STR+'abcdef'); }).to.throw(Error); + it('should throw an error if we have extra characters at the end of the string', function () { + expect(() => Base64.decode(B64_STR+'abcdef')).to.throw(Error); }); }); }); diff --git a/tests/test.browser.js b/tests/test.browser.js new file mode 100644 index 000000000..3b2299f63 --- /dev/null +++ b/tests/test.browser.js @@ -0,0 +1,244 @@ +/* eslint-disable no-console */ +const expect = chai.expect; + +import { isMac, isWindows, isIOS, isAndroid, isChromeOS, + isSafari, isFirefox, isChrome, isChromium, isOpera, isEdge, + isGecko, isWebKit, isBlink } from '../core/util/browser.js'; + +describe('OS detection', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + }); + + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + }); + + it('should handle macOS', function () { + const platforms = [ + "MacIntel", + "MacPPC", + ]; + + navigator.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15"; + platforms.forEach((platform) => { + navigator.platform = platform; + expect(isMac()).to.be.true; + expect(isWindows()).to.be.false; + expect(isIOS()).to.be.false; + expect(isAndroid()).to.be.false; + expect(isChromeOS()).to.be.false; + }); + }); + + it('should handle Windows', function () { + const platforms = [ + "Win32", + "Win64", + ]; + + navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"; + platforms.forEach((platform) => { + navigator.platform = platform; + expect(isMac()).to.be.false; + expect(isWindows()).to.be.true; + expect(isIOS()).to.be.false; + expect(isAndroid()).to.be.false; + expect(isChromeOS()).to.be.false; + }); + }); + + it('should handle iOS', function () { + const platforms = [ + "iPhone", + "iPod", + "iPad", + ]; + + navigator.userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Mobile/15E148 Safari/604.1"; + platforms.forEach((platform) => { + navigator.platform = platform; + expect(isMac()).to.be.false; + expect(isWindows()).to.be.false; + expect(isIOS()).to.be.true; + expect(isAndroid()).to.be.false; + expect(isChromeOS()).to.be.false; + }); + }); + + it('should handle Android', function () { + let userAgents = [ + "Mozilla/5.0 (Linux; Android 13; SM-G960U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.128 Mobile Safari/537.36", + "Mozilla/5.0 (Android 13; Mobile; LG-M255; rv:108.0) Gecko/108.0 Firefox/108.0", + ]; + + navigator.platform = "Linux x86_64"; + userAgents.forEach((ua) => { + navigator.userAgent = ua; + expect(isMac()).to.be.false; + expect(isWindows()).to.be.false; + expect(isIOS()).to.be.false; + expect(isAndroid()).to.be.true; + expect(isChromeOS()).to.be.false; + }); + }); + + it('should handle ChromeOS', function () { + let userAgents = [ + "Mozilla/5.0 (X11; CrOS x86_64 15183.59.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.75 Safari/537.36", + "Mozilla/5.0 (X11; CrOS aarch64 15183.59.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.75 Safari/537.36", + ]; + + navigator.platform = "Linux x86_64"; + userAgents.forEach((ua) => { + navigator.userAgent = ua; + expect(isMac()).to.be.false; + expect(isWindows()).to.be.false; + expect(isIOS()).to.be.false; + expect(isAndroid()).to.be.false; + expect(isChromeOS()).to.be.true; + }); + }); +}); + +describe('Browser detection', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + }); + + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + }); + + it('should handle Chrome', function () { + navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.true; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.false; + expect(isWebKit()).to.be.false; + expect(isBlink()).to.be.true; + }); + + it('should handle Chromium', function () { + navigator.userAgent = "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Raspbian Chromium/74.0.3729.157 Chrome/74.0.3729.157 Safari/537.36"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.true; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.false; + expect(isWebKit()).to.be.false; + expect(isBlink()).to.be.true; + }); + + it('should handle Firefox', function () { + navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.true; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.true; + expect(isWebKit()).to.be.false; + expect(isBlink()).to.be.false; + }); + + it('should handle Seamonkey', function () { + navigator.userAgent = "Mozilla/5.0 (Windows NT 6.1; rv:36.0) Gecko/20100101 Firefox/36.0 Seamonkey/2.33.1"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.true; + expect(isWebKit()).to.be.false; + expect(isBlink()).to.be.false; + }); + + it('should handle Safari', function () { + navigator.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15"; + + expect(isSafari()).to.be.true; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.false; + expect(isWebKit()).to.be.true; + expect(isBlink()).to.be.false; + }); + + it('should handle Edge', function () { + navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.34"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.true; + + expect(isGecko()).to.be.false; + expect(isWebKit()).to.be.false; + expect(isBlink()).to.be.true; + }); + + it('should handle Opera', function () { + navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 OPR/91.0.4516.20"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.true; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.false; + expect(isWebKit()).to.be.false; + expect(isBlink()).to.be.true; + }); + + it('should handle Epiphany', function () { + navigator.userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Safari/605.1.15 Epiphany/605.1.15"; + + expect(isSafari()).to.be.false; + expect(isFirefox()).to.be.false; + expect(isChrome()).to.be.false; + expect(isChromium()).to.be.false; + expect(isOpera()).to.be.false; + expect(isEdge()).to.be.false; + + expect(isGecko()).to.be.false; + expect(isWebKit()).to.be.true; + expect(isBlink()).to.be.false; + }); +}); diff --git a/tests/test.copyrect.js b/tests/test.copyrect.js new file mode 100644 index 000000000..a10cddce7 --- /dev/null +++ b/tests/test.copyrect.js @@ -0,0 +1,92 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import CopyRectDecoder from '../core/decoders/copyrect.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +describe('CopyRect Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new CopyRectDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle the CopyRect encoding', function () { + // seed some initial data to copy + display.fillRect(0, 0, 4, 4, [ 0x11, 0x22, 0x33 ]); + display.fillRect(0, 0, 2, 2, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done; + done = testDecodeRect(decoder, 0, 2, 2, 2, + [0x00, 0x02, 0x00, 0x00], + display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 2, 2, 2, + [0x00, 0x00, 0x00, 0x00], + display, 24); + expect(done).to.be.true; + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(display).to.have.displayed(targetData); + }); + + it('should handle empty rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, + [0x00, 0x00, 0x00, 0x00], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); +}); diff --git a/tests/test.deflator.js b/tests/test.deflator.js new file mode 100644 index 000000000..12e8a46bf --- /dev/null +++ b/tests/test.deflator.js @@ -0,0 +1,82 @@ +/* eslint-disable no-console */ +const expect = chai.expect; + +import { inflateInit, inflate } from "../vendor/pako/lib/zlib/inflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; +import Deflator from "../core/deflator.js"; + +function _inflator(compText, expected) { + let strm = new ZStream(); + let chunkSize = 1024 * 10 * 10; + strm.output = new Uint8Array(chunkSize); + + inflateInit(strm, 5); + + if (expected > chunkSize) { + chunkSize = expected; + strm.output = new Uint8Array(chunkSize); + } + + /* eslint-disable camelcase */ + strm.input = compText; + strm.avail_in = strm.input.length; + strm.next_in = 0; + + strm.next_out = 0; + strm.avail_out = expected.length; + /* eslint-enable camelcase */ + + let ret = inflate(strm, 0); + + // Check that return code is not an error + expect(ret).to.be.greaterThan(-1); + + return new Uint8Array(strm.output.buffer, 0, strm.next_out); +} + +describe('Deflate data', function () { + + it('should be able to deflate messages', function () { + let deflator = new Deflator(); + + let text = "123asdf"; + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = deflator.deflate(preText); + + let inflatedText = _inflator(compText, text.length); + expect(inflatedText).to.array.equal(preText); + + }); + + it('should be able to deflate large messages', function () { + let deflator = new Deflator(); + + /* Generate a big string with random characters. Used because + repetition of letters might be deflated more effectively than + random ones. */ + let text = ""; + let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < 300000; i++) { + text += characters.charAt(Math.floor(Math.random() * characters.length)); + } + + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = deflator.deflate(preText); + + //Check that the compressed size is expected size + expect(compText.length).to.be.greaterThan((1024 * 10 * 10) * 2); + + let inflatedText = _inflator(compText, text.length); + + expect(inflatedText).to.array.equal(preText); + + }); +}); diff --git a/tests/test.display.js b/tests/test.display.js index b8e9b51f5..e6c0406f9 100644 --- a/tests/test.display.js +++ b/tests/test.display.js @@ -1,43 +1,37 @@ -/* jshint expr: true */ -var expect = chai.expect; +const expect = chai.expect; import Base64 from '../core/base64.js'; import Display from '../core/display.js'; -import sinon from '../vendor/sinon.js'; - describe('Display/Canvas Helper', function () { - var checked_data = [ + const checkedData = new Uint8ClampedArray([ 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 - ]; - checked_data = new Uint8Array(checked_data); - - var basic_data = [0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]; - basic_data = new Uint8Array(basic_data); - - function make_image_canvas (input_data) { - var canvas = document.createElement('canvas'); - canvas.width = 4; - canvas.height = 4; - var ctx = canvas.getContext('2d'); - var data = ctx.createImageData(4, 4); - for (var i = 0; i < checked_data.length; i++) { data.data[i] = input_data[i]; } + ]); + + const basicData = new Uint8ClampedArray([0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]); + + function makeImageCanvas(inputData, width, height) { + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const ctx = canvas.getContext('2d'); + const data = new ImageData(inputData, width, height); ctx.putImageData(data, 0, 0); return canvas; } - function make_image_png (input_data) { - var canvas = make_image_canvas(input_data); - var url = canvas.toDataURL(); - var data = url.split(",")[1]; + function makeImagePng(inputData, width, height) { + const canvas = makeImageCanvas(inputData, width, height); + const url = canvas.toDataURL(); + const data = url.split(",")[1]; return Base64.decode(data); } describe('viewport handling', function () { - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.clipViewport = true; @@ -49,23 +43,22 @@ describe('Display/Canvas Helper', function () { it('should take viewport location into consideration when drawing images', function () { display.resize(4, 4); display.viewportChangeSize(2, 2); - display.drawImage(make_image_canvas(basic_data), 1, 1); + display.drawImage(makeImageCanvas(basicData, 4, 1), 1, 1); display.flip(); - var expected = new Uint8Array(16); - var i; - for (i = 0; i < 8; i++) { expected[i] = basic_data[i]; } - for (i = 8; i < 16; i++) { expected[i] = 0; } + const expected = new Uint8Array(16); + for (let i = 0; i < 8; i++) { expected[i] = basicData[i]; } + for (let i = 8; i < 16; i++) { expected[i] = 0; } expect(display).to.have.displayed(expected); }); - it('should resize the target canvas when resizing the viewport', function() { + it('should resize the target canvas when resizing the viewport', function () { display.viewportChangeSize(2, 2); expect(display._target.width).to.equal(2); expect(display._target.height).to.equal(2); }); - it('should move the viewport if necessary', function() { + it('should move the viewport if necessary', function () { display.viewportChangeSize(5, 5); expect(display.absX(0)).to.equal(0); expect(display.absY(0)).to.equal(0); @@ -73,7 +66,7 @@ describe('Display/Canvas Helper', function () { expect(display._target.height).to.equal(5); }); - it('should limit the viewport to the framebuffer size', function() { + it('should limit the viewport to the framebuffer size', function () { display.viewportChangeSize(6, 6); expect(display._target.width).to.equal(5); expect(display._target.height).to.equal(5); @@ -91,16 +84,7 @@ describe('Display/Canvas Helper', function () { expect(display.flip).to.have.been.calledOnce; }); - it('should report clipping when framebuffer > viewport', function () { - expect(display.isClipped).to.be.true; - }); - - it('should report not clipping when framebuffer = viewport', function () { - display.viewportChangeSize(5, 5); - expect(display.isClipped).to.be.false; - }); - - it('should show the entire framebuffer when disabling the viewport', function() { + it('should show the entire framebuffer when disabling the viewport', function () { display.clipViewport = false; expect(display.absX(0)).to.equal(0); expect(display.absY(0)).to.equal(0); @@ -108,7 +92,7 @@ describe('Display/Canvas Helper', function () { expect(display._target.height).to.equal(5); }); - it('should ignore viewport changes when the viewport is disabled', function() { + it('should ignore viewport changes when the viewport is disabled', function () { display.clipViewport = false; display.viewportChangeSize(2, 2); display.viewportChangePos(1, 1); @@ -118,7 +102,7 @@ describe('Display/Canvas Helper', function () { expect(display._target.height).to.equal(5); }); - it('should show the entire framebuffer just after enabling the viewport', function() { + it('should show the entire framebuffer just after enabling the viewport', function () { display.clipViewport = false; display.clipViewport = true; expect(display.absX(0)).to.equal(0); @@ -129,7 +113,7 @@ describe('Display/Canvas Helper', function () { }); describe('resizing', function () { - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.clipViewport = false; @@ -138,16 +122,16 @@ describe('Display/Canvas Helper', function () { it('should change the size of the logical canvas', function () { display.resize(5, 7); - expect(display._fb_width).to.equal(5); - expect(display._fb_height).to.equal(7); + expect(display._fbWidth).to.equal(5); + expect(display._fbHeight).to.equal(7); }); it('should keep the framebuffer data', function () { - display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); + display.fillRect(0, 0, 4, 4, [0xff, 0, 0]); display.resize(2, 2); display.flip(); - var expected = []; - for (var i = 0; i < 4 * 2*2; i += 4) { + const expected = []; + for (let i = 0; i < 4 * 2*2; i += 4) { expected[i] = 0xff; expected[i+1] = expected[i+2] = 0; expected[i+3] = 0xff; @@ -189,8 +173,8 @@ describe('Display/Canvas Helper', function () { }); describe('rescaling', function () { - var display; - var canvas; + let display; + let canvas; beforeEach(function () { canvas = document.createElement('canvas'); @@ -230,14 +214,15 @@ describe('Display/Canvas Helper', function () { }); describe('autoscaling', function () { - var display; - var canvas; + let display; + let canvas; beforeEach(function () { canvas = document.createElement('canvas'); display = new Display(canvas); display.clipViewport = true; display.resize(4, 3); + display.viewportChangeSize(4, 3); document.body.appendChild(canvas); }); @@ -278,40 +263,18 @@ describe('Display/Canvas Helper', function () { // TODO(directxman12): improve the tests for each of the drawing functions to cover more than just the // basic cases - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.resize(4, 4); }); - it('should clear the screen on #clear without a logo set', function () { - display.fillRect(0, 0, 4, 4, [0x00, 0x00, 0xff]); - display._logo = null; - display.clear(); - display.resize(4, 4); - var empty = []; - for (var i = 0; i < 4 * display._fb_width * display._fb_height; i++) { empty[i] = 0; } - expect(display).to.have.displayed(new Uint8Array(empty)); - }); - - it('should draw the logo on #clear with a logo set', function (done) { - display._logo = { width: 4, height: 4, type: "image/png", data: make_image_png(checked_data) }; - display.clear(); - display.onflush = function () { - expect(display).to.have.displayed(checked_data); - expect(display._fb_width).to.equal(4); - expect(display._fb_height).to.equal(4); - done(); - }; - display.flush(); - }); - it('should not draw directly on the target canvas', function () { - display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); + display.fillRect(0, 0, 4, 4, [0xff, 0, 0]); display.flip(); display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - var expected = []; - for (var i = 0; i < 4 * display._fb_width * display._fb_height; i += 4) { + const expected = []; + for (let i = 0; i < 4 * display._fbWidth * display._fbHeight; i += 4) { expected[i] = 0xff; expected[i+1] = expected[i+2] = 0; expected[i+3] = 0xff; @@ -321,153 +284,110 @@ describe('Display/Canvas Helper', function () { it('should support filling a rectangle with particular color via #fillRect', function () { display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - display.fillRect(0, 0, 2, 2, [0xff, 0, 0]); - display.fillRect(2, 2, 2, 2, [0xff, 0, 0]); + display.fillRect(0, 0, 2, 2, [0, 0, 0xff]); + display.fillRect(2, 2, 2, 2, [0, 0, 0xff]); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); it('should support copying an portion of the canvas via #copyImage', function () { display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - display.fillRect(0, 0, 2, 2, [0xff, 0, 0x00]); + display.fillRect(0, 0, 2, 2, [0, 0, 0xff]); display.copyImage(0, 0, 2, 2, 2, 2); display.flip(); - expect(display).to.have.displayed(checked_data); - }); - - it('should support drawing images via #imageRect', function (done) { - display.imageRect(0, 0, "image/png", make_image_png(checked_data)); - display.flip(); - display.onflush = function () { - expect(display).to.have.displayed(checked_data); - done(); - }; - display.flush(); - }); - - it('should support drawing tile data with a background color and sub tiles', function () { - display.startTile(0, 0, 4, 4, [0, 0xff, 0]); - display.subTile(0, 0, 2, 2, [0xff, 0, 0]); - display.subTile(2, 2, 2, 2, [0xff, 0, 0]); - display.finishTile(); - display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); - it('should support drawing BGRX blit images with true color via #blitImage', function () { - var data = []; - for (var i = 0; i < 16; i++) { - data[i * 4] = checked_data[i * 4 + 2]; - data[i * 4 + 1] = checked_data[i * 4 + 1]; - data[i * 4 + 2] = checked_data[i * 4]; - data[i * 4 + 3] = checked_data[i * 4 + 3]; - } - display.blitImage(0, 0, 4, 4, data, 0); + it('should support drawing images via #imageRect', async function () { + display.imageRect(0, 0, 4, 4, "image/png", makeImagePng(checkedData, 4, 4)); display.flip(); - expect(display).to.have.displayed(checked_data); + await display.flush(); + expect(display).to.have.displayed(checkedData); }); - it('should support drawing RGB blit images with true color via #blitRgbImage', function () { - var data = []; - for (var i = 0; i < 16; i++) { - data[i * 3] = checked_data[i * 4]; - data[i * 3 + 1] = checked_data[i * 4 + 1]; - data[i * 3 + 2] = checked_data[i * 4 + 2]; - } - display.blitRgbImage(0, 0, 4, 4, data, 0); + it('should support blit images with true color via #blitImage', function () { + display.blitImage(0, 0, 4, 4, checkedData, 0); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); it('should support drawing an image object via #drawImage', function () { - var img = make_image_canvas(checked_data); + const img = makeImageCanvas(checkedData, 4, 4); display.drawImage(img, 0, 0); display.flip(); - expect(display).to.have.displayed(checked_data); + expect(display).to.have.displayed(checkedData); }); }); describe('the render queue processor', function () { - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.resize(4, 4); - sinon.spy(display, '_scan_renderQ'); - }); - - afterEach(function () { - window.requestAnimationFrame = this.old_requestAnimationFrame; + sinon.spy(display, '_scanRenderQ'); }); it('should try to process an item when it is pushed on, if nothing else is on the queue', function () { - display._renderQ_push({ type: 'noop' }); // does nothing - expect(display._scan_renderQ).to.have.been.calledOnce; + display._renderQPush({ type: 'noop' }); // does nothing + expect(display._scanRenderQ).to.have.been.calledOnce; }); it('should not try to process an item when it is pushed on if we are waiting for other items', function () { display._renderQ.length = 2; - display._renderQ_push({ type: 'noop' }); - expect(display._scan_renderQ).to.not.have.been.called; + display._renderQPush({ type: 'noop' }); + expect(display._scanRenderQ).to.not.have.been.called; }); it('should wait until an image is loaded to attempt to draw it and the rest of the queue', function () { - var img = { complete: false, addEventListener: sinon.spy() } - display._renderQ = [{ type: 'img', x: 3, y: 4, img: img }, + const img = { complete: false, width: 4, height: 4, addEventListener: sinon.spy() }; + display._renderQ = [{ type: 'img', x: 3, y: 4, width: 4, height: 4, img: img }, { type: 'fill', x: 1, y: 2, width: 3, height: 4, color: 5 }]; display.drawImage = sinon.spy(); display.fillRect = sinon.spy(); - display._scan_renderQ(); + display._scanRenderQ(); expect(display.drawImage).to.not.have.been.called; expect(display.fillRect).to.not.have.been.called; expect(img.addEventListener).to.have.been.calledOnce; display._renderQ[0].img.complete = true; - display._scan_renderQ(); + display._scanRenderQ(); expect(display.drawImage).to.have.been.calledOnce; expect(display.fillRect).to.have.been.calledOnce; expect(img.addEventListener).to.have.been.calledOnce; }); - it('should call callback when queue is flushed', function () { - display.onflush = sinon.spy(); + it('should resolve promise when queue is flushed', async function () { display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - expect(display.onflush).to.not.have.been.called; - display.flush(); - expect(display.onflush).to.have.been.calledOnce; + let promise = display.flush(); + expect(promise).to.be.an.instanceOf(Promise); + await promise; }); it('should draw a blit image on type "blit"', function () { display.blitImage = sinon.spy(); - display._renderQ_push({ type: 'blit', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); + display._renderQPush({ type: 'blit', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); expect(display.blitImage).to.have.been.calledOnce; expect(display.blitImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0); }); - it('should draw a blit RGB image on type "blitRgb"', function () { - display.blitRgbImage = sinon.spy(); - display._renderQ_push({ type: 'blitRgb', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] }); - expect(display.blitRgbImage).to.have.been.calledOnce; - expect(display.blitRgbImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0); - }); - it('should copy a region on type "copy"', function () { display.copyImage = sinon.spy(); - display._renderQ_push({ type: 'copy', x: 3, y: 4, width: 5, height: 6, old_x: 7, old_y: 8 }); + display._renderQPush({ type: 'copy', x: 3, y: 4, width: 5, height: 6, oldX: 7, oldY: 8 }); expect(display.copyImage).to.have.been.calledOnce; expect(display.copyImage).to.have.been.calledWith(7, 8, 3, 4, 5, 6); }); it('should fill a rect with a given color on type "fill"', function () { display.fillRect = sinon.spy(); - display._renderQ_push({ type: 'fill', x: 3, y: 4, width: 5, height: 6, color: [7, 8, 9]}); + display._renderQPush({ type: 'fill', x: 3, y: 4, width: 5, height: 6, color: [7, 8, 9]}); expect(display.fillRect).to.have.been.calledOnce; expect(display.fillRect).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9]); }); it('should draw an image from an image object on type "img" (if complete)', function () { display.drawImage = sinon.spy(); - display._renderQ_push({ type: 'img', x: 3, y: 4, img: { complete: true } }); + display._renderQPush({ type: 'img', x: 3, y: 4, img: { complete: true } }); expect(display.drawImage).to.have.been.calledOnce; expect(display.drawImage).to.have.been.calledWith({ complete: true }, 3, 4); }); diff --git a/tests/test.gesturehandler.js b/tests/test.gesturehandler.js new file mode 100644 index 000000000..73356be36 --- /dev/null +++ b/tests/test.gesturehandler.js @@ -0,0 +1,1026 @@ +const expect = chai.expect; + +import EventTargetMixin from '../core/util/eventtarget.js'; + +import GestureHandler from '../core/input/gesturehandler.js'; + +class DummyTarget extends EventTargetMixin { +} + +describe('Gesture handler', function () { + let target, handler; + let gestures; + let clock; + let touches; + + before(function () { + clock = sinon.useFakeTimers(); + }); + + after(function () { + clock.restore(); + }); + + beforeEach(function () { + target = new DummyTarget(); + gestures = sinon.spy(); + target.addEventListener('gesturestart', gestures); + target.addEventListener('gesturemove', gestures); + target.addEventListener('gestureend', gestures); + touches = []; + handler = new GestureHandler(); + handler.attach(target); + }); + + afterEach(function () { + if (handler) { + handler.detach(); + } + target = null; + gestures = null; + }); + + function touchStart(id, x, y) { + let touch = { identifier: id, + clientX: x, clientY: y }; + touches.push(touch); + let ev = { type: 'touchstart', + touches: touches, + targetTouches: touches, + changedTouches: [ touch ], + stopPropagation: sinon.spy(), + preventDefault: sinon.spy() }; + target.dispatchEvent(ev); + } + + function touchMove(id, x, y) { + let touch = touches.find(t => t.identifier === id); + touch.clientX = x; + touch.clientY = y; + let ev = { type: 'touchmove', + touches: touches, + targetTouches: touches, + changedTouches: [ touch ], + stopPropagation: sinon.spy(), + preventDefault: sinon.spy() }; + target.dispatchEvent(ev); + } + + function touchEnd(id) { + let idx = touches.findIndex(t => t.identifier === id); + let touch = touches.splice(idx, 1)[0]; + let ev = { type: 'touchend', + touches: touches, + targetTouches: touches, + changedTouches: [ touch ], + stopPropagation: sinon.spy(), + preventDefault: sinon.spy() }; + target.dispatchEvent(ev); + } + + describe('Single finger tap', function () { + it('should handle single finger tap', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + }); + }); + + describe('Two finger tap', function () { + it('should handle two finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.not.have.been.called; + + touchEnd(2); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twotap', + clientX: 25.0, + clientY: 40.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twotap', + clientX: 25.0, + clientY: 40.0 } })); + }); + + it('should ignore slow starting two finger tap', function () { + touchStart(1, 20.0, 30.0); + + clock.tick(500); + + touchStart(2, 30.0, 50.0); + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow ending two finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchEnd(1); + + clock.tick(500); + + touchEnd(2); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow two finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + + clock.tick(1500); + + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Three finger tap', function () { + it('should handle three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.not.have.been.called; + + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + touchEnd(3); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'threetap', + clientX: 30.0, + clientY: 40.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'threetap', + clientX: 30.0, + clientY: 40.0 } })); + }); + + it('should ignore slow starting three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + + clock.tick(500); + + touchStart(3, 40.0, 40.0); + touchEnd(1); + touchEnd(2); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow ending three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + touchEnd(1); + touchEnd(2); + + clock.tick(500); + + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore three finger drag', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + + touchMove(1, 120.0, 130.0); + touchMove(2, 130.0, 150.0); + touchMove(3, 140.0, 140.0); + + touchEnd(1); + touchEnd(2); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore slow three finger tap', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 50.0); + touchStart(3, 40.0, 40.0); + + clock.tick(1500); + + touchEnd(1); + touchEnd(2); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Single finger drag', function () { + it('should handle horizontal single finger drag', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 40.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 80.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 80.0, + clientY: 30.0 } })); + }); + + it('should handle vertical single finger drag', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 20.0, 50.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 20.0, 90.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 20.0, + clientY: 90.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 20.0, + clientY: 90.0 } })); + }); + + it('should handle diagonal single finger drag', function () { + touchStart(1, 120.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 90.0, 100.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 60.0, 70.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag', + clientX: 120.0, + clientY: 130.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 60.0, + clientY: 70.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 60.0, + clientY: 70.0 } })); + }); + }); + + describe('Long press', function () { + it('should handle long press', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'longpress', + clientX: 20.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'longpress', + clientX: 20.0, + clientY: 30.0 } })); + }); + + it('should handle long press drag', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'longpress', + clientX: 20.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchMove(1, 120.0, 50.0); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'longpress', + clientX: 120.0, + clientY: 50.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'longpress', + clientX: 120.0, + clientY: 50.0 } })); + }); + }); + + describe('Two finger drag', function () { + it('should handle fast and distinct horizontal two finger drag', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 40.0, 30.0); + touchMove(2, 50.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 90.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 60.0, + magnitudeY: 0.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 60.0, + magnitudeY: 0.0 } })); + }); + + it('should handle fast and distinct vertical two finger drag', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 20.0, 100.0); + touchMove(2, 30.0, 40.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 30.0, 90.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 65.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag', + clientX: 25.0, + clientY: 30.0, + magnitudeX: 0.0, + magnitudeY: 65.0 } })); + }); + + it('should handle fast and distinct diagonal two finger drag', function () { + touchStart(1, 120.0, 130.0); + touchStart(2, 130.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 80.0, 90.0); + touchMove(2, 100.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 60.0, 70.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 125.0, + clientY: 130.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 125.0, + clientY: 130.0, + magnitudeX: -55.0, + magnitudeY: -50.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag', + clientX: 125.0, + clientY: 130.0, + magnitudeX: -55.0, + magnitudeY: -50.0 } })); + }); + + it('should ignore fast almost two finger dragging', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + touchMove(1, 80.0, 30.0); + touchMove(2, 70.0, 30.0); + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.not.have.been.called; + }); + + it('should handle slow horizontal two finger drag', function () { + touchStart(1, 50.0, 40.0); + touchStart(2, 60.0, 40.0); + touchMove(1, 80.0, 40.0); + touchMove(2, 110.0, 40.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 55.0, + clientY: 40.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 55.0, + clientY: 40.0, + magnitudeX: 40.0, + magnitudeY: 0.0 } })); + }); + + it('should handle slow vertical two finger drag', function () { + touchStart(1, 40.0, 40.0); + touchStart(2, 40.0, 60.0); + touchMove(2, 40.0, 80.0); + touchMove(1, 40.0, 100.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 40.0, + clientY: 50.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 40.0, + clientY: 50.0, + magnitudeX: 0.0, + magnitudeY: 40.0 } })); + }); + + it('should handle slow diagonal two finger drag', function () { + touchStart(1, 50.0, 40.0); + touchStart(2, 40.0, 60.0); + touchMove(1, 70.0, 60.0); + touchMove(2, 90.0, 110.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag', + clientX: 45.0, + clientY: 50.0, + magnitudeX: 0.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag', + clientX: 45.0, + clientY: 50.0, + magnitudeX: 35.0, + magnitudeY: 35.0 } })); + }); + + it('should ignore too slow two finger drag', function () { + touchStart(1, 20.0, 30.0); + + clock.tick(500); + + touchStart(2, 30.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(2, 50.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Pinch', function () { + it('should handle pinching distinctly and fast inwards', function () { + touchStart(1, 0.0, 0.0); + touchStart(2, 130.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 50.0, 40.0); + touchMove(2, 100.0, 130.0); + + expect(gestures).to.not.have.been.called; + + touchMove(2, 60.0, 70.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 130.0, + magnitudeY: 130.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 10.0, + magnitudeY: 30.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 10.0, + magnitudeY: 30.0 } })); + }); + + it('should handle pinching fast and distinctly outwards', function () { + touchStart(1, 100.0, 100.0); + touchStart(2, 110.0, 100.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 130.0, 70.0); + touchMove(2, 0.0, 200.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 180.0, 20.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 100.0, + magnitudeX: 10.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 100.0, + magnitudeX: 180.0, + magnitudeY: 180.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 100.0, + magnitudeX: 180.0, + magnitudeY: 180.0 } })); + }); + + it('should ignore fast almost pinching', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 130.0, 130.0); + touchMove(1, 80.0, 70.0); + touchEnd(1); + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + clock.tick(1500); + + expect(gestures).to.not.have.been.called; + }); + + it('should handle pinching inwards slowly', function () { + touchStart(1, 0.0, 0.0); + touchStart(2, 130.0, 130.0); + touchMove(1, 50.0, 40.0); + touchMove(2, 100.0, 130.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 130.0, + magnitudeY: 130.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 65.0, + clientY: 65.0, + magnitudeX: 50.0, + magnitudeY: 90.0 } })); + }); + + it('should handle pinching outwards slowly', function () { + touchStart(1, 100.0, 130.0); + touchStart(2, 110.0, 130.0); + touchMove(2, 200.0, 130.0); + + expect(gestures).to.not.have.been.called; + + clock.tick(60); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 130.0, + magnitudeX: 10.0, + magnitudeY: 0.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'pinch', + clientX: 105.0, + clientY: 130.0, + magnitudeX: 100.0, + magnitudeY: 0.0 } })); + }); + + it('should ignore pinching too slowly', function () { + touchStart(1, 0.0, 0.0); + + clock.tick(500); + + touchStart(2, 130.0, 130.0); + touchMove(2, 100.0, 130.0); + touchMove(1, 50.0, 40.0); + + expect(gestures).to.not.have.been.called; + }); + }); + + describe('Ignoring', function () { + it('should ignore extra touches during gesture', function () { + touchStart(1, 20.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchStart(2, 10.0, 10.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 100.0, 50.0); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag', + clientX: 100.0, + clientY: 50.0 } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag', + clientX: 100.0, + clientY: 50.0 } })); + }); + + it('should ignore extra touches when waiting for gesture to end', function () { + touchStart(1, 20.0, 30.0); + touchStart(2, 30.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(2, 90.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'twodrag' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'twodrag' } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'twodrag' } })); + + gestures.resetHistory(); + + touchStart(3, 10.0, 10.0); + touchEnd(3); + + expect(gestures).to.not.have.been.called; + }); + + it('should ignore extra touches after gesture', function () { + touchStart(1, 20.0, 30.0); + touchMove(1, 40.0, 30.0); + touchMove(1, 80.0, 30.0); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'drag' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchStart(2, 10.0, 10.0); + + expect(gestures).to.not.have.been.called; + + touchMove(1, 100.0, 50.0); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gesturemove', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchEnd(1); + + expect(gestures).to.have.been.calledOnceWith( + sinon.match({ type: 'gestureend', + detail: { type: 'drag' } })); + + gestures.resetHistory(); + + touchEnd(2); + + expect(gestures).to.not.have.been.called; + + // Check that everything is reseted after trailing ignores are released + + touchStart(3, 20.0, 30.0); + touchEnd(3); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap' } })); + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap' } })); + }); + + it('should properly reset after a gesture', function () { + touchStart(1, 20.0, 30.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(1); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap', + clientX: 20.0, + clientY: 30.0 } })); + + gestures.resetHistory(); + + touchStart(2, 70.0, 80.0); + + expect(gestures).to.not.have.been.called; + + touchEnd(2); + + expect(gestures).to.have.been.calledTwice; + + expect(gestures.firstCall).to.have.been.calledWith( + sinon.match({ type: 'gesturestart', + detail: { type: 'onetap', + clientX: 70.0, + clientY: 80.0 } })); + + expect(gestures.secondCall).to.have.been.calledWith( + sinon.match({ type: 'gestureend', + detail: { type: 'onetap', + clientX: 70.0, + clientY: 80.0 } })); + }); + }); +}); diff --git a/tests/test.helper.js b/tests/test.helper.js index aa64e9550..9995973fd 100644 --- a/tests/test.helper.js +++ b/tests/test.helper.js @@ -1,184 +1,124 @@ -var assert = chai.assert; -var expect = chai.expect; +const expect = chai.expect; import keysyms from '../core/input/keysymdef.js'; import * as KeyboardUtil from "../core/input/util.js"; -function isIE() { - return navigator && !!(/trident/i).exec(navigator.userAgent); -} -function isEdge() { - return navigator && !!(/edge/i).exec(navigator.userAgent); -} - -describe('Helpers', function() { +describe('Helpers', function () { "use strict"; - describe('keysyms.lookup', function() { - it('should map ASCII characters to keysyms', function() { + describe('keysyms.lookup', function () { + it('should map ASCII characters to keysyms', function () { expect(keysyms.lookup('a'.charCodeAt())).to.be.equal(0x61); expect(keysyms.lookup('A'.charCodeAt())).to.be.equal(0x41); - }); - it('should map Latin-1 characters to keysyms', function() { + }); + it('should map Latin-1 characters to keysyms', function () { expect(keysyms.lookup('ø'.charCodeAt())).to.be.equal(0xf8); expect(keysyms.lookup('é'.charCodeAt())).to.be.equal(0xe9); }); - it('should map characters that are in Windows-1252 but not in Latin-1 to keysyms', function() { + it('should map characters that are in Windows-1252 but not in Latin-1 to keysyms', function () { expect(keysyms.lookup('Š'.charCodeAt())).to.be.equal(0x01a9); }); - it('should map characters which aren\'t in Latin1 *or* Windows-1252 to keysyms', function() { + it('should map characters which aren\'t in Latin1 *or* Windows-1252 to keysyms', function () { expect(keysyms.lookup('ũ'.charCodeAt())).to.be.equal(0x03fd); }); - it('should map unknown codepoints to the Unicode range', function() { + it('should map unknown codepoints to the Unicode range', function () { expect(keysyms.lookup('\n'.charCodeAt())).to.be.equal(0x100000a); expect(keysyms.lookup('\u262D'.charCodeAt())).to.be.equal(0x100262d); }); // This requires very recent versions of most browsers... skipping for now - it.skip('should map UCS-4 codepoints to the Unicode range', function() { + it.skip('should map UCS-4 codepoints to the Unicode range', function () { //expect(keysyms.lookup('\u{1F686}'.codePointAt())).to.be.equal(0x101f686); }); }); - describe('getKeycode', function() { - it('should pass through proper code', function() { + describe('getKeycode', function () { + it('should pass through proper code', function () { expect(KeyboardUtil.getKeycode({code: 'Semicolon'})).to.be.equal('Semicolon'); }); - it('should map legacy values', function() { + it('should map legacy values', function () { expect(KeyboardUtil.getKeycode({code: ''})).to.be.equal('Unidentified'); expect(KeyboardUtil.getKeycode({code: 'OSLeft'})).to.be.equal('MetaLeft'); }); - it('should map keyCode to code when possible', function() { + it('should map keyCode to code when possible', function () { expect(KeyboardUtil.getKeycode({keyCode: 0x14})).to.be.equal('CapsLock'); expect(KeyboardUtil.getKeycode({keyCode: 0x5b})).to.be.equal('MetaLeft'); expect(KeyboardUtil.getKeycode({keyCode: 0x35})).to.be.equal('Digit5'); expect(KeyboardUtil.getKeycode({keyCode: 0x65})).to.be.equal('Numpad5'); }); - it('should map keyCode left/right side', function() { + it('should map keyCode left/right side', function () { expect(KeyboardUtil.getKeycode({keyCode: 0x10, location: 1})).to.be.equal('ShiftLeft'); expect(KeyboardUtil.getKeycode({keyCode: 0x10, location: 2})).to.be.equal('ShiftRight'); expect(KeyboardUtil.getKeycode({keyCode: 0x11, location: 1})).to.be.equal('ControlLeft'); expect(KeyboardUtil.getKeycode({keyCode: 0x11, location: 2})).to.be.equal('ControlRight'); }); - it('should map keyCode on numpad', function() { + it('should map keyCode on numpad', function () { expect(KeyboardUtil.getKeycode({keyCode: 0x0d, location: 0})).to.be.equal('Enter'); expect(KeyboardUtil.getKeycode({keyCode: 0x0d, location: 3})).to.be.equal('NumpadEnter'); expect(KeyboardUtil.getKeycode({keyCode: 0x23, location: 0})).to.be.equal('End'); expect(KeyboardUtil.getKeycode({keyCode: 0x23, location: 3})).to.be.equal('Numpad1'); }); - it('should return Unidentified when it cannot map the keyCode', function() { + it('should return Unidentified when it cannot map the keyCode', function () { expect(KeyboardUtil.getKeycode({keycode: 0x42})).to.be.equal('Unidentified'); }); - describe('Fix Meta on macOS', function() { - var origNavigator; + describe('Fix Meta on macOS', function () { + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these // tests. origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - window.navigator.platform = "Mac x86_64"; }); afterEach(function () { Object.defineProperty(window, "navigator", origNavigator); }); - it('should respect ContextMenu on modern browser', function() { + it('should respect ContextMenu on modern browser', function () { expect(KeyboardUtil.getKeycode({code: 'ContextMenu', keyCode: 0x5d})).to.be.equal('ContextMenu'); }); - it('should translate legacy ContextMenu to MetaRight', function() { + it('should translate legacy ContextMenu to MetaRight', function () { expect(KeyboardUtil.getKeycode({keyCode: 0x5d})).to.be.equal('MetaRight'); }); }); }); - describe('getKey', function() { - it('should prefer key', function() { - if (isIE() || isEdge()) this.skip(); + describe('getKey', function () { + it('should prefer key', function () { expect(KeyboardUtil.getKey({key: 'a', charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.be.equal('a'); }); - it('should map legacy values', function() { - expect(KeyboardUtil.getKey({key: 'Spacebar'})).to.be.equal(' '); - expect(KeyboardUtil.getKey({key: 'Left'})).to.be.equal('ArrowLeft'); + it('should map legacy values', function () { expect(KeyboardUtil.getKey({key: 'OS'})).to.be.equal('Meta'); - expect(KeyboardUtil.getKey({key: 'Win'})).to.be.equal('Meta'); expect(KeyboardUtil.getKey({key: 'UIKeyInputLeftArrow'})).to.be.equal('ArrowLeft'); }); - it('should use code if no key', function() { + it('should handle broken Delete', function () { + expect(KeyboardUtil.getKey({key: '\x00', code: 'NumpadDecimal'})).to.be.equal('Delete'); + }); + it('should use code if no key', function () { expect(KeyboardUtil.getKey({code: 'NumpadBackspace'})).to.be.equal('Backspace'); }); - it('should not use code fallback for character keys', function() { + it('should not use code fallback for character keys', function () { expect(KeyboardUtil.getKey({code: 'KeyA'})).to.be.equal('Unidentified'); expect(KeyboardUtil.getKey({code: 'Digit1'})).to.be.equal('Unidentified'); expect(KeyboardUtil.getKey({code: 'Period'})).to.be.equal('Unidentified'); expect(KeyboardUtil.getKey({code: 'Numpad1'})).to.be.equal('Unidentified'); }); - it('should use charCode if no key', function() { + it('should use charCode if no key', function () { expect(KeyboardUtil.getKey({charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.be.equal('Š'); + // Broken Oculus browser + expect(KeyboardUtil.getKey({charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43, key: 'Unidentified'})).to.be.equal('Š'); }); - it('should return Unidentified when it cannot map the key', function() { + it('should return Unidentified when it cannot map the key', function () { expect(KeyboardUtil.getKey({keycode: 0x42})).to.be.equal('Unidentified'); }); - - describe('Broken key AltGraph on IE/Edge', function() { - var origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should ignore printable character key on IE', function() { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; - expect(KeyboardUtil.getKey({key: 'a'})).to.be.equal('Unidentified'); - }); - it('should ignore printable character key on Edge', function() { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; - expect(KeyboardUtil.getKey({key: 'a'})).to.be.equal('Unidentified'); - }); - it('should allow non-printable character key on IE', function() { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko"; - expect(KeyboardUtil.getKey({key: 'Shift'})).to.be.equal('Shift'); - }); - it('should allow non-printable character key on Edge', function() { - window.navigator.userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"; - expect(KeyboardUtil.getKey({key: 'Shift'})).to.be.equal('Shift'); - }); - }); }); - describe('getKeysym', function() { - describe('Non-character keys', function() { - it('should recognize the right keys', function() { + describe('getKeysym', function () { + describe('Non-character keys', function () { + it('should recognize the right keys', function () { expect(KeyboardUtil.getKeysym({key: 'Enter'})).to.be.equal(0xFF0D); expect(KeyboardUtil.getKeysym({key: 'Backspace'})).to.be.equal(0xFF08); expect(KeyboardUtil.getKeysym({key: 'Tab'})).to.be.equal(0xFF09); @@ -189,42 +129,81 @@ describe('Helpers', function() { expect(KeyboardUtil.getKeysym({key: 'Escape'})).to.be.equal(0xFF1B); expect(KeyboardUtil.getKeysym({key: 'ArrowUp'})).to.be.equal(0xFF52); }); - it('should map left/right side', function() { + it('should map left/right side', function () { expect(KeyboardUtil.getKeysym({key: 'Shift', location: 1})).to.be.equal(0xFFE1); expect(KeyboardUtil.getKeysym({key: 'Shift', location: 2})).to.be.equal(0xFFE2); expect(KeyboardUtil.getKeysym({key: 'Control', location: 1})).to.be.equal(0xFFE3); expect(KeyboardUtil.getKeysym({key: 'Control', location: 2})).to.be.equal(0xFFE4); }); - it('should handle AltGraph', function() { + it('should handle AltGraph', function () { expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'Alt', location: 2})).to.be.equal(0xFFEA); expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'AltGraph', location: 2})).to.be.equal(0xFE03); }); - it('should return null for unknown keys', function() { + it('should handle Windows key with incorrect location', function () { + expect(KeyboardUtil.getKeysym({key: 'Meta', location: 0})).to.be.equal(0xFFEC); + }); + it('should handle Clear/NumLock key with incorrect location', function () { + this.skip(); // Broken because of Clear/NumLock override + expect(KeyboardUtil.getKeysym({key: 'Clear', code: 'NumLock', location: 3})).to.be.equal(0xFF0B); + }); + it('should handle Meta/Windows distinction', function () { + expect(KeyboardUtil.getKeysym({code: 'AltLeft', key: 'Meta', location: 1})).to.be.equal(0xFFE7); + expect(KeyboardUtil.getKeysym({code: 'AltRight', key: 'Meta', location: 2})).to.be.equal(0xFFE8); + expect(KeyboardUtil.getKeysym({code: 'MetaLeft', key: 'Meta', location: 1})).to.be.equal(0xFFEB); + expect(KeyboardUtil.getKeysym({code: 'MetaRight', key: 'Meta', location: 2})).to.be.equal(0xFFEC); + }); + it('should send NumLock even if key is Clear', function () { + expect(KeyboardUtil.getKeysym({key: 'Clear', code: 'NumLock'})).to.be.equal(0xFF7F); + }); + it('should return null for unknown keys', function () { expect(KeyboardUtil.getKeysym({key: 'Semicolon'})).to.be.null; expect(KeyboardUtil.getKeysym({key: 'BracketRight'})).to.be.null; }); - it('should handle remappings', function() { + it('should handle remappings', function () { expect(KeyboardUtil.getKeysym({code: 'ControlLeft', key: 'Tab'})).to.be.equal(0xFF09); }); }); - describe('Numpad', function() { - it('should handle Numpad numbers', function() { - if (isIE() || isEdge()) this.skip(); + describe('Numpad', function () { + it('should handle Numpad numbers', function () { expect(KeyboardUtil.getKeysym({code: 'Digit5', key: '5', location: 0})).to.be.equal(0x0035); expect(KeyboardUtil.getKeysym({code: 'Numpad5', key: '5', location: 3})).to.be.equal(0xFFB5); }); - it('should handle Numpad non-character keys', function() { + it('should handle Numpad non-character keys', function () { expect(KeyboardUtil.getKeysym({code: 'Home', key: 'Home', location: 0})).to.be.equal(0xFF50); expect(KeyboardUtil.getKeysym({code: 'Numpad5', key: 'Home', location: 3})).to.be.equal(0xFF95); expect(KeyboardUtil.getKeysym({code: 'Delete', key: 'Delete', location: 0})).to.be.equal(0xFFFF); expect(KeyboardUtil.getKeysym({code: 'NumpadDecimal', key: 'Delete', location: 3})).to.be.equal(0xFF9F); }); - it('should handle Numpad Decimal key', function() { - if (isIE() || isEdge()) this.skip(); + it('should handle Numpad Decimal key', function () { expect(KeyboardUtil.getKeysym({code: 'NumpadDecimal', key: '.', location: 3})).to.be.equal(0xFFAE); expect(KeyboardUtil.getKeysym({code: 'NumpadDecimal', key: ',', location: 3})).to.be.equal(0xFFAC); }); }); + + describe('Japanese IM keys on Windows', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + window.navigator.platform = "Windows"; + }); + + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + }); + + const keys = { 'Zenkaku': 0xff2a, 'Hankaku': 0xff2a, + 'Romaji': 0xff24, 'KanaMode': 0xff24 }; + for (let [key, keysym] of Object.entries(keys)) { + it(`should fake combined key for ${key} on Windows`, function () { + expect(KeyboardUtil.getKeysym({code: 'FakeIM', key: key})).to.be.equal(keysym); + }); + } + }); }); }); diff --git a/tests/test.hextile.js b/tests/test.hextile.js new file mode 100644 index 000000000..cbe6f7b5a --- /dev/null +++ b/tests/test.hextile.js @@ -0,0 +1,242 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import HextileDecoder from '../core/decoders/hextile.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +function push32(arr, num) { + arr.push((num >> 24) & 0xFF, + (num >> 16) & 0xFF, + (num >> 8) & 0xFF, + num & 0xFF); +} + +describe('Hextile Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new HextileDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle a tile with fg, bg specified, normal subrects', function () { + let data = []; + data.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects + push32(data, 0x00ff0000); // becomes 00ff0000 --> #00FF00 bg color + data.push(0x00); // becomes 0000ff00 --> #0000FF fg color + data.push(0x00); + data.push(0xff); + data.push(0x00); + data.push(2); // 2 subrects + data.push(0); // x: 0, y: 0 + data.push(1 | (1 << 4)); // width: 2, height: 2 + data.push(2 | (2 << 4)); // x: 2, y: 2 + data.push(1 | (1 << 4)); // width: 2, height: 2 + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle a raw tile', function () { + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + let data = []; + data.push(0x01); // raw + for (let i = 0; i < targetData.length; i += 4) { + data.push(targetData[i]); + data.push(targetData[i + 1]); + data.push(targetData[i + 2]); + // Last byte zero to test correct alpha handling + data.push(0); + } + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle a tile with only bg specified (solid bg)', function () { + let data = []; + data.push(0x02); + push32(data, 0x00ff0000); // becomes 00ff0000 --> #00FF00 bg color + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let expected = []; + for (let i = 0; i < 16; i++) { + push32(expected, 0x00ff00ff); + } + + expect(done).to.be.true; + expect(display).to.have.displayed(new Uint8Array(expected)); + }); + + it('should handle a tile with only bg specified and an empty frame afterwards', function () { + // set the width so we can have two tiles + display.resize(8, 4); + + let data = []; + + // send a bg frame + data.push(0x02); + push32(data, 0x00ff0000); // becomes 00ff0000 --> #00FF00 bg color + + // send an empty frame + data.push(0x00); + + let done = testDecodeRect(decoder, 0, 0, 32, 4, data, display, 24); + + let expected = []; + for (let i = 0; i < 16; i++) { + push32(expected, 0x00ff00ff); // rect 1: solid + } + for (let i = 0; i < 16; i++) { + push32(expected, 0x00ff00ff); // rect 2: same bkground color + } + + expect(done).to.be.true; + expect(display).to.have.displayed(new Uint8Array(expected)); + }); + + it('should handle a tile with bg and coloured subrects', function () { + let data = []; + data.push(0x02 | 0x08 | 0x10); // bg spec, anysubrects, colouredsubrects + push32(data, 0x00ff0000); // becomes 00ff0000 --> #00FF00 bg color + data.push(2); // 2 subrects + data.push(0x00); // becomes 0000ff00 --> #0000FF fg color + data.push(0x00); + data.push(0xff); + data.push(0x00); + data.push(0); // x: 0, y: 0 + data.push(1 | (1 << 4)); // width: 2, height: 2 + data.push(0x00); // becomes 0000ff00 --> #0000FF fg color + data.push(0x00); + data.push(0xff); + data.push(0x00); + data.push(2 | (2 << 4)); // x: 2, y: 2 + data.push(1 | (1 << 4)); // width: 2, height: 2 + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should carry over fg and bg colors from the previous tile if not specified', function () { + display.resize(4, 17); + + let data = []; + data.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects + push32(data, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color + data.push(0x00); // becomes 0000ffff --> #0000FF fg color + data.push(0x00); + data.push(0xff); + data.push(0xff); + data.push(8); // 8 subrects + for (let i = 0; i < 4; i++) { + data.push((0 << 4) | (i * 4)); // x: 0, y: i*4 + data.push(1 | (1 << 4)); // width: 2, height: 2 + data.push((2 << 4) | (i * 4 + 2)); // x: 2, y: i * 4 + 2 + data.push(1 | (1 << 4)); // width: 2, height: 2 + } + data.push(0x08); // anysubrects + data.push(1); // 1 subrect + data.push(0); // x: 0, y: 0 + data.push(1 | (1 << 4)); // width: 2, height: 2 + + let done = testDecodeRect(decoder, 0, 0, 4, 17, data, display, 24); + + let targetData = [ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]; + + let expected = []; + for (let i = 0; i < 4; i++) { + expected = expected.concat(targetData); + } + expected = expected.concat(targetData.slice(0, 16)); + + expect(done).to.be.true; + expect(display).to.have.displayed(new Uint8Array(expected)); + }); + + it('should fail on an invalid subencoding', function () { + let data = [45]; // an invalid subencoding + expect(() => testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24)).to.throw(); + }); + + it('should handle empty rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, [], display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); +}); diff --git a/tests/test.inflator.js b/tests/test.inflator.js new file mode 100644 index 000000000..533bcd865 --- /dev/null +++ b/tests/test.inflator.js @@ -0,0 +1,113 @@ +/* eslint-disable no-console */ +const expect = chai.expect; + +import { deflateInit, deflate, Z_FULL_FLUSH } from "../vendor/pako/lib/zlib/deflate.js"; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; +import Inflator from "../core/inflator.js"; + +function _deflator(data) { + let strm = new ZStream(); + + deflateInit(strm, 5); + + /* eslint-disable camelcase */ + strm.input = data; + strm.avail_in = strm.input.length; + strm.next_in = 0; + /* eslint-enable camelcase */ + + let chunks = []; + let totalLen = 0; + while (strm.avail_in > 0) { + /* eslint-disable camelcase */ + strm.output = new Uint8Array(1024 * 10 * 10); + strm.avail_out = strm.output.length; + strm.next_out = 0; + /* eslint-enable camelcase */ + + let ret = deflate(strm, Z_FULL_FLUSH); + + // Check that return code is not an error + expect(ret).to.be.greaterThan(-1); + + let chunk = new Uint8Array(strm.output.buffer, 0, strm.next_out); + totalLen += chunk.length; + chunks.push(chunk); + } + + // Combine chunks into a single data + + let outData = new Uint8Array(totalLen); + let offset = 0; + + for (let i = 0; i < chunks.length; i++) { + outData.set(chunks[i], offset); + offset += chunks[i].length; + } + + return outData; +} + +describe('Inflate data', function () { + + it('should be able to inflate messages', function () { + let inflator = new Inflator(); + + let text = "123asdf"; + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = _deflator(preText); + + inflator.setInput(compText); + let inflatedText = inflator.inflate(preText.length); + + expect(inflatedText).to.array.equal(preText); + + }); + + it('should be able to inflate large messages', function () { + let inflator = new Inflator(); + + /* Generate a big string with random characters. Used because + repetition of letters might be deflated more effectively than + random ones. */ + let text = ""; + let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + for (let i = 0; i < 300000; i++) { + text += characters.charAt(Math.floor(Math.random() * characters.length)); + } + + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = _deflator(preText); + + //Check that the compressed size is expected size + expect(compText.length).to.be.greaterThan((1024 * 10 * 10) * 2); + + inflator.setInput(compText); + let inflatedText = inflator.inflate(preText.length); + + expect(inflatedText).to.array.equal(preText); + }); + + it('should throw an error on insufficient data', function () { + let inflator = new Inflator(); + + let text = "123asdf"; + let preText = new Uint8Array(text.length); + for (let i = 0; i < preText.length; i++) { + preText[i] = text.charCodeAt(i); + } + + let compText = _deflator(preText); + + inflator.setInput(compText); + expect(() => inflator.inflate(preText.length * 2)).to.throw(); + }); +}); diff --git a/tests/test.int.js b/tests/test.int.js new file mode 100644 index 000000000..954fd279f --- /dev/null +++ b/tests/test.int.js @@ -0,0 +1,16 @@ +/* eslint-disable no-console */ +const expect = chai.expect; + +import { toUnsigned32bit, toSigned32bit } from '../core/util/int.js'; + +describe('Integer casting', function () { + it('should cast unsigned to signed', function () { + let expected = 4294967286; + expect(toUnsigned32bit(-10)).to.equal(expected); + }); + + it('should cast signed to unsigned', function () { + let expected = -10; + expect(toSigned32bit(4294967286)).to.equal(expected); + }); +}); diff --git a/tests/test.jpeg.js b/tests/test.jpeg.js new file mode 100644 index 000000000..8dee48912 --- /dev/null +++ b/tests/test.jpeg.js @@ -0,0 +1,292 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import JPEGDecoder from '../core/decoders/jpeg.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +describe('JPEG Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new JPEGDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle JPEG rects', async function () { + let data = [ + // JPEG data + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, + 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x01, 0x2c, + 0x01, 0x2c, 0x00, 0x42, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x03, 0x02, 0x02, 0x03, 0x02, 0x02, 0x03, + 0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x05, + 0x08, 0x05, 0x05, 0x04, 0x04, 0x05, 0x0a, 0x07, + 0x07, 0x06, 0x08, 0x0c, 0x0a, 0x0c, 0x0c, 0x0b, + 0x0a, 0x0b, 0x0b, 0x0d, 0x0e, 0x12, 0x10, 0x0d, + 0x0e, 0x11, 0x0e, 0x0b, 0x0b, 0x10, 0x16, 0x10, + 0x11, 0x13, 0x14, 0x15, 0x15, 0x15, 0x0c, 0x0f, + 0x17, 0x18, 0x16, 0x14, 0x18, 0x12, 0x14, 0x15, + 0x14, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x03, 0x04, + 0x04, 0x05, 0x04, 0x05, 0x09, 0x05, 0x05, 0x09, + 0x14, 0x0d, 0x0b, 0x0d, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xff, 0xc0, + 0x00, 0x11, 0x08, 0x00, 0x04, 0x00, 0x04, 0x03, + 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, + 0x01, 0xff, 0xc4, 0x00, 0x1f, 0x00, 0x00, 0x01, + 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x10, 0x00, + 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, + 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, + 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, + 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, + 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, + 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, + 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, + 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, + 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, + 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, + 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, + 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, + 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, + 0xfa, 0xff, 0xc4, 0x00, 0x1f, 0x01, 0x00, 0x03, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x11, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, + 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, + 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, + 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, + 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, + 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, + 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, + 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, + 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, + 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, + 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, + 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, + 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, + 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, + 0xfa, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, + 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf9, + 0xf7, 0xfb, 0x67, 0x56, 0xff, 0x00, 0x9f, 0xf8, + 0x3f, 0xf0, 0x51, 0xa7, 0xff, 0x00, 0xf2, 0x3d, + 0x7e, 0x6f, 0xfd, 0xab, 0x94, 0x7f, 0xd0, 0x9a, + 0x8f, 0xfe, 0x0d, 0xc7, 0x7f, 0xf3, 0x61, 0xfd, + 0xa7, 0xff, 0x00, 0x10, 0x77, 0x0d, 0xff, 0x00, + 0x43, 0xec, 0xcf, 0xff, 0x00, 0x0b, 0xab, 0x1f, + 0xff, 0xd9, + ]; + + let decodeDone = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + expect(decodeDone).to.be.true; + + let targetData = new Uint8Array([ + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255 + ]); + + // Browsers have rounding errors, so we need an approximate + // comparing function + function almost(a, b) { + let diff = Math.abs(a - b); + return diff < 5; + } + + await display.flush(); + expect(display).to.have.displayed(targetData, almost); + }); + + it('should handle JPEG rects without Huffman and quantification tables', async function () { + let data1 = [ + // JPEG data + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, + 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x01, 0x2c, + 0x01, 0x2c, 0x00, 0x42, 0xff, 0xdb, 0x00, 0x43, + 0x00, 0x03, 0x02, 0x02, 0x03, 0x02, 0x02, 0x03, + 0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x05, + 0x08, 0x05, 0x05, 0x04, 0x04, 0x05, 0x0a, 0x07, + 0x07, 0x06, 0x08, 0x0c, 0x0a, 0x0c, 0x0c, 0x0b, + 0x0a, 0x0b, 0x0b, 0x0d, 0x0e, 0x12, 0x10, 0x0d, + 0x0e, 0x11, 0x0e, 0x0b, 0x0b, 0x10, 0x16, 0x10, + 0x11, 0x13, 0x14, 0x15, 0x15, 0x15, 0x0c, 0x0f, + 0x17, 0x18, 0x16, 0x14, 0x18, 0x12, 0x14, 0x15, + 0x14, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x03, 0x04, + 0x04, 0x05, 0x04, 0x05, 0x09, 0x05, 0x05, 0x09, + 0x14, 0x0d, 0x0b, 0x0d, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, + 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xff, 0xc0, + 0x00, 0x11, 0x08, 0x00, 0x04, 0x00, 0x04, 0x03, + 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, + 0x01, 0xff, 0xc4, 0x00, 0x1f, 0x00, 0x00, 0x01, + 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x10, 0x00, + 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, + 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, + 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, + 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, + 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, + 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, + 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, + 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, + 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, + 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, + 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, + 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, + 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, + 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, + 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, + 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, + 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, + 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, + 0xfa, 0xff, 0xc4, 0x00, 0x1f, 0x01, 0x00, 0x03, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, + 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x11, 0x00, + 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, + 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, + 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, + 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, + 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, + 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, + 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, + 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, + 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, + 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, + 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, + 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, + 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, + 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, + 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, + 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, + 0xfa, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, + 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf9, + 0xf7, 0xfb, 0x67, 0x56, 0xff, 0x00, 0x9f, 0xf8, + 0x3f, 0xf0, 0x51, 0xa7, 0xff, 0x00, 0xf2, 0x3d, + 0x7e, 0x6f, 0xfd, 0xab, 0x94, 0x7f, 0xd0, 0x9a, + 0x8f, 0xfe, 0x0d, 0xc7, 0x7f, 0xf3, 0x61, 0xfd, + 0xa7, 0xff, 0x00, 0x10, 0x77, 0x0d, 0xff, 0x00, + 0x43, 0xec, 0xcf, 0xff, 0x00, 0x0b, 0xab, 0x1f, + 0xff, 0xd9, + ]; + + let decodeDone; + + decodeDone = testDecodeRect(decoder, 0, 0, 4, 4, data1, display, 24); + expect(decodeDone).to.be.true; + + display.fillRect(0, 0, 4, 4, [128, 128, 128, 255]); + + let data2 = [ + // JPEG data + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, + 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x01, 0x2c, + 0x01, 0x2c, 0x00, 0x73, 0xff, 0xc0, 0x00, 0x11, + 0x08, 0x00, 0x04, 0x00, 0x04, 0x03, 0x01, 0x11, + 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, + 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, + 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf9, 0xf7, 0xfb, + 0x67, 0x56, 0xff, 0x00, 0x9f, 0xf8, 0x3f, 0xf0, + 0x51, 0xa7, 0xff, 0x00, 0xf2, 0x3d, 0x7e, 0x6f, + 0xfd, 0xab, 0x94, 0x7f, 0xd0, 0x9a, 0x8f, 0xfe, + 0x0d, 0xc7, 0x7f, 0xf3, 0x61, 0xfd, 0xa7, 0xff, + 0x00, 0x10, 0x77, 0x0d, 0xff, 0x00, 0x43, 0xec, + 0xcf, 0xff, 0x00, 0x0b, 0xab, 0x1f, 0xff, 0xd9, + ]; + + decodeDone = testDecodeRect(decoder, 0, 0, 4, 4, data2, display, 24); + expect(decodeDone).to.be.true; + + let targetData = new Uint8Array([ + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255 + ]); + + // Browsers have rounding errors, so we need an approximate + // comparing function + function almost(a, b) { + let diff = Math.abs(a - b); + return diff < 5; + } + + await display.flush(); + expect(display).to.have.displayed(targetData, almost); + }); +}); diff --git a/tests/test.keyboard.js b/tests/test.keyboard.js index 513d797f9..efc84c306 100644 --- a/tests/test.keyboard.js +++ b/tests/test.keyboard.js @@ -1,38 +1,30 @@ -var assert = chai.assert; -var expect = chai.expect; - -import sinon from '../vendor/sinon.js'; +const expect = chai.expect; import Keyboard from '../core/input/keyboard.js'; -function isIE() { - return navigator && !!(/trident/i).exec(navigator.userAgent); -} -function isEdge() { - return navigator && !!(/edge/i).exec(navigator.userAgent); -} - -/* jshint newcap: false, expr: true */ -describe('Key Event Handling', function() { +describe('Key Event Handling', function () { "use strict"; // The real KeyboardEvent constructor might not work everywhere we // want to run these tests function keyevent(typeArg, KeyboardEventInit) { - var e = { type: typeArg }; - for (var key in KeyboardEventInit) { + const e = { type: typeArg }; + for (let key in KeyboardEventInit) { e[key] = KeyboardEventInit[key]; } e.stopPropagation = sinon.spy(); e.preventDefault = sinon.spy(); + e.getModifierState = function (key) { + return e[key]; + }; + return e; - }; + } - describe('Decode Keyboard Events', function() { - it('should decode keydown events', function(done) { - if (isIE() || isEdge()) this.skip(); - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + describe('Decode Keyboard Events', function () { + it('should decode keydown events', function (done) { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); expect(down).to.be.equal(true); @@ -40,11 +32,10 @@ describe('Key Event Handling', function() { }; kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); }); - it('should decode keyup events', function(done) { - if (isIE() || isEdge()) this.skip(); - var calls = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should decode keyup events', function (done) { + let calls = 0; + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); if (calls++ === 1) { @@ -55,121 +46,13 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); }); - - describe('Legacy keypress Events', function() { - it('should wait for keypress when needed', function() { - var kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - it('should decode keypress events', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - kbd._handleKeyPress(keyevent('keypress', {code: 'KeyA', charCode: 0x61})); - }); - it('should ignore keypress with different code', function() { - var kbd = new Keyboard(document); - kbd.onkeyevent = sinon.spy(); - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - kbd._handleKeyPress(keyevent('keypress', {code: 'KeyB', charCode: 0x61})); - expect(kbd.onkeyevent).to.not.have.been.called; - }); - it('should handle keypress with missing code', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); - kbd._handleKeyPress(keyevent('keypress', {charCode: 0x61})); - }); - it('should guess key if no keypress and numeric key', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - expect(keysym).to.be.equal(0x32); - expect(code).to.be.equal('Digit2'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'Digit2', keyCode: 0x32})); - }); - it('should guess key if no keypress and alpha key', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41, shiftKey: false})); - }); - it('should guess key if no keypress and alpha key (with shift)', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - expect(keysym).to.be.equal(0x41); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41, shiftKey: true})); - }); - it('should not guess key if no keypress and unknown key', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - expect(keysym).to.be.equal(0); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - done(); - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x09})); - }); - }); - - describe('suppress the right events at the right time', function() { - beforeEach(function () { - if (isIE() || isEdge()) this.skip(); - }); - it('should suppress anything with a valid key', function() { - var kbd = new Keyboard(document, {}); - var evt = keyevent('keydown', {code: 'KeyA', key: 'a'}); - kbd._handleKeyDown(evt); - expect(evt.preventDefault).to.have.been.called; - evt = keyevent('keyup', {code: 'KeyA', key: 'a'}); - kbd._handleKeyUp(evt); - expect(evt.preventDefault).to.have.been.called; - }); - it('should not suppress keys without key', function() { - var kbd = new Keyboard(document, {}); - var evt = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); - kbd._handleKeyDown(evt); - expect(evt.preventDefault).to.not.have.been.called; - }); - it('should suppress the following keypress event', function() { - var kbd = new Keyboard(document, {}); - var evt = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); - kbd._handleKeyDown(evt); - var evt = keyevent('keypress', {code: 'KeyA', charCode: 0x41}); - kbd._handleKeyPress(evt); - expect(evt.preventDefault).to.have.been.called; - }); - }); }); - describe('Fake keyup', function() { - it('should fake keyup events for virtual keyboards', function(done) { - if (isIE() || isEdge()) this.skip(); - var count = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + describe('Fake keyup', function () { + it('should fake keyup events for virtual keyboards', function (done) { + let count = 0; + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { switch (count++) { case 0: expect(keysym).to.be.equal(0x61); @@ -185,63 +68,12 @@ describe('Key Event Handling', function() { }; kbd._handleKeyDown(keyevent('keydown', {code: 'Unidentified', key: 'a'})); }); - - describe('iOS', function() { - var origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } - - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - - window.navigator.platform = "iPhone 9.0"; - }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); - }); - - it('should fake keyup events on iOS', function(done) { - if (isIE() || isEdge()) this.skip(); - var count = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - switch (count++) { - case 0: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - break; - case 1: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(false); - done(); - } - }; - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - }); - }); }); - describe('Track Key State', function() { - beforeEach(function () { - if (isIE() || isEdge()) this.skip(); - }); - it('should send release using the same keysym as the press', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + describe('Track Key State', function () { + it('should send release using the same keysym as the press', function (done) { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); if (!down) { @@ -251,10 +83,10 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'b'})); }); - it('should send the same keysym for multiple presses', function() { - var count = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should send the same keysym for multiple presses', function () { + let count = 0; + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); expect(down).to.be.equal(true); @@ -264,17 +96,17 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'b'})); expect(count).to.be.equal(2); }); - it('should do nothing on keyup events if no keys are down', function() { - var kbd = new Keyboard(document); + it('should do nothing on keyup events if no keys are down', function () { + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); expect(kbd.onkeyevent).to.not.have.been.called; }); - describe('Legacy Events', function() { - it('should track keys using keyCode if no code', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + describe('Legacy Events', function () { + it('should track keys using keyCode if no code', function (done) { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('Platform65'); if (!down) { @@ -284,17 +116,17 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {keyCode: 65, key: 'a'})); kbd._handleKeyUp(keyevent('keyup', {keyCode: 65, key: 'b'})); }); - it('should ignore compositing code', function() { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should ignore compositing code', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('Unidentified'); }; kbd._handleKeyDown(keyevent('keydown', {keyCode: 229, key: 'a'})); }); - it('should track keys using keyIdentifier if no code', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should track keys using keyIdentifier if no code', function (done) { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('Platform65'); if (!down) { @@ -307,36 +139,25 @@ describe('Key Event Handling', function() { }); }); - describe('Shuffle modifiers on macOS', function() { - var origNavigator; + describe('Shuffle modifiers on macOS', function () { + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these // tests. origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.platform !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } - window.navigator.platform = "Mac x86_64"; }); afterEach(function () { Object.defineProperty(window, "navigator", origNavigator); }); - it('should change Alt to AltGraph', function() { - var count = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should change Alt to AltGraph', function () { + let count = 0; + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { switch (count++) { case 0: expect(keysym).to.be.equal(0xFF7E); @@ -352,18 +173,18 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); expect(count).to.be.equal(2); }); - it('should change left Super to Alt', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should change left Super to Alt', function (done) { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0xFFE9); expect(code).to.be.equal('MetaLeft'); done(); }; kbd._handleKeyDown(keyevent('keydown', {code: 'MetaLeft', key: 'Meta', location: 1})); }); - it('should change right Super to left Super', function(done) { - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { + it('should change right Super to left Super', function (done) { + const kbd = new Keyboard(document); + kbd.onkeyevent = (keysym, code, down) => { expect(keysym).to.be.equal(0xFFEB); expect(code).to.be.equal('MetaRight'); done(); @@ -372,18 +193,13 @@ describe('Key Event Handling', function() { }); }); - describe('Escape AltGraph on Windows', function() { - var origNavigator; + describe('Meta key combination on iOS and macOS', function () { + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these // tests. origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } Object.defineProperty(window, "navigator", {value: {}}); if (window.navigator.platform !== undefined) { @@ -391,110 +207,385 @@ describe('Key Event Handling', function() { // versions of Chrome this.skip(); } + }); + + afterEach(function () { + if (origNavigator !== undefined) { + Object.defineProperty(window, "navigator", origNavigator); + } + }); + + it('should send keyup when meta key is pressed on iOS', function () { + window.navigator.platform = "iPad"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'MetaRight', key: 'Meta', location: 2, metaKey: true})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a', metaKey: true})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent).to.have.been.calledWith(0x61, "KeyA", true); + expect(kbd.onkeyevent).to.have.been.calledWith(0x61, "KeyA", false); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyUp(keyevent('keyup', {code: 'MetaRight', key: 'Meta', location: 2, metaKey: true})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + }); + + it('should send keyup when meta key is pressed on macOS', function () { + window.navigator.platform = "Mac"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'MetaRight', key: 'Meta', location: 2, metaKey: true})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a', metaKey: true})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent).to.have.been.calledWith(0x61, "KeyA", true); + expect(kbd.onkeyevent).to.have.been.calledWith(0x61, "KeyA", false); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyUp(keyevent('keyup', {code: 'MetaRight', key: 'Meta', location: 2, metaKey: true})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + }); + }); + + describe('Caps Lock on iOS and macOS', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + }); + + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + }); + + it('should toggle caps lock on key press on iOS', function () { + window.navigator.platform = "iPad"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + }); + + it('should toggle caps lock on key press on mac', function () { + window.navigator.platform = "Mac"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + }); + + it('should toggle caps lock on key release on iOS', function () { + window.navigator.platform = "iPad"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyUp(keyevent('keyup', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + }); + + it('should toggle caps lock on key release on mac', function () { + window.navigator.platform = "Mac"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyUp(keyevent('keyup', {code: 'CapsLock', key: 'CapsLock'})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xFFE5, "CapsLock", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xFFE5, "CapsLock", false); + }); + }); + + describe('Modifier status info', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + }); + + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + }); + + it('should provide caps lock state', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'A', NumLock: false, CapsLock: true})); + + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0x41, "KeyA", true, false, true); + }); + it('should provide num lock state', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'A', NumLock: true, CapsLock: false})); + + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0x41, "KeyA", true, true, false); + }); + + it('should have no num lock state on mac', function () { + window.navigator.platform = "Mac"; + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'A', NumLock: false, CapsLock: true})); + + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0x41, "KeyA", true, null, true); + }); + }); + + describe('Japanese IM keys on Windows', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + window.navigator.platform = "Windows"; + }); + + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + }); + + const keys = { 'Zenkaku': 0xff2a, 'Hankaku': 0xff2a, + 'Alphanumeric': 0xff30, 'Katakana': 0xff26, + 'Hiragana': 0xff25, 'Romaji': 0xff24, + 'KanaMode': 0xff24 }; + for (let [key, keysym] of Object.entries(keys)) { + it(`should fake key release for ${key} on Windows`, function () { + let kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'FakeIM', key: key})); + + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(keysym, "FakeIM", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(keysym, "FakeIM", false); + }); + } + }); + + describe('Escape AltGraph on Windows', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); window.navigator.platform = "Windows x86_64"; + + this.clock = sinon.useFakeTimers(); }); afterEach(function () { Object.defineProperty(window, "navigator", origNavigator); + if (this.clock !== undefined) { + this.clock.restore(); + } }); - it('should generate fake undo/redo events on press when AltGraph is down', function() { - var times_called = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - switch(times_called++) { - case 0: - expect(keysym).to.be.equal(0xFFE3); - expect(code).to.be.equal('ControlLeft'); - expect(down).to.be.equal(true); - break; - case 1: - expect(keysym).to.be.equal(0xFFEA); - expect(code).to.be.equal('AltRight'); - expect(down).to.be.equal(true); - break; - case 2: - expect(keysym).to.be.equal(0xFFEA); - expect(code).to.be.equal('AltRight'); - expect(down).to.be.equal(false); - break; - case 3: - expect(keysym).to.be.equal(0xFFE3); - expect(code).to.be.equal('ControlLeft'); - expect(down).to.be.equal(false); - break; - case 4: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(true); - break; - case 5: - expect(keysym).to.be.equal(0xFFE3); - expect(code).to.be.equal('ControlLeft'); - expect(down).to.be.equal(true); - break; - case 6: - expect(keysym).to.be.equal(0xFFEA); - expect(code).to.be.equal('AltRight'); - expect(down).to.be.equal(true); - break; - } - }; - // First the modifier combo + it('should supress ControlLeft until it knows if it is AltGr', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); - // Next a normal character - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - expect(times_called).to.be.equal(7); - }); - it('should no do anything on key release', function() { - var times_called = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - switch(times_called++) { - case 7: - expect(keysym).to.be.equal(0x61); - expect(code).to.be.equal('KeyA'); - expect(down).to.be.equal(false); - break; - } - }; - // First the modifier combo + expect(kbd.onkeyevent).to.not.have.been.called; + }); + + it('should not trigger on repeating ControlLeft', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); - // Next a normal character - kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); - kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); - expect(times_called).to.be.equal(8); - }); - it('should not consider a char modifier to be down on the modifier key itself', function() { - var times_called = 0; - var kbd = new Keyboard(document); - kbd.onkeyevent = function(keysym, code, down) { - switch(times_called++) { - case 0: - expect(keysym).to.be.equal(0xFFE3); - expect(code).to.be.equal('ControlLeft'); - expect(down).to.be.equal(true); - break; - case 1: - expect(keysym).to.be.equal(0xFFE9); - expect(code).to.be.equal('AltLeft'); - expect(down).to.be.equal(true); - break; - case 2: - expect(keysym).to.be.equal(0xFFE3); - expect(code).to.be.equal('ControlLeft'); - expect(down).to.be.equal(true); - break; - } - }; - // First the modifier combo kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - kbd._handleKeyDown(keyevent('keydown', {code: 'AltLeft', key: 'Alt', location: 1})); - // Then one of the keys again + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); + }); + + it('should not supress ControlRight', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'ControlRight', key: 'Control', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe4, "ControlRight", true); + }); + + it('should release ControlLeft after 100 ms', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); + expect(kbd.onkeyevent).to.not.have.been.called; + this.clock.tick(100); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe3, "ControlLeft", true); + }); + + it('should release ControlLeft on other key press', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); + expect(kbd.onkeyevent).to.not.have.been.called; + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0x61, "KeyA", true); + + // Check that the timer is properly dead + kbd.onkeyevent.resetHistory(); + this.clock.tick(100); + expect(kbd.onkeyevent).to.not.have.been.called; + }); + + it('should release ControlLeft on other key release', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); - expect(times_called).to.be.equal(3); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0x61, "KeyA", true); + kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); + expect(kbd.onkeyevent).to.have.been.calledThrice; + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); + expect(kbd.onkeyevent.thirdCall).to.have.been.calledWith(0x61, "KeyA", false); + + // Check that the timer is properly dead + kbd.onkeyevent.resetHistory(); + this.clock.tick(100); + expect(kbd.onkeyevent).to.not.have.been.called; + }); + + it('should generate AltGraph for quick Ctrl+Alt sequence', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1, timeStamp: Date.now()})); + this.clock.tick(20); + kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2, timeStamp: Date.now()})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xfe03, 'AltRight', true); + + // Check that the timer is properly dead + kbd.onkeyevent.resetHistory(); + this.clock.tick(100); + expect(kbd.onkeyevent).to.not.have.been.called; + }); + + it('should generate Ctrl, Alt for slow Ctrl+Alt sequence', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1, timeStamp: Date.now()})); + this.clock.tick(60); + kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2, timeStamp: Date.now()})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent.firstCall).to.have.been.calledWith(0xffe3, "ControlLeft", true); + expect(kbd.onkeyevent.secondCall).to.have.been.calledWith(0xffea, "AltRight", true); + + // Check that the timer is properly dead + kbd.onkeyevent.resetHistory(); + this.clock.tick(100); + expect(kbd.onkeyevent).to.not.have.been.called; + }); + + it('should pass through single Alt', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffea, 'AltRight', true); + }); + + it('should pass through single AltGr', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'AltGraph', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xfe03, 'AltRight', true); + }); + }); + + describe('Missing Shift keyup on Windows', function () { + let origNavigator; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); + + Object.defineProperty(window, "navigator", {value: {}}); + window.navigator.platform = "Windows x86_64"; + + this.clock = sinon.useFakeTimers(); + }); + afterEach(function () { + Object.defineProperty(window, "navigator", origNavigator); + if (this.clock !== undefined) { + this.clock.restore(); + } + }); + + it('should fake a left Shift keyup', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftLeft', key: 'Shift', location: 1})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftRight', key: 'Shift', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyUp(keyevent('keyup', {code: 'ShiftLeft', key: 'Shift', location: 1})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', false); + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', false); + }); + + it('should fake a right Shift keyup', function () { + const kbd = new Keyboard(document); + kbd.onkeyevent = sinon.spy(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftLeft', key: 'Shift', location: 1})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyDown(keyevent('keydown', {code: 'ShiftRight', key: 'Shift', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledOnce; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', true); + kbd.onkeyevent.resetHistory(); + + kbd._handleKeyUp(keyevent('keyup', {code: 'ShiftRight', key: 'Shift', location: 2})); + expect(kbd.onkeyevent).to.have.been.calledTwice; + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe2, 'ShiftRight', false); + expect(kbd.onkeyevent).to.have.been.calledWith(0xffe1, 'ShiftLeft', false); }); }); }); diff --git a/tests/test.localization.js b/tests/test.localization.js index 339144a50..916ff8462 100644 --- a/tests/test.localization.js +++ b/tests/test.localization.js @@ -1,76 +1,146 @@ -/* jshint expr: true */ +const expect = chai.expect; +import _, { Localizer, l10n } from '../app/localization.js'; -var assert = chai.assert; -var expect = chai.expect; +describe('Localization', function () { + "use strict"; -import l10nGet, { l10n } from '../app/localization.js'; + let origNavigator; + let fetch; -describe('Localization', function() { - "use strict"; + beforeEach(function () { + // window.navigator is a protected read-only property in many + // environments, so we need to redefine it whilst running these + // tests. + origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - describe('language selection', function () { - var origNavigator; - beforeEach(function () { - // window.navigator is a protected read-only property in many - // environments, so we need to redefine it whilst running these - // tests. - origNavigator = Object.getOwnPropertyDescriptor(window, "navigator"); - if (origNavigator === undefined) { - // Object.getOwnPropertyDescriptor() doesn't work - // properly in any version of IE - this.skip(); - } + Object.defineProperty(window, "navigator", {value: {}}); + window.navigator.languages = []; - Object.defineProperty(window, "navigator", {value: {}}); - if (window.navigator.languages !== undefined) { - // Object.defineProperty() doesn't work properly in old - // versions of Chrome - this.skip(); - } + fetch = sinon.stub(window, "fetch"); + fetch.resolves(new Response("{}")); + }); + afterEach(function () { + fetch.restore(); - window.navigator.languages = []; + Object.defineProperty(window, "navigator", origNavigator); + }); + + describe('Singleton', function () { + it('should export a singleton object', function () { + expect(l10n).to.be.instanceOf(Localizer); }); - afterEach(function () { - Object.defineProperty(window, "navigator", origNavigator); + it('should export a singleton translation function', async function () { + // FIXME: Can we use some spy instead? + window.navigator.languages = ["de"]; + fetch.resolves(new Response(JSON.stringify({ "Foobar": "gazonk" }))); + await l10n.setup(["de"]); + expect(_("Foobar")).to.equal("gazonk"); }); + }); - it('should use English by default', function() { - expect(l10n.language).to.equal('en'); + describe('language selection', function () { + it('should use English by default', function () { + let lclz = new Localizer(); + expect(lclz.language).to.equal('en'); }); - it('should use English if no user language matches', function() { + it('should use English if no user language matches', async function () { window.navigator.languages = ["nl", "de"]; - l10n.setup(["es", "fr"]); - expect(l10n.language).to.equal('en'); + let lclz = new Localizer(); + await lclz.setup(["es", "fr"]); + expect(lclz.language).to.equal('en'); }); - it('should use the most preferred user language', function() { + it('should fall back to generic English for other English', async function () { + window.navigator.languages = ["en-AU", "de"]; + let lclz = new Localizer(); + await lclz.setup(["de", "fr", "en-GB"]); + expect(lclz.language).to.equal('en'); + }); + it('should prefer specific English over generic', async function () { + window.navigator.languages = ["en-GB", "de"]; + let lclz = new Localizer(); + await lclz.setup(["de", "en-AU", "en-GB"]); + expect(lclz.language).to.equal('en-GB'); + }); + it('should use the most preferred user language', async function () { window.navigator.languages = ["nl", "de", "fr"]; - l10n.setup(["es", "fr", "de"]); - expect(l10n.language).to.equal('de'); + let lclz = new Localizer(); + await lclz.setup(["es", "fr", "de"]); + expect(lclz.language).to.equal('de'); }); - it('should prefer sub-languages languages', function() { + it('should prefer sub-languages languages', async function () { window.navigator.languages = ["pt-BR"]; - l10n.setup(["pt", "pt-BR"]); - expect(l10n.language).to.equal('pt-BR'); + let lclz = new Localizer(); + await lclz.setup(["pt", "pt-BR"]); + expect(lclz.language).to.equal('pt-BR'); }); - it('should fall back to language "parents"', function() { + it('should fall back to language "parents"', async function () { window.navigator.languages = ["pt-BR"]; - l10n.setup(["fr", "pt", "de"]); - expect(l10n.language).to.equal('pt'); + let lclz = new Localizer(); + await lclz.setup(["fr", "pt", "de"]); + expect(lclz.language).to.equal('pt'); }); - it('should not use specific language when user asks for a generic language', function() { + it('should not use specific language when user asks for a generic language', async function () { window.navigator.languages = ["pt", "de"]; - l10n.setup(["fr", "pt-BR", "de"]); - expect(l10n.language).to.equal('de'); + let lclz = new Localizer(); + await lclz.setup(["fr", "pt-BR", "de"]); + expect(lclz.language).to.equal('de'); }); - it('should handle underscore as a separator', function() { + it('should handle underscore as a separator', async function () { window.navigator.languages = ["pt-BR"]; - l10n.setup(["pt_BR"]); - expect(l10n.language).to.equal('pt_BR'); + let lclz = new Localizer(); + await lclz.setup(["pt_BR"]); + expect(lclz.language).to.equal('pt_BR'); }); - it('should handle difference in case', function() { + it('should handle difference in case', async function () { window.navigator.languages = ["pt-br"]; - l10n.setup(["pt-BR"]); - expect(l10n.language).to.equal('pt-BR'); + let lclz = new Localizer(); + await lclz.setup(["pt-BR"]); + expect(lclz.language).to.equal('pt-BR'); + }); + }); + + describe('Translation loading', function () { + it('should not fetch a translation for English', async function () { + window.navigator.languages = []; + let lclz = new Localizer(); + await lclz.setup([]); + expect(fetch).to.not.have.been.called; + }); + it('should fetch dictionary relative base URL', async function () { + window.navigator.languages = ["de", "fr"]; + fetch.resolves(new Response('{ "Foobar": "gazonk" }')); + let lclz = new Localizer(); + await lclz.setup(["ru", "fr"], "/some/path/"); + expect(fetch).to.have.been.calledOnceWith("/some/path/fr.json"); + expect(lclz.get("Foobar")).to.equal("gazonk"); + }); + it('should handle base URL without trailing slash', async function () { + window.navigator.languages = ["de", "fr"]; + fetch.resolves(new Response('{ "Foobar": "gazonk" }')); + let lclz = new Localizer(); + await lclz.setup(["ru", "fr"], "/some/path"); + expect(fetch).to.have.been.calledOnceWith("/some/path/fr.json"); + expect(lclz.get("Foobar")).to.equal("gazonk"); + }); + it('should handle current base URL', async function () { + window.navigator.languages = ["de", "fr"]; + fetch.resolves(new Response('{ "Foobar": "gazonk" }')); + let lclz = new Localizer(); + await lclz.setup(["ru", "fr"]); + expect(fetch).to.have.been.calledOnceWith("fr.json"); + expect(lclz.get("Foobar")).to.equal("gazonk"); + }); + it('should fail if dictionary cannot be found', async function () { + window.navigator.languages = ["de", "fr"]; + fetch.resolves(new Response('{}', { status: 404 })); + let lclz = new Localizer(); + let ok = false; + try { + await lclz.setup(["ru", "fr"], "/some/path/"); + } catch (e) { + ok = true; + } + expect(ok).to.be.true; }); }); }); diff --git a/tests/test.mouse.js b/tests/test.mouse.js deleted file mode 100644 index 248a93347..000000000 --- a/tests/test.mouse.js +++ /dev/null @@ -1,299 +0,0 @@ -var assert = chai.assert; -var expect = chai.expect; - -import sinon from '../vendor/sinon.js'; - -import Mouse from '../core/input/mouse.js'; -import * as eventUtils from '../core/util/events.js'; - -/* jshint newcap: false, expr: true */ -describe('Mouse Event Handling', function() { - "use strict"; - - sinon.stub(eventUtils, 'setCapture'); - // This function is only used on target (the canvas) - // and for these tests we can assume that the canvas is 100x100 - // located at coordinates 10x10 - sinon.stub(Element.prototype, 'getBoundingClientRect').returns( - {left: 10, right: 110, top: 10, bottom: 110, width: 100, height: 100}); - var target = document.createElement('canvas'); - - // The real constructors might not work everywhere we - // want to run these tests - var mouseevent, touchevent; - mouseevent = touchevent = function(typeArg, MouseEventInit) { - var e = { type: typeArg }; - for (var key in MouseEventInit) { - e[key] = MouseEventInit[key]; - } - e.stopPropagation = sinon.spy(); - e.preventDefault = sinon.spy(); - return e; - }; - - describe('Decode Mouse Events', function() { - it('should decode mousedown events', function(done) { - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - expect(bmask).to.be.equal(0x01); - expect(down).to.be.equal(1); - done(); - }; - mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); - }); - it('should decode mouseup events', function(done) { - var calls = 0; - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - expect(bmask).to.be.equal(0x01); - if (calls++ === 1) { - expect(down).to.not.be.equal(1); - done(); - } - }; - mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); - mouse._handleMouseUp(mouseevent('mouseup', { button: '0x01' })); - }); - it('should decode mousemove events', function(done) { - var mouse = new Mouse(target); - mouse.onmousemove = function(x, y) { - // Note that target relative coordinates are sent - expect(x).to.be.equal(40); - expect(y).to.be.equal(10); - done(); - }; - mouse._handleMouseMove(mouseevent('mousemove', - { clientX: 50, clientY: 20 })); - }); - it('should decode mousewheel events', function(done) { - var calls = 0; - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - calls++; - expect(bmask).to.be.equal(1<<6); - if (calls === 1) { - expect(down).to.be.equal(1); - } else if (calls === 2) { - expect(down).to.not.be.equal(1); - done(); - } - }; - mouse._handleMouseWheel(mouseevent('mousewheel', - { deltaX: 50, deltaY: 0, - deltaMode: 0})); - }); - }); - - describe('Double-click for Touch', function() { - - beforeEach(function () { this.clock = sinon.useFakeTimers(); }); - afterEach(function () { this.clock.restore(); }); - - it('should use same pos for 2nd tap if close enough', function(done) { - var calls = 0; - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - done(); - } - }; - // touch events are sent in an array of events - // with one item for each touch point - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(200); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 67, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 66, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if far apart', function(done) { - var calls = 0; - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(200); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 57, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 56, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if not soon enough', function(done) { - var calls = 0; - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 78, clientY: 46 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 79, clientY: 45 }]})); - this.clock.tick(500); - mouse._handleMouseDown(touchevent( - 'touchstart', { touches: [{ clientX: 67, clientY: 35 }]})); - this.clock.tick(10); - mouse._handleMouseUp(touchevent( - 'touchend', { touches: [{ clientX: 66, clientY: 36 }]})); - }); - - it('should not modify 2nd tap pos if not touch', function(done) { - var calls = 0; - var mouse = new Mouse(target); - mouse.onmousebutton = function(x, y, down, bmask) { - calls++; - if (calls === 1) { - expect(down).to.be.equal(1); - expect(x).to.be.equal(68); - expect(y).to.be.equal(36); - } else if (calls === 3) { - expect(down).to.be.equal(1); - expect(x).to.not.be.equal(68); - expect(y).to.not.be.equal(36); - done(); - } - }; - mouse._handleMouseDown(mouseevent( - 'mousedown', { button: '0x01', clientX: 78, clientY: 46 })); - this.clock.tick(10); - mouse._handleMouseUp(mouseevent( - 'mouseup', { button: '0x01', clientX: 79, clientY: 45 })); - this.clock.tick(200); - mouse._handleMouseDown(mouseevent( - 'mousedown', { button: '0x01', clientX: 67, clientY: 35 })); - this.clock.tick(10); - mouse._handleMouseUp(mouseevent( - 'mouseup', { button: '0x01', clientX: 66, clientY: 36 })); - }); - - }); - - describe('Accumulate mouse wheel events with small delta', function() { - - beforeEach(function () { this.clock = sinon.useFakeTimers(); }); - afterEach(function () { this.clock.restore(); }); - - it('should accumulate wheel events if small enough', function () { - var mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - - // threshold is 10 - expect(mouse._accumulatedWheelDeltaX).to.be.equal(8); - - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 0, deltaMode: 0 })); - - expect(mouse.onmousebutton).to.have.callCount(2); // mouse down and up - - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 4, deltaY: 9, deltaMode: 0 })); - - expect(mouse._accumulatedWheelDeltaX).to.be.equal(4); - expect(mouse._accumulatedWheelDeltaY).to.be.equal(9); - - expect(mouse.onmousebutton).to.have.callCount(2); // still - }); - - it('should not accumulate large wheel events', function () { - var mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 11, deltaY: 0, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 0, deltaY: 70, deltaMode: 0 })); - this.clock.tick(10); - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 400, deltaY: 400, deltaMode: 0 })); - - expect(mouse.onmousebutton).to.have.callCount(8); // mouse down and up - }); - - it('should send even small wheel events after a timeout', function () { - var mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 1, deltaY: 0, deltaMode: 0 })); - this.clock.tick(51); // timeout on 50 ms - - expect(mouse.onmousebutton).to.have.callCount(2); // mouse down and up - }); - - it('should account for non-zero deltaMode', function () { - var mouse = new Mouse(target); - mouse.onmousebutton = sinon.spy(); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 0, deltaY: 2, deltaMode: 1 })); - - this.clock.tick(10); - - mouse._handleMouseWheel(mouseevent( - 'mousewheel', { clientX: 18, clientY: 40, - deltaX: 1, deltaY: 0, deltaMode: 2 })); - - expect(mouse.onmousebutton).to.have.callCount(4); // mouse down and up - }); - }); - -}); diff --git a/tests/test.raw.js b/tests/test.raw.js new file mode 100644 index 000000000..4a634ccd0 --- /dev/null +++ b/tests/test.raw.js @@ -0,0 +1,154 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import RawDecoder from '../core/decoders/raw.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +describe('Raw Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new RawDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle the Raw encoding', function () { + let done; + + done = testDecodeRect(decoder, 0, 0, 2, 2, + [0xff, 0x00, 0x00, 0, + 0x00, 0xff, 0x00, 0, + 0x00, 0xff, 0x00, 0, + 0xff, 0x00, 0x00, 0], + display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 0, 2, 2, + [0x00, 0x00, 0xff, 0, + 0x00, 0x00, 0xff, 0, + 0x00, 0x00, 0xff, 0, + 0x00, 0x00, 0xff, 0], + display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 2, 4, 1, + [0xee, 0x00, 0xff, 0, + 0x00, 0xee, 0xff, 0, + 0xaa, 0xee, 0xff, 0, + 0xab, 0xee, 0xff, 0], + display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 3, 4, 1, + [0xee, 0x00, 0xff, 0, + 0x00, 0xee, 0xff, 0, + 0xaa, 0xee, 0xff, 0, + 0xab, 0xee, 0xff, 0], + display, 24); + expect(done).to.be.true; + + let targetData = new Uint8Array([ + 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255, + 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255 + ]); + + expect(display).to.have.displayed(targetData); + }); + + it('should handle the Raw encoding in low colour mode', function () { + let done; + + done = testDecodeRect(decoder, 0, 0, 2, 2, + [0x30, 0x30, 0x30, 0x30], + display, 8); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 0, 2, 2, + [0x0c, 0x0c, 0x0c, 0x0c], + display, 8); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 2, 4, 1, + [0x0c, 0x0c, 0x30, 0x30], + display, 8); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 3, 4, 1, + [0x0c, 0x0c, 0x30, 0x30], + display, 8); + expect(done).to.be.true; + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(display).to.have.displayed(targetData); + }); + + it('should handle empty rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, [], display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle empty rects in low colour mode', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, [], display, 8); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); +}); diff --git a/tests/test.rfb.js b/tests/test.rfb.js index 81ee1dd66..62b80ca3f 100644 --- a/tests/test.rfb.js +++ b/tests/test.rfb.js @@ -1,102 +1,272 @@ -/* jshint expr: true */ -var assert = chai.assert; -var expect = chai.expect; +const expect = chai.expect; import RFB from '../core/rfb.js'; import Websock from '../core/websock.js'; +import ZStream from "../vendor/pako/lib/zlib/zstream.js"; +import { deflateInit, deflate, Z_DEFAULT_COMPRESSION } from "../vendor/pako/lib/zlib/deflate.js"; import { encodings } from '../core/encodings.js'; +import { toUnsigned32bit } from '../core/util/int.js'; +import { encodeUTF8 } from '../core/util/strings.js'; +import KeyTable from '../core/input/keysym.js'; +import legacyCrypto from '../core/crypto/crypto.js'; import FakeWebSocket from './fake.websocket.js'; -import sinon from '../vendor/sinon.js'; -var push8 = function (arr, num) { +function push8(arr, num) { "use strict"; arr.push(num & 0xFF); -}; +} -var push16 = function (arr, num) { +function push16(arr, num) { "use strict"; arr.push((num >> 8) & 0xFF, - num & 0xFF); -}; + num & 0xFF); +} -var push32 = function (arr, num) { +function push32(arr, num) { "use strict"; arr.push((num >> 24) & 0xFF, - (num >> 16) & 0xFF, - (num >> 8) & 0xFF, - num & 0xFF); -}; + (num >> 16) & 0xFF, + (num >> 8) & 0xFF, + num & 0xFF); +} + +function pushString(arr, string) { + let utf8 = unescape(encodeURIComponent(string)); + for (let i = 0; i < utf8.length; i++) { + arr.push(utf8.charCodeAt(i)); + } +} + +function deflateWithSize(data) { + // Adds the size of the string in front before deflating + + let unCompData = []; + unCompData.push((data.length >> 24) & 0xFF, + (data.length >> 16) & 0xFF, + (data.length >> 8) & 0xFF, + (data.length & 0xFF)); + + for (let i = 0; i < data.length; i++) { + unCompData.push(data.charCodeAt(i)); + } -describe('Remote Frame Buffer Protocol Client', function() { - var clock; + let strm = new ZStream(); + let chunkSize = 1024 * 10 * 10; + strm.output = new Uint8Array(chunkSize); + deflateInit(strm, Z_DEFAULT_COMPRESSION); + + /* eslint-disable camelcase */ + strm.input = unCompData; + strm.avail_in = strm.input.length; + strm.next_in = 0; + strm.next_out = 0; + strm.avail_out = chunkSize; + /* eslint-enable camelcase */ + + deflate(strm, 3); + + return new Uint8Array(strm.output.buffer, 0, strm.next_out); +} + +describe('Remote Frame Buffer Protocol Client', function () { + let clock; + let raf; + let fakeResizeObserver = null; + const realObserver = window.ResizeObserver; + + // Since we are using fake timers we don't actually want + // to wait for the browser to observe the size change, + // that's why we use a fake ResizeObserver + class FakeResizeObserver { + constructor(handler) { + this.fire = handler; + fakeResizeObserver = this; + } + disconnect() {} + observe(target, options) {} + unobserve(target) {} + } before(FakeWebSocket.replace); after(FakeWebSocket.restore); before(function () { - this.clock = clock = sinon.useFakeTimers(); + this.clock = clock = sinon.useFakeTimers(Date.now()); + // sinon doesn't support this yet + raf = window.requestAnimationFrame; + window.requestAnimationFrame = setTimeout; + // We must do this in a 'before' since it needs to be set before + // the RFB constructor, which runs in beforeEach further down + window.ResizeObserver = FakeResizeObserver; // Use a single set of buffers instead of reallocating to // speed up tests - var sock = new Websock(); - var _sQ = new Uint8Array(sock._sQbufferSize); - var rQ = new Uint8Array(sock._rQbufferSize); + const sock = new Websock(); + const _sQ = new Uint8Array(sock._sQbufferSize); + const rQ = new Uint8Array(sock._rQbufferSize); - Websock.prototype._old_allocate_buffers = Websock.prototype._allocate_buffers; - Websock.prototype._allocate_buffers = function () { + Websock.prototype._oldAllocateBuffers = Websock.prototype._allocateBuffers; + Websock.prototype._allocateBuffers = function () { this._sQ = _sQ; this._rQ = rQ; }; + // Avoiding printing the entire Websock buffer on errors + Websock.prototype.inspect = function () { return "[object Websock]"; }; }); after(function () { - Websock.prototype._allocate_buffers = Websock.prototype._old_allocate_buffers; + Websock.prototype._allocateBuffers = Websock.prototype._oldAllocateBuffers; + delete Websock.prototype.inspect; this.clock.restore(); + window.requestAnimationFrame = raf; + window.ResizeObserver = realObserver; + }); + + let container; + let rfbs; + + beforeEach(function () { + // Create a container element for all RFB objects to attach to + container = document.createElement('div'); + container.style.width = "100%"; + container.style.height = "100%"; + document.body.appendChild(container); + + // And track all created RFB objects + rfbs = []; + }); + afterEach(function () { + // Make sure every created RFB object is properly cleaned up + // or they might affect subsequent tests + rfbs.forEach(function (rfb) { + rfb.disconnect(); + expect(rfb._disconnect).to.have.been.called; + }); + rfbs = []; + + document.body.removeChild(container); + container = null; }); - function make_rfb (url, options) { + function makeRFB(url, options) { url = url || 'wss://host:8675'; - var rfb = new RFB(document.createElement('canvas'), url, options); + const rfb = new RFB(container, url, options); clock.tick(); rfb._sock._websocket._open(); - rfb._rfb_connection_state = 'connected'; + rfb._rfbConnectionState = 'connected'; + sinon.spy(rfb, "_disconnect"); + rfbs.push(rfb); return rfb; } describe('Connecting/Disconnecting', function () { - describe('#RFB', function () { - it('should set the current state to "connecting"', function () { - var client = new RFB(document.createElement('canvas'), 'wss://host:8675'); - client._rfb_connection_state = ''; - this.clock.tick(); - expect(client._rfb_connection_state).to.equal('connecting'); + describe('#RFB (constructor)', function () { + let open, attach; + beforeEach(function () { + open = sinon.spy(Websock.prototype, 'open'); + attach = sinon.spy(Websock.prototype, 'attach'); + }); + afterEach(function () { + open.restore(); + attach.restore(); }); it('should actually connect to the websocket', function () { - var client = new RFB(document.createElement('canvas'), 'ws://HOST:8675/PATH'); - sinon.spy(client._sock, 'open'); - this.clock.tick(); - expect(client._sock.open).to.have.been.calledOnce; - expect(client._sock.open).to.have.been.calledWith('ws://HOST:8675/PATH'); + new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); + expect(open).to.have.been.calledOnceWithExactly('ws://HOST:8675/PATH', []); + }); + + it('should pass on connection problems', function () { + open.restore(); + open = sinon.stub(Websock.prototype, 'open'); + open.throws(new Error('Failure')); + expect(() => new RFB(document.createElement('div'), 'ws://HOST:8675/PATH')).to.throw('Failure'); + }); + + it('should handle WebSocket/RTCDataChannel objects', function () { + let sock = new FakeWebSocket('ws://HOST:8675/PATH', []); + new RFB(document.createElement('div'), sock); + expect(open).to.not.have.been.called; + expect(attach).to.have.been.calledOnceWithExactly(sock); + }); + + it('should handle already open WebSocket/RTCDataChannel objects', function () { + let sock = new FakeWebSocket('ws://HOST:8675/PATH', []); + sock._open(); + const client = new RFB(document.createElement('div'), sock); + let callback = sinon.spy(); + client.addEventListener('disconnect', callback); + expect(open).to.not.have.been.called; + expect(attach).to.have.been.calledOnceWithExactly(sock); + // Check if it is ready for some data + sock._receiveData(new Uint8Array(['R', 'F', 'B', '0', '0', '3', '0', '0', '8'])); + expect(callback).to.not.have.been.called; + }); + + it('should refuse closed WebSocket/RTCDataChannel objects', function () { + let sock = new FakeWebSocket('ws://HOST:8675/PATH', []); + sock.readyState = WebSocket.CLOSED; + expect(() => new RFB(document.createElement('div'), sock)).to.throw(); + }); + + it('should pass on attach problems', function () { + attach.restore(); + attach = sinon.stub(Websock.prototype, 'attach'); + attach.throws(new Error('Failure')); + let sock = new FakeWebSocket('ws://HOST:8675/PATH', []); + expect(() => new RFB(document.createElement('div'), sock)).to.throw('Failure'); }); }); describe('#disconnect', function () { - var client; + let client; + let close; + beforeEach(function () { - client = make_rfb(); + client = makeRFB(); + close = sinon.stub(Websock.prototype, "close"); + }); + afterEach(function () { + close.restore(); }); - it('should go to state "disconnecting" before "disconnected"', function () { - sinon.spy(client, '_updateConnectionState'); + it('should start closing WebSocket', function () { + let callback = sinon.spy(); + client.addEventListener('disconnect', callback); + client.disconnect(); + expect(close).to.have.been.calledOnceWithExactly(); + expect(callback).to.not.have.been.called; + }); + + it('should send disconnect event', function () { + let callback = sinon.spy(); + client.addEventListener('disconnect', callback); + client.disconnect(); + close.thisValues[0]._eventHandlers.close(new CloseEvent("close", { 'code': 1000, 'reason': "", 'wasClean': true })); + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.true; + }); + + it('should force disconnect if disconnecting takes too long', function () { + let callback = sinon.spy(); + client.addEventListener('disconnect', callback); + client.disconnect(); + this.clock.tick(3 * 1000); + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.true; + }); + + it('should not fail if disconnect completes before timeout', function () { + let callback = sinon.spy(); + client.addEventListener('disconnect', callback); client.disconnect(); - expect(client._updateConnectionState).to.have.been.calledTwice; - expect(client._updateConnectionState.getCall(0).args[0]) - .to.equal('disconnecting'); - expect(client._updateConnectionState.getCall(1).args[0]) - .to.equal('disconnected'); - expect(client._rfb_connection_state).to.equal('disconnected'); + client._updateConnectionState('disconnecting'); + this.clock.tick(3 * 1000 / 2); + close.thisValues[0]._eventHandlers.close(new CloseEvent("close", { 'code': 1000, 'reason': "", 'wasClean': true })); + this.clock.tick(3 * 1000 / 2 + 1); + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.true; }); it('should unregister error event handler', function () { @@ -117,167 +287,211 @@ describe('Remote Frame Buffer Protocol Client', function() { expect(client._sock.off).to.have.been.calledWith('open'); }); }); - - describe('#sendCredentials', function () { - var client; - beforeEach(function () { - client = make_rfb(); - client._rfb_connection_state = 'connecting'; - }); - - it('should set the rfb credentials properly"', function () { - client.sendCredentials({ password: 'pass' }); - expect(client._rfb_credentials).to.deep.equal({ password: 'pass' }); - }); - - it('should call init_msg "soon"', function () { - client._init_msg = sinon.spy(); - client.sendCredentials({ password: 'pass' }); - this.clock.tick(5); - expect(client._init_msg).to.have.been.calledOnce; - }); - }); }); describe('Public API Basic Behavior', function () { - var client; + let client; beforeEach(function () { - client = make_rfb(); + client = makeRFB(); }); describe('#sendCtrlAlDel', function () { it('should sent ctrl[down]-alt[down]-del[down] then del[up]-alt[up]-ctrl[up]', function () { - var expected = {_sQ: new Uint8Array(48), _sQlen: 0, flush: function () {}}; - RFB.messages.keyEvent(expected, 0xFFE3, 1); - RFB.messages.keyEvent(expected, 0xFFE9, 1); - RFB.messages.keyEvent(expected, 0xFFFF, 1); - RFB.messages.keyEvent(expected, 0xFFFF, 0); - RFB.messages.keyEvent(expected, 0xFFE9, 0); - RFB.messages.keyEvent(expected, 0xFFE3, 0); + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.keyEvent(esock, 0xFFE3, 1); + RFB.messages.keyEvent(esock, 0xFFE9, 1); + RFB.messages.keyEvent(esock, 0xFFFF, 1); + RFB.messages.keyEvent(esock, 0xFFFF, 0); + RFB.messages.keyEvent(esock, 0xFFE9, 0); + RFB.messages.keyEvent(esock, 0xFFE3, 0); + let expected = ews._getSentData(); client.sendCtrlAltDel(); - expect(client._sock).to.have.sent(expected._sQ); + + expect(client._sock).to.have.sent(expected); }); it('should not send the keys if we are not in a normal state', function () { - sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "broken"; + client._rfbConnectionState = "connecting"; client.sendCtrlAltDel(); - expect(client._sock.flush).to.not.have.been.called; + expect(client._sock).to.have.sent(new Uint8Array([])); }); it('should not send the keys if we are set as view_only', function () { - sinon.spy(client._sock, 'flush'); client._viewOnly = true; client.sendCtrlAltDel(); - expect(client._sock.flush).to.not.have.been.called; + expect(client._sock).to.have.sent(new Uint8Array([])); }); }); describe('#sendKey', function () { it('should send a single key with the given code and state (down = true)', function () { - var expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}}; - RFB.messages.keyEvent(expected, 123, 1); + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.keyEvent(esock, 123, 1); + let expected = ews._getSentData(); + client.sendKey(123, 'Key123', true); - expect(client._sock).to.have.sent(expected._sQ); + + expect(client._sock).to.have.sent(expected); }); it('should send both a down and up event if the state is not specified', function () { - var expected = {_sQ: new Uint8Array(16), _sQlen: 0, flush: function () {}}; - RFB.messages.keyEvent(expected, 123, 1); - RFB.messages.keyEvent(expected, 123, 0); + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.keyEvent(esock, 123, 1); + RFB.messages.keyEvent(esock, 123, 0); + let expected = ews._getSentData(); + client.sendKey(123, 'Key123'); - expect(client._sock).to.have.sent(expected._sQ); + + expect(client._sock).to.have.sent(expected); }); it('should not send the key if we are not in a normal state', function () { - sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "broken"; + client._rfbConnectionState = "connecting"; client.sendKey(123, 'Key123'); - expect(client._sock.flush).to.not.have.been.called; + expect(client._sock).to.have.sent(new Uint8Array([])); }); it('should not send the key if we are set as view_only', function () { - sinon.spy(client._sock, 'flush'); client._viewOnly = true; client.sendKey(123, 'Key123'); - expect(client._sock.flush).to.not.have.been.called; + expect(client._sock).to.have.sent(new Uint8Array([])); }); it('should send QEMU extended events if supported', function () { client._qemuExtKeyEventSupported = true; - var expected = {_sQ: new Uint8Array(12), _sQlen: 0, flush: function () {}}; - RFB.messages.QEMUExtendedKeyEvent(expected, 0x20, true, 0x0039); + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.QEMUExtendedKeyEvent(esock, 0x20, true, 0x0039); + let expected = ews._getSentData(); + client.sendKey(0x20, 'Space', true); - expect(client._sock).to.have.sent(expected._sQ); + + expect(client._sock).to.have.sent(expected); }); it('should not send QEMU extended events if unknown key code', function () { client._qemuExtKeyEventSupported = true; - var expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}}; - RFB.messages.keyEvent(expected, 123, 1); + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.keyEvent(esock, 123, 1); + let expected = ews._getSentData(); + client.sendKey(123, 'FooBar', true); - expect(client._sock).to.have.sent(expected._sQ); + + expect(client._sock).to.have.sent(expected); }); }); - describe('#clipboardPasteFrom', function () { - it('should send the given text in a paste event', function () { - var expected = {_sQ: new Uint8Array(11), _sQlen: 0, flush: function () {}}; - RFB.messages.clientCutText(expected, 'abc'); - client.clipboardPasteFrom('abc'); - expect(client._sock).to.have.sent(expected._sQ); + describe('#focus', function () { + it('should move focus to canvas object', function () { + sinon.spy(client._canvas, "focus"); + client.focus(); + expect(client._canvas.focus).to.have.been.calledOnce; }); - it('should not send the text if we are not in a normal state', function () { - sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "broken"; - client.clipboardPasteFrom('abc'); - expect(client._sock.flush).to.not.have.been.called; + it('should include focus options', function () { + sinon.spy(client._canvas, "focus"); + client.focus({ foobar: 12, gazonk: true }); + expect(client._canvas.focus).to.have.been.calledOnce; + expect(client._canvas.focus).to.have.been.calledWith({ foobar: 12, gazonk: true}); }); }); - describe("#requestDesktopSize", function () { - beforeEach(function() { - client._supportsSetDesktopSize = true; + describe('#blur', function () { + it('should remove focus from canvas object', function () { + sinon.spy(client._canvas, "blur"); + client.blur(); + expect(client._canvas.blur).to.have.been.calledOnce; }); + }); - it('should send the request with the given width and height', function () { - var expected = [251]; - push8(expected, 0); // padding - push16(expected, 1); // width - push16(expected, 2); // height - push8(expected, 1); // number-of-screens - push8(expected, 0); // padding before screen array - push32(expected, 0); // id - push16(expected, 0); // x-position - push16(expected, 0); // y-position - push16(expected, 1); // width - push16(expected, 2); // height - push32(expected, 0); // flags - - client.requestDesktopSize(1, 2); - expect(client._sock).to.have.sent(new Uint8Array(expected)); + describe('#clipboardPasteFrom', function () { + describe('Clipboard update handling', function () { + beforeEach(function () { + sinon.spy(RFB.messages, 'clientCutText'); + sinon.spy(RFB.messages, 'extendedClipboardNotify'); + }); + + afterEach(function () { + RFB.messages.clientCutText.restore(); + RFB.messages.extendedClipboardNotify.restore(); + }); + + it('should send the given text in an clipboard update', function () { + client.clipboardPasteFrom('abc'); + + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(client._sock, + new Uint8Array([97, 98, 99])); + }); + + it('should mask unsupported characters', function () { + client.clipboardPasteFrom('abc€'); + + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(client._sock, + new Uint8Array([97, 98, 99, 63])); + }); + + it('should mask characters, not UTF-16 code points', function () { + client.clipboardPasteFrom('😂'); + + expect(RFB.messages.clientCutText).to.have.been.calledOnce; + expect(RFB.messages.clientCutText).to.have.been.calledWith(client._sock, + new Uint8Array([63])); + }); + + it('should send an notify if extended clipboard is supported by server', function () { + // Send our capabilities + let data = [3, 0, 0, 0]; + const flags = [0x1F, 0x00, 0x00, 0x01]; + let fileSizes = [0x00, 0x00, 0x00, 0x1E]; + + push32(data, toUnsigned32bit(-8)); + data = data.concat(flags); + data = data.concat(fileSizes); + client._sock._websocket._receiveData(new Uint8Array(data)); + + client.clipboardPasteFrom('extended test'); + expect(RFB.messages.extendedClipboardNotify).to.have.been.calledOnce; + }); }); - it('should not send the request if the client has not recieved a ExtendedDesktopSize rectangle', function () { + it('should flush multiple times for large clipboards', function () { sinon.spy(client._sock, 'flush'); - client._supportsSetDesktopSize = false; - client.requestDesktopSize(1,2); - expect(client._sock.flush).to.not.have.been.called; + let longText = ""; + for (let i = 0; i < client._sock._sQbufferSize + 100; i++) { + longText += 'a'; + } + client.clipboardPasteFrom(longText); + expect(client._sock.flush).to.have.been.calledTwice; }); - it('should not send the request if we are not in a normal state', function () { + it('should not send the text if we are not in a normal state', function () { sinon.spy(client._sock, 'flush'); - client._rfb_connection_state = "broken"; - client.requestDesktopSize(1,2); + client._rfbConnectionState = "connecting"; + client.clipboardPasteFrom('abc'); expect(client._sock.flush).to.not.have.been.called; }); }); describe("XVP operations", function () { beforeEach(function () { - client._rfb_xvp_ver = 1; + client._rfbXvpVer = 1; }); it('should send the shutdown signal on #machineShutdown', function () { @@ -303,1635 +517,4701 @@ describe('Remote Frame Buffer Protocol Client', function() { }); }); - describe('Misc Internals', function () { - describe('#_updateConnectionState', function () { - var client; - beforeEach(function () { - client = make_rfb(); - }); + describe('Clipping', function () { + let client; - it('should clear the disconnect timer if the state is not "disconnecting"', function () { - var spy = sinon.spy(); - client._disconnTimer = setTimeout(spy, 50); - client._rfb_connection_state = 'connecting'; - client._updateConnectionState('connected'); - this.clock.tick(51); - expect(spy).to.not.have.been.called; - expect(client._disconnTimer).to.be.null; - }); + beforeEach(function () { + client = makeRFB(); + container.style.width = '70px'; + container.style.height = '80px'; + client.clipViewport = true; + }); - it('should set the rfb_connection_state', function () { - client._rfb_connection_state = 'disconnecting'; - client._updateConnectionState('disconnected'); - expect(client._rfb_connection_state).to.equal('disconnected'); - }); + it('should update display clip state when changing the property', function () { + const spy = sinon.spy(client._display, "clipViewport", ["set"]); - it('should not change the state when we are disconnected', function () { - client._rfb_connection_state = 'disconnected'; - client._updateConnectionState('connecting'); - expect(client._rfb_connection_state).to.not.equal('connecting'); - }); + client.clipViewport = false; + expect(spy.set).to.have.been.calledOnce; + expect(spy.set).to.have.been.calledWith(false); + spy.set.resetHistory(); - it('should ignore state changes to the same state', function () { - var connectSpy = sinon.spy(); - var disconnectSpy = sinon.spy(); - client.addEventListener("connect", connectSpy); - client.addEventListener("disconnect", disconnectSpy); + client.clipViewport = true; + expect(spy.set).to.have.been.calledOnce; + expect(spy.set).to.have.been.calledWith(true); + }); - client._rfb_connection_state = 'connected'; - client._updateConnectionState('connected'); - expect(connectSpy).to.not.have.been.called; + it('should update the viewport when the container size changes', function () { + sinon.spy(client._display, "viewportChangeSize"); - client._rfb_connection_state = 'disconnected'; - client._updateConnectionState('disconnected'); - expect(disconnectSpy).to.not.have.been.called; - }); + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); - it('should ignore illegal state changes', function () { - var spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'connected'; - client._updateConnectionState('disconnected'); - expect(client._rfb_connection_state).to.not.equal('disconnected'); - expect(spy).to.not.have.been.called; - }); + expect(client._display.viewportChangeSize).to.have.been.calledOnce; + expect(client._display.viewportChangeSize).to.have.been.calledWith(40, 50); }); - describe('#_fail', function () { - var client; - beforeEach(function () { - client = make_rfb(); - }); + it('should update the viewport when the remote session resizes', function () { + // Simple ExtendedDesktopSize FBU message + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xcc, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, + 0x00, 0x00, 0x00, 0x00 ]; + + sinon.spy(client._display, "viewportChangeSize"); + + client._sock._websocket._receiveData(new Uint8Array(incoming)); + // The resize will cause scrollbars on the container, this causes a + // resize observation in the browsers + fakeResizeObserver.fire(); + clock.tick(1000); + + // FIXME: Display implicitly calls viewportChangeSize() when + // resizing the framebuffer, hence calledTwice. + expect(client._display.viewportChangeSize).to.have.been.calledTwice; + expect(client._display.viewportChangeSize).to.have.been.calledWith(70, 80); + }); - it('should close the WebSocket connection', function () { - sinon.spy(client._sock, 'close'); - client._fail(); - expect(client._sock.close).to.have.been.calledOnce; - }); + it('should not update the viewport if not clipping', function () { + client.clipViewport = false; + sinon.spy(client._display, "viewportChangeSize"); - it('should transition to disconnected', function () { - sinon.spy(client, '_updateConnectionState'); - client._fail(); - this.clock.tick(2000); - expect(client._updateConnectionState).to.have.been.called; - expect(client._rfb_connection_state).to.equal('disconnected'); - }); + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); - it('should set clean_disconnect variable', function () { - client._rfb_clean_disconnect = true; - client._rfb_connection_state = 'connected'; - client._fail(); - expect(client._rfb_clean_disconnect).to.be.false; - }); + expect(client._display.viewportChangeSize).to.not.have.been.called; + }); - it('should result in disconnect event with clean set to false', function () { - client._rfb_connection_state = 'connected'; - var spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._fail(); - this.clock.tick(2000); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.clean).to.be.false; - }); + it('should not update the viewport if scaling', function () { + client.scaleViewport = true; + sinon.spy(client._display, "viewportChangeSize"); - }); - }); + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); - describe('Connection States', function () { - describe('connecting', function () { - it('should open the websocket connection', function () { - var client = new RFB(document.createElement('canvas'), - 'ws://HOST:8675/PATH'); - sinon.spy(client._sock, 'open'); - this.clock.tick(); - expect(client._sock.open).to.have.been.calledOnce; - }); + expect(client._display.viewportChangeSize).to.not.have.been.called; }); - describe('connected', function () { - var client; + describe('Clipping and remote resize', function () { beforeEach(function () { - client = make_rfb(); + // Given a remote (100, 100) larger than the container (70x80), + client._resize(100, 100); + client._supportsSetDesktopSize = true; + client.resizeSession = true; + sinon.spy(RFB.messages, "setDesktopSize"); }); - - it('should result in a connect event if state becomes connected', function () { - var spy = sinon.spy(); - client.addEventListener("connect", spy); - client._rfb_connection_state = 'connecting'; - client._updateConnectionState('connected'); - expect(spy).to.have.been.calledOnce; + afterEach(function () { + RFB.messages.setDesktopSize.restore(); }); - - it('should not result in a connect event if the state is not "connected"', function () { - var spy = sinon.spy(); - client.addEventListener("connect", spy); - client._sock._websocket.open = function () {}; // explicitly don't call onopen - client._updateConnectionState('connecting'); - expect(spy).to.not.have.been.called; + it('should not change remote size when changing clipping', function () { + // When changing clipping the scrollbars of the container + // will appear and disappear and thus trigger resize observations + client.clipViewport = false; + fakeResizeObserver.fire(); + clock.tick(1000); + client.clipViewport = true; + fakeResizeObserver.fire(); + clock.tick(1000); + + // Then no resize requests should be sent + expect(RFB.messages.setDesktopSize).to.not.have.been.called; }); }); - describe('disconnecting', function () { - var client; + describe('Dragging', function () { beforeEach(function () { - client = make_rfb(); + client.dragViewport = true; + sinon.spy(RFB.messages, "pointerEvent"); }); - it('should force disconnect if we do not call Websock.onclose within the disconnection timeout', function () { - sinon.spy(client, '_updateConnectionState'); - client._sock._websocket.close = function () {}; // explicitly don't call onclose - client._updateConnectionState('disconnecting'); - this.clock.tick(3 * 1000); - expect(client._updateConnectionState).to.have.been.calledTwice; - expect(client._rfb_disconnect_reason).to.not.equal(""); - expect(client._rfb_connection_state).to.equal("disconnected"); + afterEach(function () { + RFB.messages.pointerEvent.restore(); }); - it('should not fail if Websock.onclose gets called within the disconnection timeout', function () { - client._updateConnectionState('disconnecting'); - this.clock.tick(3 * 1000 / 2); - client._sock._websocket.close(); - this.clock.tick(3 * 1000 / 2 + 1); - expect(client._rfb_connection_state).to.equal('disconnected'); + it('should not send button messages when initiating viewport dragging', function () { + client._handleMouseButton(13, 9, 0x001); + expect(RFB.messages.pointerEvent).to.not.have.been.called; }); - it('should close the WebSocket connection', function () { - sinon.spy(client._sock, 'close'); - client._updateConnectionState('disconnecting'); - expect(client._sock.close).to.have.been.calledOnce; - }); - }); + it('should send button messages when release without movement', function () { + // Just up and down + client._handleMouseButton(13, 9, 0x001); + client._handleMouseButton(13, 9, 0x000); + expect(RFB.messages.pointerEvent).to.have.been.calledTwice; - describe('disconnected', function () { - var client; - beforeEach(function () { client = make_rfb(); }); + RFB.messages.pointerEvent.resetHistory(); - it('should result in a disconnect event if state becomes "disconnected"', function () { - var spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'disconnecting'; - client._updateConnectionState('disconnected'); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.clean).to.be.true; + // Small movement + client._handleMouseButton(13, 9, 0x001); + client._handleMouseMove(15, 14); + client._handleMouseButton(15, 14, 0x000); + expect(RFB.messages.pointerEvent).to.have.been.calledTwice; }); - it('should not result in a disconnect event if the state is not "disconnected"', function () { - var spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._sock._websocket.close = function () {}; // explicitly don't call onclose - client._updateConnectionState('disconnecting'); - expect(spy).to.not.have.been.called; + it('should not send button messages when in view only', function () { + client._viewOnly = true; + client._handleMouseButton(13, 9, 0x001); + client._handleMouseButton(13, 9, 0x000); + expect(RFB.messages.pointerEvent).to.not.have.been.called; }); - it('should result in a disconnect event without msg when no reason given', function () { - var spy = sinon.spy(); - client.addEventListener("disconnect", spy); - client._rfb_connection_state = 'disconnecting'; - client._rfb_disconnect_reason = ""; - client._updateConnectionState('disconnected'); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0].length).to.equal(1); + it('should send button message directly when drag is disabled', function () { + client.dragViewport = false; + client._handleMouseButton(13, 9, 0x001); + expect(RFB.messages.pointerEvent).to.have.been.calledOnce; }); - }); - }); - describe('Protocol Initialization States', function () { - var client; - beforeEach(function () { - client = make_rfb(); - client._rfb_connection_state = 'connecting'; - }); + it('should be initiate viewport dragging on sufficient movement', function () { + sinon.spy(client._display, "viewportChangePos"); - describe('ProtocolVersion', function () { - function send_ver (ver, client) { - var arr = new Uint8Array(12); - for (var i = 0; i < ver.length; i++) { - arr[i+4] = ver.charCodeAt(i); - } - arr[0] = 'R'; arr[1] = 'F'; arr[2] = 'B'; arr[3] = ' '; - arr[11] = '\n'; - client._sock._websocket._receive_data(arr); - } + // Too small movement - describe('version parsing', function () { - it('should interpret version 003.003 as version 3.3', function () { - send_ver('003.003', client); - expect(client._rfb_version).to.equal(3.3); - }); + client._handleMouseButton(13, 9, 0x001); + client._handleMouseMove(18, 9); - it('should interpret version 003.006 as version 3.3', function () { - send_ver('003.006', client); - expect(client._rfb_version).to.equal(3.3); - }); + expect(RFB.messages.pointerEvent).to.not.have.been.called; + expect(client._display.viewportChangePos).to.not.have.been.called; - it('should interpret version 003.889 as version 3.3', function () { - send_ver('003.889', client); - expect(client._rfb_version).to.equal(3.3); - }); + // Sufficient movement - it('should interpret version 003.007 as version 3.7', function () { - send_ver('003.007', client); - expect(client._rfb_version).to.equal(3.7); - }); + client._handleMouseMove(43, 9); - it('should interpret version 003.008 as version 3.8', function () { - send_ver('003.008', client); - expect(client._rfb_version).to.equal(3.8); - }); + expect(RFB.messages.pointerEvent).to.not.have.been.called; + expect(client._display.viewportChangePos).to.have.been.calledOnce; + expect(client._display.viewportChangePos).to.have.been.calledWith(-30, 0); - it('should interpret version 004.000 as version 3.8', function () { - send_ver('004.000', client); - expect(client._rfb_version).to.equal(3.8); - }); + client._display.viewportChangePos.resetHistory(); - it('should interpret version 004.001 as version 3.8', function () { - send_ver('004.001', client); - expect(client._rfb_version).to.equal(3.8); - }); + // Now a small movement should move right away - it('should interpret version 005.000 as version 3.8', function () { - send_ver('005.000', client); - expect(client._rfb_version).to.equal(3.8); - }); + client._handleMouseMove(43, 14); - it('should fail on an invalid version', function () { - sinon.spy(client, "_fail"); - send_ver('002.000', client); - expect(client._fail).to.have.been.calledOnce; - }); + expect(RFB.messages.pointerEvent).to.not.have.been.called; + expect(client._display.viewportChangePos).to.have.been.calledOnce; + expect(client._display.viewportChangePos).to.have.been.calledWith(0, -5); }); - it('should send back the interpreted version', function () { - send_ver('004.000', client); + it('should not send button messages when dragging ends', function () { + // First the movement - var expected_str = 'RFB 003.008\n'; - var expected = []; - for (var i = 0; i < expected_str.length; i++) { - expected[i] = expected_str.charCodeAt(i); - } + client._handleMouseButton(13, 9, 0x001); + client._handleMouseMove(43, 9); + client._handleMouseButton(43, 9, 0x000); - expect(client._sock).to.have.sent(new Uint8Array(expected)); + expect(RFB.messages.pointerEvent).to.not.have.been.called; }); - it('should transition to the Security state on successful negotiation', function () { - send_ver('003.008', client); - expect(client._rfb_init_state).to.equal('Security'); - }); + it('should terminate viewport dragging on a button up event', function () { + // First the dragging movement - describe('Repeater', function () { - beforeEach(function () { - client = make_rfb('wss://host:8675', { repeaterID: "12345" }); - client._rfb_connection_state = 'connecting'; - }); + client._handleMouseButton(13, 9, 0x001); + client._handleMouseMove(43, 9); + client._handleMouseButton(43, 9, 0x000); - it('should interpret version 000.000 as a repeater', function () { - send_ver('000.000', client); - expect(client._rfb_version).to.equal(0); + // Another movement now should not move the viewport - var sent_data = client._sock._websocket._get_sent_data(); - expect(new Uint8Array(sent_data.buffer, 0, 9)).to.array.equal(new Uint8Array([73, 68, 58, 49, 50, 51, 52, 53, 0])); - expect(sent_data).to.have.length(250); - }); + sinon.spy(client._display, "viewportChangePos"); - it('should handle two step repeater negotiation', function () { - send_ver('000.000', client); - send_ver('003.008', client); - expect(client._rfb_version).to.equal(3.8); - }); + client._handleMouseMove(43, 59); + + expect(client._display.viewportChangePos).to.not.have.been.called; }); }); + }); - describe('Security', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - }); + describe('Scaling', function () { + let client; + beforeEach(function () { + client = makeRFB(); + container.style.width = '70px'; + container.style.height = '80px'; + client.scaleViewport = true; + }); - it('should simply receive the auth scheme when for versions < 3.7', function () { - client._rfb_version = 3.6; - var auth_scheme_raw = [1, 2, 3, 4]; - var auth_scheme = (auth_scheme_raw[0] << 24) + (auth_scheme_raw[1] << 16) + - (auth_scheme_raw[2] << 8) + auth_scheme_raw[3]; - client._sock._websocket._receive_data(auth_scheme_raw); - expect(client._rfb_auth_scheme).to.equal(auth_scheme); - }); + it('should update display scale factor when changing the property', function () { + const spy = sinon.spy(client._display, "scale", ["set"]); + sinon.spy(client._display, "autoscale"); - it('should prefer no authentication is possible', function () { - client._rfb_version = 3.7; - var auth_schemes = [2, 1, 3]; - client._sock._websocket._receive_data(auth_schemes); - expect(client._rfb_auth_scheme).to.equal(1); - expect(client._sock).to.have.sent(new Uint8Array([1, 1])); - }); + client.scaleViewport = false; + expect(spy.set).to.have.been.calledOnce; + expect(spy.set).to.have.been.calledWith(1.0); + expect(client._display.autoscale).to.not.have.been.called; - it('should choose for the most prefered scheme possible for versions >= 3.7', function () { - client._rfb_version = 3.7; - var auth_schemes = [2, 22, 16]; - client._sock._websocket._receive_data(auth_schemes); - expect(client._rfb_auth_scheme).to.equal(22); - expect(client._sock).to.have.sent(new Uint8Array([22])); - }); + client.scaleViewport = true; + expect(client._display.autoscale).to.have.been.calledOnce; + expect(client._display.autoscale).to.have.been.calledWith(70, 80); + }); - it('should fail if there are no supported schemes for versions >= 3.7', function () { - sinon.spy(client, "_fail"); - client._rfb_version = 3.7; - var auth_schemes = [1, 32]; - client._sock._websocket._receive_data(auth_schemes); - expect(client._fail).to.have.been.calledOnce; - }); + it('should update the clipping setting when changing the property', function () { + client.clipViewport = true; - it('should fail with the appropriate message if no types are sent for versions >= 3.7', function () { - client._rfb_version = 3.7; - var failure_data = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; - sinon.spy(client, '_fail'); - client._sock._websocket._receive_data(failure_data); + const spy = sinon.spy(client._display, "clipViewport", ["set"]); - expect(client._fail).to.have.been.calledOnce; - expect(client._fail).to.have.been.calledWith( - 'Security negotiation failed on no security types (reason: whoops)'); - }); + client.scaleViewport = false; + expect(spy.set).to.have.been.calledOnce; + expect(spy.set).to.have.been.calledWith(true); - it('should transition to the Authentication state and continue on successful negotiation', function () { - client._rfb_version = 3.7; - var auth_schemes = [1, 1]; - client._negotiate_authentication = sinon.spy(); - client._sock._websocket._receive_data(auth_schemes); - expect(client._rfb_init_state).to.equal('Authentication'); - expect(client._negotiate_authentication).to.have.been.calledOnce; - }); + spy.set.resetHistory(); + + client.scaleViewport = true; + expect(spy.set).to.have.been.calledOnce; + expect(spy.set).to.have.been.calledWith(false); }); - describe('Authentication', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - }); + it('should update the scaling when the container size changes', function () { + sinon.spy(client._display, "autoscale"); - function send_security(type, cl) { - cl._sock._websocket._receive_data(new Uint8Array([1, type])); - } + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); - it('should fail on auth scheme 0 (pre 3.7) with the given message', function () { - client._rfb_version = 3.6; - var err_msg = "Whoopsies"; - var data = [0, 0, 0, 0]; - var err_len = err_msg.length; - push32(data, err_len); - for (var i = 0; i < err_len; i++) { - data.push(err_msg.charCodeAt(i)); - } + expect(client._display.autoscale).to.have.been.calledOnce; + expect(client._display.autoscale).to.have.been.calledWith(40, 50); + }); - sinon.spy(client, '_fail'); - client._sock._websocket._receive_data(new Uint8Array(data)); - expect(client._fail).to.have.been.calledWith( - 'Security negotiation failed on authentication scheme (reason: Whoopsies)'); - }); + it('should update the scaling when the remote session resizes', function () { + // Simple ExtendedDesktopSize FBU message + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xcc, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, + 0x00, 0x00, 0x00, 0x00 ]; - it('should transition straight to SecurityResult on "no auth" (1) for versions >= 3.8', function () { - client._rfb_version = 3.8; - send_security(1, client); - expect(client._rfb_init_state).to.equal('SecurityResult'); - }); + sinon.spy(client._display, "autoscale"); - it('should transition straight to ServerInitialisation on "no auth" for versions < 3.8', function () { - client._rfb_version = 3.7; - send_security(1, client); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); - }); + client._sock._websocket._receiveData(new Uint8Array(incoming)); + // The resize will cause scrollbars on the container, this causes a + // resize observation in the browsers + fakeResizeObserver.fire(); + clock.tick(1000); - it('should fail on an unknown auth scheme', function () { - sinon.spy(client, "_fail"); - client._rfb_version = 3.8; - send_security(57, client); - expect(client._fail).to.have.been.calledOnce; - }); + expect(client._display.autoscale).to.have.been.calledOnce; + expect(client._display.autoscale).to.have.been.calledWith(70, 80); + }); - describe('VNC Authentication (type 2) Handler', function () { - beforeEach(function () { - client._rfb_init_state = 'Security'; - client._rfb_version = 3.8; - }); + it('should not update the display scale factor if not scaling', function () { + client.scaleViewport = false; + sinon.spy(client._display, "autoscale"); + + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(client._display.autoscale).to.not.have.been.called; + }); + }); + + describe('Remote resize', function () { + let client; + beforeEach(function () { + client = makeRFB(); + client.resizeSession = true; + container.style.width = '70px'; + container.style.height = '80px'; + + const incoming = [ 0x00, // msg-type=FBU + 0x00, // padding + 0x00, 0x01, // number of rects = 1 + 0x00, 0x00, // reason = server initialized + 0x00, 0x00, // status = no error + 0x00, 0x04, // new width = 4 + 0x00, 0x04, // new height = 4 + 0xff, 0xff, + 0xfe, 0xcc, // enc = (-308) ExtendedDesktopSize + 0x01, // number of screens = 1 + 0x00, 0x00, + 0x00, // padding + 0x78, 0x90, + 0xab, 0xcd, // screen id = 0 + 0x00, 0x00, // screen x = 0 + 0x00, 0x00, // screen y = 0 + 0x00, 0x04, // screen width = 4 + 0x00, 0x04, // screen height = 4 + 0x12, 0x34, + 0x56, 0x78]; // screen flags + client._sock._websocket._receiveData(new Uint8Array(incoming)); + + sinon.spy(RFB.messages, "setDesktopSize"); + }); + + afterEach(function () { + RFB.messages.setDesktopSize.restore(); + }); + + it('should only request a resize when turned on', function () { + client.resizeSession = false; + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + client.resizeSession = true; + expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; + }); + + it('should request a resize when initially connecting', function () { + // Create a new object that hasn't yet seen a + // ExtendedDesktopSize rect + client = makeRFB(); + client.resizeSession = true; + container.style.width = '70px'; + container.style.height = '80px'; + + // Simple ExtendedDesktopSize FBU message + const incoming = [ 0x00, // msg-type=FBU + 0x00, // padding + 0x00, 0x01, // number of rects = 1 + 0x00, 0x00, // reason = server initialized + 0x00, 0x00, // status = no error + 0x00, 0x04, // new width = 4 + 0x00, 0x04, // new height = 4 + 0xff, 0xff, + 0xfe, 0xcc, // enc = (-308) ExtendedDesktopSize + 0x01, // number of screens = 1 + 0x00, 0x00, + 0x00, // padding + 0x78, 0x90, + 0xab, 0xcd, // screen id = 0 + 0x00, 0x00, // screen x = 0 + 0x00, 0x00, // screen y = 0 + 0x00, 0x04, // screen width = 4 + 0x00, 0x04, // screen height = 4 + 0x12, 0x34, + 0x56, 0x78]; // screen flags + + // First message should trigger a resize + + client._sock._websocket._receiveData(new Uint8Array(incoming)); + + // It should match the current size of the container, + // not the reported size from the server + expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; + expect(RFB.messages.setDesktopSize).to.have.been.calledWith( + sinon.match.object, 70, 80, 0x7890abcd, 0x12345678); + + RFB.messages.setDesktopSize.resetHistory(); + + // Second message should not trigger a resize + + client._sock._websocket._receiveData(new Uint8Array(incoming)); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + }); + + it('should request a resize when the container resizes', function () { + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; + expect(RFB.messages.setDesktopSize).to.have.been.calledWith( + sinon.match.object, 40, 50, 0x7890abcd, 0x12345678); + }); + + it('should not request the same size twice', function () { + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; + expect(RFB.messages.setDesktopSize).to.have.been.calledWith( + sinon.match.object, 40, 50, 0x7890abcd, 0x12345678); + + // Server responds with the requested size 40x50 + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x28, 0x00, 0x32, 0xff, 0xff, 0xfe, 0xcc, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x32, + 0x00, 0x00, 0x00, 0x00]; + + client._sock._websocket._receiveData(new Uint8Array(incoming)); + clock.tick(1000); + + RFB.messages.setDesktopSize.resetHistory(); + + // size is still 40x50 + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + }); + + it('should not resize until the container size is stable', function () { + container.style.width = '20px'; + container.style.height = '30px'; + fakeResizeObserver.fire(); + clock.tick(400); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(400); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + + clock.tick(200); + + expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; + expect(RFB.messages.setDesktopSize).to.have.been.calledWith( + sinon.match.object, 40, 50, 0x7890abcd, 0x12345678); + }); + + it('should not resize when resize is disabled', function () { + client._resizeSession = false; + + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + }); + + it('should not resize when resize is not supported', function () { + client._supportsSetDesktopSize = false; + + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + }); + + it('should not resize when in view only mode', function () { + client._viewOnly = true; + + container.style.width = '40px'; + container.style.height = '50px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + }); + + it('should not try to override a server resize', function () { + // Simple ExtendedDesktopSize FBU message, new size: 100x100 + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x64, 0x00, 0x64, 0xff, 0xff, 0xfe, 0xcc, + 0x01, 0x00, 0x00, 0x00, 0xab, 0xab, 0xab, 0xab, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, + 0x11, 0x22, 0x33, 0x44 ]; + + // Note that this will cause the browser to display scrollbars + // since the framebuffer is 100x100 and the container is 70x80. + // The usable space (clientWidth/clientHeight) will be even smaller + // due to the scrollbars taking up space. + client._sock._websocket._receiveData(new Uint8Array(incoming)); + // The scrollbars cause the ResizeObserver to fire + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.not.have.been.called; + + // An actual size change must not be ignored afterwards + container.style.width = '120px'; + container.style.height = '130px'; + fakeResizeObserver.fire(); + clock.tick(1000); + + expect(RFB.messages.setDesktopSize).to.have.been.calledOnce; + expect(RFB.messages.setDesktopSize).to.have.been.calledWith( + sinon.match.object, 120, 130, 0xabababab, 0x11223344); + }); + }); + + describe('Misc Internals', function () { + describe('#_fail', function () { + let client; + beforeEach(function () { + client = makeRFB(); + }); + + it('should close the WebSocket connection', function () { + sinon.spy(client._sock, 'close'); + client._fail(); + expect(client._sock.close).to.have.been.calledOnce; + }); + + it('should transition to disconnected', function () { + sinon.spy(client, '_updateConnectionState'); + client._fail(); + this.clock.tick(2000); + expect(client._updateConnectionState).to.have.been.called; + expect(client._rfbConnectionState).to.equal('disconnected'); + }); + + it('should set clean_disconnect variable', function () { + client._rfbCleanDisconnect = true; + client._rfbConnectionState = 'connected'; + client._fail(); + expect(client._rfbCleanDisconnect).to.be.false; + }); + + it('should result in disconnect event with clean set to false', function () { + client._rfbConnectionState = 'connected'; + const spy = sinon.spy(); + client.addEventListener("disconnect", spy); + client._fail(); + this.clock.tick(2000); + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.clean).to.be.false; + }); + + }); + }); + + describe('Protocol Initialization States', function () { + let client; + beforeEach(function () { + client = makeRFB(); + client._rfbConnectionState = 'connecting'; + }); + + function sendVer(ver, client) { + const arr = new Uint8Array(12); + for (let i = 0; i < ver.length; i++) { + arr[i+4] = ver.charCodeAt(i); + } + arr[0] = 'R'; arr[1] = 'F'; arr[2] = 'B'; arr[3] = ' '; + arr[11] = '\n'; + client._sock._websocket._receiveData(arr); + } + + function sendSecurity(type, cl) { + cl._sock._websocket._receiveData(new Uint8Array([1, type])); + } + + describe('ProtocolVersion', function () { + describe('version parsing', function () { + it('should interpret version 003.003 as version 3.3', function () { + sendVer('003.003', client); + expect(client._rfbVersion).to.equal(3.3); + }); + + it('should interpret version 003.006 as version 3.3', function () { + sendVer('003.006', client); + expect(client._rfbVersion).to.equal(3.3); + }); + + it('should interpret version 003.889 as version 3.8', function () { + sendVer('003.889', client); + expect(client._rfbVersion).to.equal(3.8); + }); + + it('should interpret version 003.007 as version 3.7', function () { + sendVer('003.007', client); + expect(client._rfbVersion).to.equal(3.7); + }); + + it('should interpret version 003.008 as version 3.8', function () { + sendVer('003.008', client); + expect(client._rfbVersion).to.equal(3.8); + }); + + it('should interpret version 004.000 as version 3.8', function () { + sendVer('004.000', client); + expect(client._rfbVersion).to.equal(3.8); + }); + + it('should interpret version 004.001 as version 3.8', function () { + sendVer('004.001', client); + expect(client._rfbVersion).to.equal(3.8); + }); + + it('should interpret version 005.000 as version 3.8', function () { + sendVer('005.000', client); + expect(client._rfbVersion).to.equal(3.8); + }); + + it('should fail on an invalid version', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + sendVer('002.000', client); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + }); + + it('should send back the interpreted version', function () { + sendVer('004.000', client); + + const expectedStr = 'RFB 003.008\n'; + const expected = []; + for (let i = 0; i < expectedStr.length; i++) { + expected[i] = expectedStr.charCodeAt(i); + } + + expect(client._sock).to.have.sent(new Uint8Array(expected)); + }); + + it('should transition to the Security state on successful negotiation', function () { + sendVer('003.008', client); + expect(client._rfbInitState).to.equal('Security'); + }); + + describe('Repeater', function () { + beforeEach(function () { + client = makeRFB('wss://host:8675', { repeaterID: "12345" }); + client._rfbConnectionState = 'connecting'; + }); + + it('should interpret version 000.000 as a repeater', function () { + sendVer('000.000', client); + expect(client._rfbVersion).to.equal(0); + + const sentData = client._sock._websocket._getSentData(); + expect(new Uint8Array(sentData.buffer, 0, 9)).to.array.equal(new Uint8Array([73, 68, 58, 49, 50, 51, 52, 53, 0])); + expect(sentData).to.have.length(250); + }); + + it('should handle two step repeater negotiation', function () { + sendVer('000.000', client); + sendVer('003.008', client); + expect(client._rfbVersion).to.equal(3.8); + }); + }); + }); + + describe('Security', function () { + beforeEach(function () { + sendVer('003.008\n', client); + client._sock._websocket._getSentData(); + }); + + it('should respect server preference order', function () { + const authSchemes = [ 6, 79, 30, 188, 16, 6, 1 ]; + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); + expect(client._sock).to.have.sent(new Uint8Array([30])); + }); + + it('should fail if there are no supported schemes', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + const authSchemes = [1, 32]; + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + + it('should fail with the appropriate message if no types are sent', function () { + const failureData = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; + let callback = sinon.spy(); + client.addEventListener("securityfailure", callback); + + client._sock._websocket._receiveData(new Uint8Array(failureData)); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.status).to.equal(1); + expect(callback.args[0][0].detail.reason).to.equal("whoops"); + }); + + it('should transition to the Authentication state and continue on successful negotiation', function () { + const authSchemes = [1, 2]; + sinon.spy(client, "_negotiateAuthentication"); + client._sock._websocket._receiveData(new Uint8Array(authSchemes)); + expect(client._rfbInitState).to.equal('Authentication'); + expect(client._negotiateAuthentication).to.have.been.calledOnce; + }); + }); + + describe('Legacy Authentication', function () { + it('should fail on auth scheme 0 (pre 3.7) with the given message', function () { + const errMsg = "Whoopsies"; + const data = [0, 0, 0, 0]; + const errLen = errMsg.length; + push32(data, errLen); + for (let i = 0; i < errLen; i++) { + data.push(errMsg.charCodeAt(i)); + } + + sendVer('003.006\n', client); + client._sock._websocket._getSentData(); + let callback = sinon.spy(); + client.addEventListener("securityfailure", callback); + + client._sock._websocket._receiveData(new Uint8Array(data)); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.status).to.equal(1); + expect(callback.args[0][0].detail.reason).to.equal("Whoopsies"); + }); + + it('should transition straight to ServerInitialisation on "no auth" for versions < 3.7', function () { + sendVer('003.006\n', client); + client._sock._websocket._getSentData(); + + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 1])); + expect(client._rfbInitState).to.equal('ServerInitialisation'); + }); + + it('should transition straight to ServerInitialisation on "no auth" for versions < 3.8', function () { + sendVer('003.007\n', client); + client._sock._websocket._getSentData(); + + sendSecurity(1, client); + expect(client._rfbInitState).to.equal('ServerInitialisation'); + }); + }); + + describe('Authentication', function () { + beforeEach(function () { + sendVer('003.008\n', client); + client._sock._websocket._getSentData(); + }); + + it('should transition straight to SecurityResult on "no auth" (1)', function () { + sendSecurity(1, client); + expect(client._rfbInitState).to.equal('SecurityResult'); + }); + + it('should fail on an unknown auth scheme', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + sendSecurity(57, client); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + + describe('VNC Authentication (type 2) Handler', function () { it('should fire the credentialsrequired event if missing a password', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); + client.addEventListener("credentialsrequired", spy); + sendSecurity(2, client); + + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } + client._sock._websocket._receiveData(new Uint8Array(challenge)); + + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.types).to.have.members(["password"]); + }); + + it('should encrypt the password with DES and then send it back', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ password: 'passwd' }); + }); + sendSecurity(2, client); + client._sock._websocket._getSentData(); // skip the choice of auth reply + + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } + client._sock._websocket._receiveData(new Uint8Array(challenge)); + clock.tick(); + + const desPass = RFB.genDES('passwd', challenge); + expect(client._sock).to.have.sent(new Uint8Array(desPass)); + }); + + it('should transition to SecurityResult immediately after sending the password', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ password: 'passwd' }); + }); + sendSecurity(2, client); + + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } + client._sock._websocket._receiveData(new Uint8Array(challenge)); + clock.tick(); + + expect(client._rfbInitState).to.equal('SecurityResult'); + }); + }); + + describe('RSA-AES Authentication (type 6) Handler', function () { + function fakeGetRandomValues(arr) { + if (arr.length === 16) { + arr.set(new Uint8Array([ + 0x1c, 0x08, 0xfe, 0x21, 0x78, 0xef, 0x4e, 0xf9, + 0x3f, 0x05, 0xec, 0xea, 0xd4, 0x6b, 0xa5, 0xd5, + ])); + } else { + arr.set(new Uint8Array([ + 0xee, 0xe2, 0xf1, 0x5a, 0x3c, 0xa7, 0xbe, 0x95, + 0x6f, 0x2a, 0x75, 0xfd, 0x62, 0x01, 0xcb, 0xbf, + 0x43, 0x74, 0xca, 0x47, 0x4d, 0xfb, 0x0f, 0xcf, + 0x3a, 0x6d, 0x55, 0x6b, 0x59, 0x3a, 0xf6, 0x87, + 0xcb, 0x03, 0xb7, 0x28, 0x35, 0x7b, 0x15, 0x8e, + 0xb6, 0xc8, 0x8f, 0x2d, 0x5e, 0x7b, 0x1c, 0x9a, + 0x32, 0x55, 0xe7, 0x64, 0x36, 0x25, 0x7b, 0xa3, + 0xe9, 0x4f, 0x6f, 0x97, 0xdc, 0xa4, 0xd4, 0x62, + 0x6d, 0x7f, 0xab, 0x02, 0x6b, 0x13, 0x56, 0x69, + 0xfb, 0xd0, 0xd4, 0x13, 0x76, 0xcd, 0x0d, 0xd0, + 0x1f, 0xd1, 0x0c, 0x63, 0x3a, 0x34, 0x20, 0x6c, + 0xbb, 0x60, 0x45, 0x82, 0x23, 0xfd, 0x7c, 0x77, + 0x6d, 0xcc, 0x5e, 0xaa, 0xc3, 0x0c, 0x43, 0xb7, + 0x8d, 0xc0, 0x27, 0x6e, 0xeb, 0x1d, 0x6c, 0x5f, + 0xd8, 0x1c, 0x3c, 0x1c, 0x60, 0x2e, 0x82, 0x15, + 0xfd, 0x2e, 0x5f, 0x3a, 0x15, 0x53, 0x14, 0x70, + 0x4f, 0xe1, 0x65, 0x68, 0x35, 0x6d, 0xc7, 0x64, + 0xdb, 0xdd, 0x09, 0x31, 0x4f, 0x7b, 0x6d, 0x6c, + 0x77, 0x59, 0x5e, 0x1e, 0xfa, 0x4b, 0x06, 0x14, + 0xbe, 0xdc, 0x9c, 0x3d, 0x7b, 0xed, 0xf3, 0x2b, + 0x19, 0x26, 0x11, 0x8e, 0x3f, 0xab, 0x73, 0x9a, + 0x0a, 0x3a, 0xaa, 0x85, 0x06, 0xd5, 0xca, 0x3f, + 0xc3, 0xe2, 0x33, 0x7f, 0x97, 0x74, 0x98, 0x8f, + 0x2f, 0xa5, 0xfc, 0x7e, 0xb1, 0x77, 0x71, 0x58, + 0xf0, 0xbc, 0x04, 0x59, 0xbb, 0xb4, 0xc6, 0xcc, + 0x0f, 0x06, 0xcd, 0xa2, 0xd5, 0x01, 0x2f, 0xb2, + 0x22, 0x0b, 0xfc, 0x1e, 0x59, 0x9f, 0xd3, 0x4f, + 0x30, 0x95, 0xc6, 0x80, 0x0f, 0x69, 0xf3, 0x4a, + 0xd4, 0x36, 0xb6, 0x5a, 0x0b, 0x16, 0x0d, 0x81, + 0x31, 0xb0, 0x69, 0xd4, 0x4e, + ])); + } + } + + async function fakeGeneratekey() { + let key = { "alg": "RSA-OAEP-256", + "d": "B7QR2yI8sXjo8vQhJpX9odqqR6wIuPr" + + "TM1B1JJEKVeSrr7OYcc1FRJ52Vap9LI" + + "AU-ezigs9QDvWMxknB8motLnG69Wck3" + + "7nt9_z4s8lFQp0nROA-oaR92HW34KNL" + + "1b2fEVWGI0N86h730MvTJC5O2cmKeMe" + + "zIG-oNqbbfFyP8AW-WLdDlgZm11-Fjz" + + "hbVpb0Bc7nRSgBPSV-EY6Sl-LuglxDx" + + "4LaTdQW7QE_WXoRUt-GYGfTseuFQQK5" + + "WeoyX3yBtQydpauW6rrgyWdtP4hDFIo" + + "ZsX6w1i-UMWMMwlIB5FdnUSi26igVGA" + + "DGpV_vGMP36bv-EHp0bY-Qp0gpIfLfgQ", + "dp": "Z1v5UceFfV2bhmbG19eGYb30jFxqoR" + + "Bq36PKNY7IunMs1keYy0FpLbyGhtgM" + + "Z1Ymmc8wEzGYsCPEP-ykcun_rlyu7Y" + + "xmcnyC9YQqTqLyqvO-7rUqDvk9TMfd" + + "qWFP6heADRhKZmEbmcau6_m2MwwK9k" + + "OkMKWvpqp8_TpJMnAH7zE", + "dq": "OBacRE15aY3NtCR4cvP5os3sT70JbD" + + "dDLHT3IHZM6rE35CYNpLDia2chm_wn" + + "McYvKFW9zC2ajRZ15i9c_VXQzS7ZlT" + + "aQYBFyMt7kVhxMEMFsPv1crD6t3uEI" + + "j0LNuNYyy0jkon_LPZKQFK654CiL-L" + + "2YaNXOH4HbHP02dWeVQIE", + "e": "AQAB", + "ext": true, + "key_ops": ["decrypt"], + "kty": "RSA", + "n": "m1c92ZFk9ZI6l_O4YFiNxbv0Ng94SB3" + + "yThy1P_mcqrGDQkRiGVdcTxAk38T9Pg" + + "LztmspF-6U5TAHO-gSmmW88AC9m6f1M" + + "spps6r7zl-M_OG-TwvGzf3BDz8zEg1F" + + "PbZV7whO1M4TCAZ0PqwG7qCc6nK1WiA" + + "haKrSpzuPdL1igfNBsX7qu5wgw4ZTTG" + + "SLbVC_LfULQ5FADgFTRXUSaxm1F8C_L" + + "wy6a2e4nTcXilmtN2IHUjHegzm-Tq2H" + + "izmR3ARdWJpESYIW5-AXoiqj29tDrqC" + + "mu2WPkB2psVp83IzZfaQNQzjNfvA8Gp" + + "imkcDCkP5VMRrtKCcG4ZAFnO-A3NBX_Q", + "p": "2Q_lNL7vCOBzAppYzCZo3WSh0hX-MOZ" + + "yPUznks5U2TjmfdNZoL6_FJRiGyyLvw" + + "SiZFdEAAvpAyESFfFigngAqMLSf448n" + + "Pg15VUGj533CotsEM0WpoEr1JCgqdUb" + + "gDAfJQIBcwOmegBqd7lWm7uzEnRCvou" + + "B70ybkJfpdprhkVE", + "q": "tzTt-F3g2u_3Ctj26Ho9iN_wC_W0lXG" + + "zslLt5nLmss8JqdLoDDrijjU-gjeRh7" + + "lgiuHdUc3dorfFKbaMNOjoW3QKqt9oZ" + + "1JM0HKeRw0X2PnWW_0WK6DK5ASWDTXb" + + "Mq2sUZqJvYEyL74H2Zrt0RPAux7XQLE" + + "VgND6ROdXnMJ70O0", + "qi": "qfl4cXQkz4BNqa2De0-PfdU-8d1w3o" + + "nnaGqx1Ds2fHzD_SJ4cNghn2TksoT9" + + "Qo64b3pUjH9igi2pyEjomk6D12N6FG" + + "0e10u7vFKv3W5YqUOgTpYdbcWHdZ2q" + + "ZWJU0XQZIrF8jLGTOO4GYP6_9sJ5R7" + + "Wk_0MdqQy8qvixWD4zLcY", + }; + key = await window.crypto.subtle.importKey("jwk", key, { + name: "RSA-OAEP", + hash: {name: "SHA-256"} + }, true, ["decrypt"]); + return {privateKey: key}; + } + + before(() => { + sinon.stub(window.crypto, "getRandomValues").callsFake(fakeGetRandomValues); + sinon.stub(window.crypto.subtle, "generateKey").callsFake(fakeGeneratekey); + }); + after(() => { + window.crypto.getRandomValues.restore(); + window.crypto.subtle.generateKey.restore(); + }); + + beforeEach(function () { + sendSecurity(6, client); + expect(client._sock).to.have.sent(new Uint8Array([6])); + }); + + const serverPublicKey = [ + 0x00, 0x00, 0x08, 0x00, 0xac, 0x1a, 0xbc, 0x42, + 0x8a, 0x2a, 0x69, 0x65, 0x54, 0xf8, 0x9a, 0xe6, + 0x43, 0xaa, 0xf7, 0x27, 0xf6, 0x2a, 0xf8, 0x8f, + 0x36, 0xd4, 0xae, 0x54, 0x0f, 0x16, 0x28, 0x08, + 0xc2, 0x5b, 0xca, 0x23, 0xdc, 0x27, 0x88, 0x1a, + 0x12, 0x82, 0xa8, 0x54, 0xea, 0x00, 0x99, 0x8d, + 0x02, 0x1d, 0x77, 0x4a, 0xeb, 0xd0, 0x93, 0x40, + 0x79, 0x86, 0xcb, 0x37, 0xd4, 0xb2, 0xc7, 0xcd, + 0x93, 0xe1, 0x00, 0x4d, 0x86, 0xff, 0x97, 0x33, + 0x0c, 0xad, 0x51, 0x47, 0x45, 0x85, 0x56, 0x07, + 0x65, 0x21, 0x7c, 0x57, 0x6d, 0x68, 0x7d, 0xd7, + 0x00, 0x43, 0x0c, 0x9d, 0x3b, 0xa1, 0x5a, 0x11, + 0xed, 0x51, 0x77, 0xf9, 0xd1, 0x5b, 0x33, 0xd7, + 0x1a, 0xeb, 0x65, 0x57, 0xc0, 0x01, 0x51, 0xff, + 0x9b, 0x82, 0xb3, 0xeb, 0x82, 0xc2, 0x1f, 0xca, + 0x47, 0xc0, 0x6a, 0x09, 0xe0, 0xf7, 0xda, 0x39, + 0x85, 0x12, 0xe7, 0x45, 0x8d, 0xb4, 0x1a, 0xda, + 0xcb, 0x86, 0x58, 0x52, 0x37, 0x66, 0x9d, 0x8a, + 0xce, 0xf2, 0x18, 0x78, 0x7d, 0x7f, 0xf0, 0x07, + 0x94, 0x8e, 0x6b, 0x17, 0xd9, 0x00, 0x2a, 0x3a, + 0xb9, 0xd4, 0x77, 0xde, 0x70, 0x85, 0xc4, 0x3a, + 0x62, 0x10, 0x02, 0xee, 0xba, 0xd8, 0xc0, 0x62, + 0xd0, 0x8e, 0xc1, 0x98, 0x19, 0x8e, 0x39, 0x0f, + 0x3e, 0x1d, 0x61, 0xb1, 0x93, 0x13, 0x59, 0x39, + 0xcb, 0x96, 0xf2, 0x17, 0xc9, 0xe1, 0x41, 0xd3, + 0x20, 0xdd, 0x62, 0x5e, 0x7d, 0x53, 0xd6, 0xb7, + 0x1d, 0xfe, 0x02, 0x18, 0x1f, 0xe0, 0xef, 0x3d, + 0x94, 0xe3, 0x0a, 0x9c, 0x59, 0x54, 0xd8, 0x98, + 0x16, 0x9c, 0x31, 0xda, 0x41, 0x0f, 0x2e, 0x71, + 0x68, 0xe0, 0xa2, 0x62, 0x3e, 0xe5, 0x25, 0x31, + 0xcf, 0xfc, 0x67, 0x63, 0xc3, 0xb0, 0xda, 0x3f, + 0x7b, 0x59, 0xbe, 0x7e, 0x9e, 0xa8, 0xd0, 0x01, + 0x4f, 0x43, 0x7f, 0x8d, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x01, + ]; + + const serverRandom = [ + 0x01, 0x00, 0x5b, 0x58, 0x2a, 0x96, 0x2d, 0xbb, + 0x88, 0xec, 0xc3, 0x54, 0x00, 0xf3, 0xbb, 0xbe, + 0x17, 0xa3, 0x84, 0xd3, 0xef, 0xd8, 0x4a, 0x31, + 0x09, 0x20, 0xdd, 0xbc, 0x16, 0x9d, 0xc9, 0x5b, + 0x99, 0x62, 0x86, 0xfe, 0x0b, 0x28, 0x4b, 0xfe, + 0x5b, 0x56, 0x2d, 0xcb, 0x6e, 0x6f, 0xec, 0xf0, + 0x53, 0x0c, 0x33, 0x84, 0x93, 0xc9, 0xbf, 0x79, + 0xde, 0xb3, 0xb9, 0x29, 0x60, 0x78, 0xde, 0xe6, + 0x1d, 0xa7, 0x89, 0x48, 0x3f, 0xd1, 0x58, 0x66, + 0x27, 0x9c, 0xd4, 0x6e, 0x72, 0x9c, 0x6e, 0x4a, + 0xc0, 0x69, 0x79, 0x6f, 0x79, 0x0f, 0x13, 0xc4, + 0x20, 0xcf, 0xa6, 0xbb, 0xce, 0x18, 0x6d, 0xd5, + 0x9e, 0xd9, 0x67, 0xbe, 0x61, 0x43, 0x67, 0x11, + 0x76, 0x2f, 0xfd, 0x78, 0x75, 0x2b, 0x89, 0x35, + 0xdd, 0x0f, 0x13, 0x7f, 0xee, 0x78, 0xad, 0x32, + 0x56, 0x21, 0x81, 0x08, 0x1f, 0xcf, 0x4c, 0x29, + 0xa3, 0xeb, 0x89, 0x2d, 0xbe, 0xba, 0x8d, 0xe4, + 0x69, 0x28, 0xba, 0x53, 0x82, 0xce, 0x5c, 0xf6, + 0x5e, 0x5e, 0xa5, 0xb3, 0x88, 0xd8, 0x3d, 0xab, + 0xf4, 0x24, 0x9e, 0x3f, 0x04, 0xaf, 0xdc, 0x48, + 0x90, 0x53, 0x37, 0xe6, 0x82, 0x1d, 0xe0, 0x15, + 0x91, 0xa1, 0xc6, 0xa9, 0x54, 0xe5, 0x2a, 0xb5, + 0x64, 0x2d, 0x93, 0xc0, 0xc0, 0xe1, 0x0f, 0x6a, + 0x4b, 0xdb, 0x77, 0xf8, 0x4a, 0x0f, 0x83, 0x36, + 0xdd, 0x5e, 0x1e, 0xdd, 0x39, 0x65, 0xa2, 0x11, + 0xc2, 0xcf, 0x56, 0x1e, 0xa1, 0x29, 0xae, 0x11, + 0x9f, 0x3a, 0x82, 0xc7, 0xbd, 0x89, 0x6e, 0x59, + 0xb8, 0x59, 0x17, 0xcb, 0x65, 0xa0, 0x4b, 0x4d, + 0xbe, 0x33, 0x32, 0x85, 0x9c, 0xca, 0x5e, 0x95, + 0xc2, 0x5a, 0xd0, 0xc9, 0x8b, 0xf1, 0xf5, 0x14, + 0xcf, 0x76, 0x80, 0xc2, 0x24, 0x0a, 0x39, 0x7e, + 0x60, 0x64, 0xce, 0xd9, 0xb8, 0xad, 0x24, 0xa8, + 0xdf, 0xcb, + ]; + + const serverHash = [ + 0x00, 0x14, 0x39, 0x30, 0x66, 0xb5, 0x66, 0x8a, + 0xcd, 0xb9, 0xda, 0xe0, 0xde, 0xcb, 0xf6, 0x47, + 0x5f, 0x54, 0x66, 0xe0, 0xbc, 0x49, 0x37, 0x01, + 0xf2, 0x9e, 0xef, 0xcc, 0xcd, 0x4d, 0x6c, 0x0e, + 0xc6, 0xab, 0x28, 0xd4, 0x7b, 0x13, + ]; + + const subType = [ + 0x00, 0x01, 0x30, 0x2a, 0xc3, 0x0b, 0xc2, 0x1c, + 0xeb, 0x02, 0x44, 0x92, 0x5d, 0xfd, 0xf9, 0xa7, + 0x94, 0xd0, 0x19, + ]; + + const clientPublicKey = [ + 0x00, 0x00, 0x08, 0x00, 0x9b, 0x57, 0x3d, 0xd9, + 0x91, 0x64, 0xf5, 0x92, 0x3a, 0x97, 0xf3, 0xb8, + 0x60, 0x58, 0x8d, 0xc5, 0xbb, 0xf4, 0x36, 0x0f, + 0x78, 0x48, 0x1d, 0xf2, 0x4e, 0x1c, 0xb5, 0x3f, + 0xf9, 0x9c, 0xaa, 0xb1, 0x83, 0x42, 0x44, 0x62, + 0x19, 0x57, 0x5c, 0x4f, 0x10, 0x24, 0xdf, 0xc4, + 0xfd, 0x3e, 0x02, 0xf3, 0xb6, 0x6b, 0x29, 0x17, + 0xee, 0x94, 0xe5, 0x30, 0x07, 0x3b, 0xe8, 0x12, + 0x9a, 0x65, 0xbc, 0xf0, 0x00, 0xbd, 0x9b, 0xa7, + 0xf5, 0x32, 0xca, 0x69, 0xb3, 0xaa, 0xfb, 0xce, + 0x5f, 0x8c, 0xfc, 0xe1, 0xbe, 0x4f, 0x0b, 0xc6, + 0xcd, 0xfd, 0xc1, 0x0f, 0x3f, 0x33, 0x12, 0x0d, + 0x45, 0x3d, 0xb6, 0x55, 0xef, 0x08, 0x4e, 0xd4, + 0xce, 0x13, 0x08, 0x06, 0x74, 0x3e, 0xac, 0x06, + 0xee, 0xa0, 0x9c, 0xea, 0x72, 0xb5, 0x5a, 0x20, + 0x21, 0x68, 0xaa, 0xd2, 0xa7, 0x3b, 0x8f, 0x74, + 0xbd, 0x62, 0x81, 0xf3, 0x41, 0xb1, 0x7e, 0xea, + 0xbb, 0x9c, 0x20, 0xc3, 0x86, 0x53, 0x4c, 0x64, + 0x8b, 0x6d, 0x50, 0xbf, 0x2d, 0xf5, 0x0b, 0x43, + 0x91, 0x40, 0x0e, 0x01, 0x53, 0x45, 0x75, 0x12, + 0x6b, 0x19, 0xb5, 0x17, 0xc0, 0xbf, 0x2f, 0x0c, + 0xba, 0x6b, 0x67, 0xb8, 0x9d, 0x37, 0x17, 0x8a, + 0x59, 0xad, 0x37, 0x62, 0x07, 0x52, 0x31, 0xde, + 0x83, 0x39, 0xbe, 0x4e, 0xad, 0x87, 0x8b, 0x39, + 0x91, 0xdc, 0x04, 0x5d, 0x58, 0x9a, 0x44, 0x49, + 0x82, 0x16, 0xe7, 0xe0, 0x17, 0xa2, 0x2a, 0xa3, + 0xdb, 0xdb, 0x43, 0xae, 0xa0, 0xa6, 0xbb, 0x65, + 0x8f, 0x90, 0x1d, 0xa9, 0xb1, 0x5a, 0x7c, 0xdc, + 0x8c, 0xd9, 0x7d, 0xa4, 0x0d, 0x43, 0x38, 0xcd, + 0x7e, 0xf0, 0x3c, 0x1a, 0x98, 0xa6, 0x91, 0xc0, + 0xc2, 0x90, 0xfe, 0x55, 0x31, 0x1a, 0xed, 0x28, + 0x27, 0x06, 0xe1, 0x90, 0x05, 0x9c, 0xef, 0x80, + 0xdc, 0xd0, 0x57, 0xfd, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x01, + ]; + + const clientRandom = [ + 0x01, 0x00, 0x84, 0x7f, 0x26, 0x54, 0x74, 0xf6, + 0x47, 0xaf, 0x33, 0x64, 0x0d, 0xa6, 0xe5, 0x30, + 0xba, 0xe6, 0xe4, 0x8e, 0x50, 0x40, 0x71, 0x1c, + 0x0e, 0x06, 0x63, 0xf5, 0x07, 0x2a, 0x26, 0x68, + 0xd6, 0xcf, 0xa6, 0x80, 0x84, 0x5e, 0x64, 0xd4, + 0x5e, 0x62, 0x31, 0xfe, 0x44, 0x51, 0x0b, 0x7c, + 0x4d, 0x55, 0xc5, 0x4a, 0x7e, 0x0d, 0x4d, 0x9b, + 0x84, 0xb4, 0x32, 0x2b, 0x4d, 0x8a, 0x34, 0x8d, + 0xc8, 0xcf, 0x19, 0x3b, 0x64, 0x82, 0x27, 0x9e, + 0xa7, 0x70, 0x2a, 0xc1, 0xb8, 0xf3, 0x6a, 0x3a, + 0xf2, 0x75, 0x6e, 0x1d, 0xeb, 0xb6, 0x70, 0x7a, + 0x15, 0x18, 0x38, 0x00, 0xb4, 0x4f, 0x55, 0xb5, + 0xd8, 0x03, 0x4e, 0xb8, 0x53, 0xff, 0x80, 0x62, + 0xf1, 0x9d, 0x27, 0xe8, 0x2a, 0x3d, 0x98, 0x19, + 0x32, 0x09, 0x7e, 0x9a, 0xb0, 0xc7, 0x46, 0x23, + 0x10, 0x85, 0x35, 0x00, 0x96, 0xce, 0xb3, 0x2c, + 0x84, 0x8d, 0xf4, 0x9e, 0xa8, 0x42, 0x67, 0xed, + 0x09, 0xa6, 0x09, 0x97, 0xb3, 0x64, 0x26, 0xfb, + 0x71, 0x11, 0x9b, 0x3f, 0xbb, 0x57, 0xb8, 0x5b, + 0x2e, 0xc5, 0x2d, 0x8c, 0x5c, 0xf7, 0xef, 0x27, + 0x25, 0x88, 0x42, 0x45, 0x43, 0xa4, 0xe7, 0xde, + 0xea, 0xf9, 0x15, 0x7b, 0x5d, 0x66, 0x24, 0xce, + 0xf7, 0xc8, 0x2f, 0xc5, 0xc0, 0x3d, 0xcd, 0xf2, + 0x62, 0xfc, 0x1a, 0x5e, 0xec, 0xff, 0xf1, 0x1b, + 0xc8, 0xdb, 0xc1, 0x0f, 0x54, 0x66, 0x9e, 0xfd, + 0x99, 0x9b, 0x23, 0x70, 0x62, 0x37, 0x80, 0xad, + 0x91, 0x6b, 0x84, 0x85, 0x6a, 0x4c, 0x80, 0x9e, + 0x60, 0x8a, 0x93, 0xa3, 0xc8, 0x8e, 0xc4, 0x4b, + 0x4d, 0xb4, 0x8e, 0x3e, 0xaf, 0xce, 0xcd, 0x83, + 0xe5, 0x21, 0x90, 0x95, 0x20, 0x3c, 0x82, 0xb4, + 0x7c, 0xab, 0x63, 0x9c, 0xae, 0xc3, 0xc9, 0x71, + 0x1a, 0xec, 0x34, 0x18, 0x47, 0xec, 0x5c, 0x4d, + 0xed, 0x84, + ]; + + const clientHash = [ + 0x00, 0x14, 0x9c, 0x91, 0x9e, 0x76, 0xcf, 0x1e, + 0x66, 0x87, 0x5e, 0x29, 0xf1, 0x13, 0x80, 0xea, + 0x7d, 0xec, 0xae, 0xf9, 0x60, 0x01, 0xd3, 0x6f, + 0xb7, 0x9e, 0xb2, 0xcd, 0x2d, 0xc8, 0xf8, 0x84, + 0xb2, 0x9f, 0xc3, 0x7e, 0xb4, 0xbe, + ]; + + const credentialsData = [ + 0x00, 0x08, 0x9d, 0xc8, 0x3a, 0xb8, 0x80, 0x4f, + 0xe3, 0x52, 0xdb, 0x62, 0x9e, 0x97, 0x64, 0x82, + 0xa8, 0xa1, 0x6b, 0x7e, 0x4d, 0x68, 0x8c, 0x29, + 0x91, 0x38, + ]; + + it('should fire the serververification event', async function () { + let verification = new Promise((resolve, reject) => { + client.addEventListener("serververification", (e) => { + resolve(e.detail.publickey); + }); + }); + + client._sock._websocket._receiveData(new Uint8Array(serverPublicKey)); + client._sock._websocket._receiveData(new Uint8Array(serverRandom)); + + expect(await verification).to.deep.equal(new Uint8Array(serverPublicKey)); + }); + + it('should handle approveServer and fire the credentialsrequired event', async function () { + let verification = new Promise((resolve, reject) => { + client.addEventListener("serververification", (e) => { + resolve(e.detail.publickey); + }); + }); + let credentials = new Promise((resolve, reject) => { + client.addEventListener("credentialsrequired", (e) => { + resolve(e.detail.types); + }); + }); + + client._sock._websocket._receiveData(new Uint8Array(serverPublicKey)); + client._sock._websocket._receiveData(new Uint8Array(serverRandom)); + + await verification; + client.approveServer(); + + client._sock._websocket._receiveData(new Uint8Array(serverHash)); + client._sock._websocket._receiveData(new Uint8Array(subType)); + + expect(await credentials).to.have.members(["password"]); + }); + + it('should send credentials to server', async function () { + let verification = new Promise((resolve, reject) => { + client.addEventListener("serververification", (e) => { + resolve(e.detail.publickey); + }); + }); + let credentials = new Promise((resolve, reject) => { + client.addEventListener("credentialsrequired", (e) => { + resolve(e.detail.types); + }); + }); + + client._sock._websocket._receiveData(new Uint8Array(serverPublicKey)); + client._sock._websocket._receiveData(new Uint8Array(serverRandom)); + + await verification; + client.approveServer(); + + client._sock._websocket._receiveData(new Uint8Array(serverHash)); + client._sock._websocket._receiveData(new Uint8Array(subType)); + + await credentials; + + let expected = []; + expected = expected.concat(clientPublicKey); + expected = expected.concat(clientRandom); + expected = expected.concat(clientHash); + expect(client._sock).to.have.sent(new Uint8Array(expected)); + + client.sendCredentials({ "password": "123456" }); + clock.tick(); + + // FIXME: We don't have a good way to know when + // the async stuff is done, so we hook in + // to this internal function that is + // called at the end + await new Promise((resolve, reject) => { + sinon.stub(client._sock._websocket, "send") + .callsFake((data) => { + FakeWebSocket.prototype.send.call(client._sock._websocket, data); + resolve(); + }); + }); + + expect(client._sock).to.have.sent(new Uint8Array(credentialsData)); + }); + }); + + describe('ARD Authentication (type 30) Handler', function () { + let byteArray = new Uint8Array(Array.from(new Uint8Array(128).keys())); + function fakeGetRandomValues(arr) { + if (arr.length == 128) { + arr.set(byteArray); + } + return arr; + } + before(() => { + sinon.stub(window.crypto, "getRandomValues").callsFake(fakeGetRandomValues); + }); + after(() => { + window.crypto.getRandomValues.restore(); + }); + it('should fire the credentialsrequired event if all credentials are missing', function () { + const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); - send_security(2, client); + sendSecurity(30, client); + + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.types).to.have.members(["username", "password"]); + }); + + it('should fire the credentialsrequired event if some credentials are missing', function () { + const spy = sinon.spy(); + client.addEventListener("credentialsrequired", spy); + client.sendCredentials({ password: 'password'}); + sendSecurity(30, client); + + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.types).to.have.members(["username", "password"]); + }); + + it('should return properly encrypted credentials and public key', async function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'user', + password: 'password' }); + }); + sendSecurity(30, client); + + expect(client._sock).to.have.sent([30]); + + const generator = new Uint8Array([127, 255]); + const prime = new Uint8Array(byteArray); + const serverKey = legacyCrypto.generateKey( + { name: "DH", g: generator, p: prime }, false, ["deriveBits"]); + const clientKey = legacyCrypto.generateKey( + { name: "DH", g: generator, p: prime }, false, ["deriveBits"]); + const serverPublicKey = legacyCrypto.exportKey("raw", serverKey.publicKey); + const clientPublicKey = legacyCrypto.exportKey("raw", clientKey.publicKey); + + let data = []; + + data = data.concat(Array.from(generator)); + push16(data, prime.length); + data = data.concat(Array.from(prime)); + data = data.concat(Array.from(serverPublicKey)); + + client._sock._websocket._receiveData(new Uint8Array(data)); + + // FIXME: We don't have a good way to know when the + // async stuff is done, so we hook in to this + // internal function that is called at the + // end + await new Promise((resolve, reject) => { + sinon.stub(client, "_resumeAuthentication") + .callsFake(() => { + RFB.prototype._resumeAuthentication.call(client); + resolve(); + }); + }); + clock.tick(); + + expect(client._rfbInitState).to.equal('SecurityResult'); + + let expectEncrypted = new Uint8Array([ + 199, 39, 204, 95, 190, 70, 127, 66, 5, 106, 153, 228, 123, 236, 150, 206, + 62, 107, 11, 4, 21, 242, 92, 184, 9, 81, 35, 125, 56, 167, 1, 215, + 182, 145, 183, 75, 245, 197, 47, 19, 122, 94, 64, 76, 77, 163, 222, 143, + 186, 174, 84, 39, 244, 179, 227, 114, 83, 231, 42, 106, 205, 43, 159, 110, + 209, 240, 157, 246, 237, 206, 134, 153, 195, 112, 92, 60, 28, 234, 91, 66, + 131, 38, 187, 195, 110, 167, 212, 241, 32, 250, 212, 213, 202, 89, 180, 21, + 71, 217, 209, 81, 42, 61, 118, 248, 65, 123, 98, 78, 139, 111, 202, 137, + 50, 185, 37, 173, 58, 99, 187, 53, 42, 125, 13, 165, 232, 163, 151, 42, 0]); + + let output = new Uint8Array(256); + output.set(expectEncrypted, 0); + output.set(clientPublicKey, 128); + + expect(client._sock).to.have.sent(output); + }); + }); + + describe('MSLogonII Authentication (type 113) Handler', function () { + function fakeGetRandomValues(arr) { + if (arr.length == 8) { + arr.set(new Uint8Array([0, 0, 0, 0, 5, 6, 7, 8])); + } else if (arr.length == 256) { + arr.set(new Uint8Array(256)); + } else if (arr.length == 64) { + arr.set(new Uint8Array(64)); + } + return arr; + } + const expected = new Uint8Array([ + 0x00, 0x00, 0x00, 0x00, 0x0a, 0xbc, 0x7c, 0xfd, + 0x58, 0x34, 0xd2, 0x24, 0x44, 0x60, 0xf0, 0xd1, + 0xa3, 0x73, 0x32, 0x02, 0x07, 0xce, 0xc1, 0x3f, + 0x10, 0x53, 0xf1, 0xdd, 0x99, 0xad, 0x44, 0x18, + 0xa1, 0xc4, 0xac, 0xc1, 0x1c, 0x13, 0x11, 0x85, + 0x3a, 0x6f, 0xcb, 0xc6, 0xb1, 0x6c, 0x68, 0x47, + 0x85, 0x01, 0xbb, 0xfa, 0x23, 0x8c, 0x59, 0x47, + 0x67, 0x47, 0x56, 0x6e, 0x6f, 0x9f, 0x07, 0x76, + 0x2e, 0x90, 0x1e, 0xdc, 0x80, 0xc4, 0x4b, 0x72, + 0xd2, 0xd5, 0xcd, 0x4b, 0x14, 0xff, 0x05, 0x8b, + 0x8d, 0xf1, 0x9b, 0xe0, 0xff, 0xa5, 0x3b, 0x56, + 0xb9, 0x6f, 0x84, 0x3e, 0x15, 0x84, 0x31, 0x4e, + 0x10, 0x0b, 0x56, 0xf4, 0x10, 0x05, 0x02, 0xc7, + 0x05, 0x0b, 0xc9, 0x66, 0x75, 0x32, 0xd3, 0x74, + 0xfc, 0x8c, 0xcf, 0xbd, 0x2d, 0x53, 0xd7, 0xa7, + 0xca, 0x82, 0x12, 0xce, 0xbb, 0x33, 0x09, 0x3f, + 0xff, 0x76, 0x7c, 0xdf, 0x2c, 0x2f, 0x4d, 0x95, + 0x86, 0xe4, 0x10, 0x07, 0x75, 0x1a, 0x6d, 0xdb, + 0x05, 0x91, 0x70, 0x34, 0x5c, 0x12, 0xbc, 0x4e, + 0x5e, 0xd0, 0x21, 0x39, 0x25, 0x2b, 0x62, 0x19, + 0x29, 0xa5, 0xe6, 0x93, 0x7b, 0xf8, 0x3f, 0xcf, + 0xd7, 0x3f, 0x0c, 0xd2, 0x68, 0x2d, 0x1e, 0x01, + 0x1a, 0x31, 0xc1, 0x59, 0x04, 0x06, 0xf6, 0x3b, + 0xec, 0x38, 0xef, 0x1b, 0x5b, 0x39, 0x88, 0xd3, + 0xe0, 0x5b, 0xb9, 0xef, 0xc3, 0x82, 0xfa, 0xdf, + 0x04, 0xf7, 0x65, 0x56, 0x82, 0x77, 0xfd, 0x63, + 0x10, 0xd7, 0xab, 0x0b, 0x5e, 0xd9, 0x07, 0x81, + 0x9d, 0xce, 0x26, 0xfb, 0x5d, 0xa8, 0x59, 0x2a, + 0xd9, 0xb8, 0xac, 0xcd, 0x6e, 0x61, 0x07, 0x39, + 0x9f, 0x8d, 0xdf, 0x53, 0x44, 0xab, 0x28, 0x01, + 0x86, 0x4d, 0x07, 0x8a, 0x5b, 0xdd, 0xc1, 0x18, + 0x29, 0xaa, 0xa2, 0xbe, 0xe2, 0x9c, 0x9e, 0xb0, + 0xb3, 0x2b, 0x2c, 0x93, 0x3e, 0x82, 0x07, 0xa6, + 0xef, 0x21, 0x2c, 0xa7, 0xf0, 0x65, 0xba, 0xda, + 0x13, 0xe4, 0x41, 0x87, 0x36, 0x1c, 0xa5, 0x81, + 0xae, 0xf3, 0x3e, 0xda, 0x03, 0x09, 0x63, 0x4b, + 0xb5, 0x29, 0x49, 0xfa, 0xbb, 0xa6, 0x31, 0x3c, + 0xc8, 0x15, 0xfb, 0xfc, 0xd6, 0xff, 0x04, 0x92, + 0x56, 0xbc, 0x66, 0xf1, 0x78, 0xfb, 0x14, 0x79, + 0x48, 0xd2, 0xcf, 0x87, 0x60, 0x23, 0xcf, 0xdb, + 0x1b, 0xad, 0x42, 0x32, 0x4e, 0x6d, 0x1f, 0x49, + ]); + before(() => { + sinon.stub(window.crypto, "getRandomValues").callsFake(fakeGetRandomValues); + }); + after(() => { + window.crypto.getRandomValues.restore(); + }); + it('should send public value and encrypted credentials', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'username', + password: 'password123456' }); + }); + sendSecurity(113, client); + + expect(client._sock).to.have.sent([113]); + + const g = new Uint8Array([0, 0, 0, 0, 0, 1, 0, 1]); + const p = new Uint8Array([0, 0, 0, 0, 0x25, 0x18, 0x26, 0x17]); + const A = new Uint8Array([0, 0, 0, 0, 0x0e, 0x12, 0xd0, 0xf5]); + + client._sock._websocket._receiveData(g); + client._sock._websocket._receiveData(p); + client._sock._websocket._receiveData(A); + clock.tick(); + + expect(client._sock).to.have.sent(expected); + expect(client._rfbInitState).to.equal('SecurityResult'); + }); + }); + + describe('XVP Authentication (type 22) Handler', function () { + it('should fall through to standard VNC authentication upon completion', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'user', + target: 'target', + password: 'password' }); + }); + sinon.spy(client, "_negotiateStdVNCAuth"); + sendSecurity(22, client); + clock.tick(); + expect(client._negotiateStdVNCAuth).to.have.been.calledOnce; + }); + + it('should fire the credentialsrequired event if all credentials are missing', function () { + const spy = sinon.spy(); + client.addEventListener("credentialsrequired", spy); + sendSecurity(22, client); + + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.types).to.have.members(["username", "password", "target"]); + }); + + it('should fire the credentialsrequired event if some credentials are missing', function () { + const spy = sinon.spy(); + client.addEventListener("credentialsrequired", spy); + client.sendCredentials({ username: 'user', + target: 'target' }); + sendSecurity(22, client); + + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.types).to.have.members(["username", "password", "target"]); + }); + + it('should send user and target separately', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'user', + target: 'target', + password: 'password' }); + }); + sendSecurity(22, client); + clock.tick(); + + const expected = [22, 4, 6]; // auth selection, len user, len target + for (let i = 0; i < 10; i++) { expected[i+3] = 'usertarget'.charCodeAt(i); } + + expect(client._sock).to.have.sent(new Uint8Array(expected)); + }); + }); + + describe('TightVNC Authentication (type 16) Handler', function () { + beforeEach(function () { + sendSecurity(16, client); + client._sock._websocket._getSentData(); // skip the security reply + }); + + function sendNumStrPairs(pairs, client) { + const data = []; + push32(data, pairs.length); + + for (let i = 0; i < pairs.length; i++) { + push32(data, pairs[i][0]); + for (let j = 0; j < 4; j++) { + data.push(pairs[i][1].charCodeAt(j)); + } + for (let j = 0; j < 8; j++) { + data.push(pairs[i][2].charCodeAt(j)); + } + } + + client._sock._websocket._receiveData(new Uint8Array(data)); + } + + it('should skip tunnel negotiation if no tunnels are requested', function () { + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._rfbTightVNC).to.be.true; + }); + + it('should fail if no supported tunnels are listed', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + sendNumStrPairs([[123, 'OTHR', 'SOMETHNG']], client); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + + it('should choose the notunnel tunnel type', function () { + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL'], [123, 'OTHR', 'SOMETHNG']], client); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 0])); + }); + + it('should choose the notunnel tunnel type for Siemens devices', function () { + sendNumStrPairs([[1, 'SICR', 'SCHANNEL'], [2, 'SICR', 'SCHANLPW']], client); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 0])); + }); + + it('should continue to sub-auth negotiation after tunnel negotiation', function () { + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL']], client); + client._sock._websocket._getSentData(); // skip the tunnel choice here + sendNumStrPairs([[1, 'STDV', 'NOAUTH__']], client); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 1])); + expect(client._rfbInitState).to.equal('SecurityResult'); + }); + + it('should accept the "no auth" auth type and transition to SecurityResult', function () { + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL']], client); + client._sock._websocket._getSentData(); // skip the tunnel choice here + sendNumStrPairs([[1, 'STDV', 'NOAUTH__']], client); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 1])); + expect(client._rfbInitState).to.equal('SecurityResult'); + }); + + it('should accept VNC authentication and transition to that', function () { + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL']], client); + client._sock._websocket._getSentData(); // skip the tunnel choice here + sinon.spy(client, "_negotiateStdVNCAuth"); + sendNumStrPairs([[2, 'STDV', 'VNCAUTH__']], client); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 0, 2])); + expect(client._negotiateStdVNCAuth).to.have.been.calledOnce; + expect(client._rfbAuthScheme).to.equal(2); + }); + + it('should fail if there are no supported auth types', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + sendNumStrPairs([[0, 'TGHT', 'NOTUNNEL']], client); + client._sock._websocket._getSentData(); // skip the tunnel choice here + sendNumStrPairs([[23, 'stdv', 'badval__']], client); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + }); + + describe('VeNCrypt Authentication (type 19) Handler', function () { + beforeEach(function () { + sendSecurity(19, client); + expect(client._sock).to.have.sent(new Uint8Array([19])); + }); + + it('should fail with non-0.2 versions', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + client._sock._websocket._receiveData(new Uint8Array([0, 1])); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + + it('should fail if there are no supported subtypes', function () { + // VeNCrypt version + client._sock._websocket._receiveData(new Uint8Array([0, 2])); + expect(client._sock).to.have.sent(new Uint8Array([0, 2])); + // Server ACK. + client._sock._websocket._receiveData(new Uint8Array([0])); + // Subtype list + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + client._sock._websocket._receiveData(new Uint8Array([2, 0, 0, 0, 9, 0, 0, 1, 4])); + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + + it('should support standard types', function () { + // VeNCrypt version + client._sock._websocket._receiveData(new Uint8Array([0, 2])); + expect(client._sock).to.have.sent(new Uint8Array([0, 2])); + // Server ACK. + client._sock._websocket._receiveData(new Uint8Array([0])); + // Subtype list + client._sock._websocket._receiveData(new Uint8Array([2, 0, 0, 0, 2, 0, 0, 1, 4])); + + let expectedResponse = []; + push32(expectedResponse, 2); // Chosen subtype. + + expect(client._sock).to.have.sent(new Uint8Array(expectedResponse)); + }); + + it('should respect server preference order', function () { + // VeNCrypt version + client._sock._websocket._receiveData(new Uint8Array([0, 2])); + expect(client._sock).to.have.sent(new Uint8Array([0, 2])); + // Server ACK. + client._sock._websocket._receiveData(new Uint8Array([0])); + // Subtype list + let subtypes = [ 6 ]; + push32(subtypes, 79); + push32(subtypes, 30); + push32(subtypes, 188); + push32(subtypes, 256); + push32(subtypes, 6); + push32(subtypes, 1); + client._sock._websocket._receiveData(new Uint8Array(subtypes)); + + let expectedResponse = []; + push32(expectedResponse, 30); // Chosen subtype. + + expect(client._sock).to.have.sent(new Uint8Array(expectedResponse)); + }); + + it('should ignore redundant VeNCrypt subtype', function () { + // VeNCrypt version + client._sock._websocket._receiveData(new Uint8Array([0, 2])); + expect(client._sock).to.have.sent(new Uint8Array([0, 2])); + // Server ACK. + client._sock._websocket._receiveData(new Uint8Array([0])); + // Subtype list + client._sock._websocket._receiveData(new Uint8Array([2, 0, 0, 0, 19, 0, 0, 0, 2])); + + let expectedResponse = []; + push32(expectedResponse, 2); // Chosen subtype. + + expect(client._sock).to.have.sent(new Uint8Array(expectedResponse)); + }); + }); + + describe('Plain Authentication (type 256) Handler', function () { + beforeEach(function () { + sendSecurity(19, client); + expect(client._sock).to.have.sent(new Uint8Array([19])); + // VeNCrypt version + client._sock._websocket._receiveData(new Uint8Array([0, 2])); + expect(client._sock).to.have.sent(new Uint8Array([0, 2])); + // Server ACK. + client._sock._websocket._receiveData(new Uint8Array([0])); + }); + + it('should support Plain authentication', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'username', password: 'password' }); + }); + client._sock._websocket._receiveData(new Uint8Array([1, 0, 0, 1, 0])); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 1, 0])); + + clock.tick(); + + const expectedResponse = []; + push32(expectedResponse, 8); + push32(expectedResponse, 8); + pushString(expectedResponse, 'username'); + pushString(expectedResponse, 'password'); + expect(client._sock).to.have.sent(new Uint8Array(expectedResponse)); + }); + + it('should support Plain authentication with an empty password', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'username', password: '' }); + }); + client._sock._websocket._receiveData(new Uint8Array([1, 0, 0, 1, 0])); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 1, 0])); + + clock.tick(); + + const expectedResponse = []; + push32(expectedResponse, 8); + push32(expectedResponse, 0); + pushString(expectedResponse, 'username'); + pushString(expectedResponse, ''); + expect(client._sock).to.have.sent(new Uint8Array(expectedResponse)); + }); + + it('should support Plain authentication with a very long username and password', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ username: 'a'.repeat(300), password: 'b'.repeat(300) }); + }); + client._sock._websocket._receiveData(new Uint8Array([1, 0, 0, 1, 0])); + expect(client._sock).to.have.sent(new Uint8Array([0, 0, 1, 0])); + + clock.tick(); + + const expectedResponse = []; + push32(expectedResponse, 300); + push32(expectedResponse, 300); + pushString(expectedResponse, 'a'.repeat(300)); + pushString(expectedResponse, 'b'.repeat(300)); + expect(client._sock).to.have.sent(new Uint8Array(expectedResponse)); + }); + }); + }); + + describe('Legacy SecurityResult', function () { + it('should not include reason in securityfailure event for versions < 3.7', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ password: 'passwd' }); + }); + const spy = sinon.spy(); + client.addEventListener("securityfailure", spy); + sendVer('003.006\n', client); + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 2])); + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } + client._sock._websocket._receiveData(new Uint8Array(challenge)); + + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 2])); + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.status).to.equal(2); + expect('reason' in spy.args[0][0].detail).to.be.false; + }); + + it('should not include reason in securityfailure event for versions < 3.8', function () { + client.addEventListener("credentialsrequired", () => { + client.sendCredentials({ password: 'passwd' }); + }); + const spy = sinon.spy(); + client.addEventListener("securityfailure", spy); + sendVer('003.007\n', client); + sendSecurity(2, client); + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } + client._sock._websocket._receiveData(new Uint8Array(challenge)); + + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 2])); + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.status).to.equal(2); + expect('reason' in spy.args[0][0].detail).to.be.false; + }); + }); + + describe('SecurityResult', function () { + beforeEach(function () { + sendVer('003.008\n', client); + client._sock._websocket._getSentData(); + sendSecurity(1, client); + client._sock._websocket._getSentData(); + }); + + it('should fall through to ServerInitialisation on a response code of 0', function () { + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._rfbInitState).to.equal('ServerInitialisation'); + }); + + it('should include reason when provided in securityfailure event', function () { + const spy = sinon.spy(); + client.addEventListener("securityfailure", spy); + const failureData = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, + 32, 102, 97, 105, 108, 117, 114, 101]; + client._sock._websocket._receiveData(new Uint8Array(failureData)); + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.status).to.equal(1); + expect(spy.args[0][0].detail.reason).to.equal('such failure'); + }); + + it('should not include reason when length is zero in securityfailure event', function () { + const spy = sinon.spy(); + client.addEventListener("securityfailure", spy); + const failureData = [0, 0, 0, 1, 0, 0, 0, 0]; + client._sock._websocket._receiveData(new Uint8Array(failureData)); + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.status).to.equal(1); + expect('reason' in spy.args[0][0].detail).to.be.false; + }); + }); + + describe('ClientInitialisation', function () { + it('should transition to the ServerInitialisation state', function () { + const client = makeRFB(); + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'SecurityResult'; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._rfbInitState).to.equal('ServerInitialisation'); + }); + + it('should send 1 if we are in shared mode', function () { + const client = makeRFB('wss://host:8675', { shared: true }); + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'SecurityResult'; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._sock).to.have.sent(new Uint8Array([1])); + }); + + it('should send 0 if we are not in shared mode', function () { + const client = makeRFB('wss://host:8675', { shared: false }); + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'SecurityResult'; + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 0])); + expect(client._sock).to.have.sent(new Uint8Array([0])); + }); + }); + + describe('ServerInitialisation', function () { + beforeEach(function () { + client._rfbInitState = 'ServerInitialisation'; + }); + + function sendServerInit(opts, client) { + const fullOpts = { width: 10, height: 12, bpp: 24, depth: 24, bigEndian: 0, + trueColor: 1, redMax: 255, greenMax: 255, blueMax: 255, + redShift: 16, greenShift: 8, blueShift: 0, name: 'a name' }; + for (let opt in opts) { + fullOpts[opt] = opts[opt]; + } + const data = []; + + push16(data, fullOpts.width); + push16(data, fullOpts.height); + + data.push(fullOpts.bpp); + data.push(fullOpts.depth); + data.push(fullOpts.bigEndian); + data.push(fullOpts.trueColor); + + push16(data, fullOpts.redMax); + push16(data, fullOpts.greenMax); + push16(data, fullOpts.blueMax); + push8(data, fullOpts.redShift); + push8(data, fullOpts.greenShift); + push8(data, fullOpts.blueShift); + + // padding + push8(data, 0); + push8(data, 0); + push8(data, 0); + + client._sock._websocket._receiveData(new Uint8Array(data)); + + const nameData = []; + let nameLen = []; + pushString(nameData, fullOpts.name); + push32(nameLen, nameData.length); + + client._sock._websocket._receiveData(new Uint8Array(nameLen)); + client._sock._websocket._receiveData(new Uint8Array(nameData)); + } + + it('should set the framebuffer width and height', function () { + sendServerInit({ width: 32, height: 84 }, client); + expect(client._fbWidth).to.equal(32); + expect(client._fbHeight).to.equal(84); + }); + + // NB(sross): we just warn, not fail, for endian-ness and shifts, so we don't test them + + it('should set the framebuffer name and call the callback', function () { + const spy = sinon.spy(); + client.addEventListener("desktopname", spy); + sendServerInit({ name: 'som€ nam€' }, client); + + expect(client._fbName).to.equal('som€ nam€'); + expect(spy).to.have.been.calledOnce; + expect(spy.args[0][0].detail.name).to.equal('som€ nam€'); + }); + + it('should handle the extended init message of the tight encoding', function () { + // NB(sross): we don't actually do anything with it, so just test that we can + // read it w/o throwing an error + client._rfbTightVNC = true; + sendServerInit({}, client); + + const tightData = []; + push16(tightData, 1); + push16(tightData, 2); + push16(tightData, 3); + push16(tightData, 0); + for (let i = 0; i < 16 + 32 + 48; i++) { + tightData.push(i); + } + client._sock._websocket._receiveData(new Uint8Array(tightData)); + + expect(client._rfbConnectionState).to.equal('connected'); + }); + + it('should resize the display', function () { + sinon.spy(client._display, 'resize'); + sendServerInit({ width: 27, height: 32 }, client); + + expect(client._display.resize).to.have.been.calledOnce; + expect(client._display.resize).to.have.been.calledWith(27, 32); + }); + + it('should grab the keyboard', function () { + sinon.spy(client._keyboard, 'grab'); + sendServerInit({}, client); + expect(client._keyboard.grab).to.have.been.calledOnce; + }); + + describe('Initial Update Request', function () { + beforeEach(function () { + sinon.spy(RFB.messages, "pixelFormat"); + sinon.spy(RFB.messages, "clientEncodings"); + sinon.spy(RFB.messages, "fbUpdateRequest"); + }); + + afterEach(function () { + RFB.messages.pixelFormat.restore(); + RFB.messages.clientEncodings.restore(); + RFB.messages.fbUpdateRequest.restore(); + }); + + // TODO(directxman12): test the various options in this configuration matrix + it('should reply with the pixel format, client encodings, and initial update request', function () { + sendServerInit({ width: 27, height: 32 }, client); + + expect(RFB.messages.pixelFormat).to.have.been.calledOnce; + expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 24, true); + expect(RFB.messages.pixelFormat).to.have.been.calledBefore(RFB.messages.clientEncodings); + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.encodingTight); + RFB.messages.clientEncodings.getCall(0).args[1].forEach((enc) => { + expect(enc).to.be.a('number'); + expect(Number.isInteger(enc)).to.be.true; + }); + expect(RFB.messages.clientEncodings).to.have.been.calledBefore(RFB.messages.fbUpdateRequest); + expect(RFB.messages.fbUpdateRequest).to.have.been.calledOnce; + expect(RFB.messages.fbUpdateRequest).to.have.been.calledWith(client._sock, false, 0, 0, 27, 32); + }); + + it('should reply with restricted settings for Intel AMT servers', function () { + sendServerInit({ width: 27, height: 32, name: "Intel(r) AMT KVM"}, client); + + expect(RFB.messages.pixelFormat).to.have.been.calledOnce; + expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 8, true); + expect(RFB.messages.pixelFormat).to.have.been.calledBefore(RFB.messages.clientEncodings); + expect(RFB.messages.clientEncodings).to.have.been.calledOnce; + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.not.include(encodings.encodingTight); + expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.not.include(encodings.encodingHextile); + expect(RFB.messages.clientEncodings).to.have.been.calledBefore(RFB.messages.fbUpdateRequest); + expect(RFB.messages.fbUpdateRequest).to.have.been.calledOnce; + expect(RFB.messages.fbUpdateRequest).to.have.been.calledWith(client._sock, false, 0, 0, 27, 32); + }); + }); + + it('should send the "connect" event', function () { + let spy = sinon.spy(); + client.addEventListener('connect', spy); + sendServerInit({}, client); + expect(spy).to.have.been.calledOnce; + }); + }); + }); + + describe('Protocol Message Processing After Completing Initialization', function () { + let client; + + beforeEach(function () { + client = makeRFB(); + client._fbName = 'some device'; + client._fbWidth = 640; + client._fbHeight = 20; + }); + + describe('Framebuffer Update Handling', function () { + function sendFbuMsg(rectInfo, rectData, client, rectCnt) { + let data = []; + + if (!rectCnt || rectCnt > -1) { + // header + data.push(0); // msg type + data.push(0); // padding + push16(data, rectCnt || rectData.length); + } + + for (let i = 0; i < rectData.length; i++) { + if (rectInfo[i]) { + push16(data, rectInfo[i].x); + push16(data, rectInfo[i].y); + push16(data, rectInfo[i].width); + push16(data, rectInfo[i].height); + push32(data, rectInfo[i].encoding); + } + data = data.concat(rectData[i]); + } + + client._sock._websocket._receiveData(new Uint8Array(data)); + } + + it('should send an update request if there is sufficient data', function () { + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.fbUpdateRequest(esock, true, 0, 0, 640, 20); + let expected = ews._getSentData(); + + client._framebufferUpdate = () => true; + client._sock._websocket._receiveData(new Uint8Array([0])); + + expect(client._sock).to.have.sent(expected); + }); + + it('should not send an update request if we need more data', function () { + client._sock._websocket._receiveData(new Uint8Array([0])); + expect(client._sock).to.have.sent(new Uint8Array([])); + }); + + it('should resume receiving an update if we previously did not have enough data', function () { + let esock = new Websock(); + let ews = new FakeWebSocket(); + ews._open(); + esock.attach(ews); + RFB.messages.fbUpdateRequest(esock, true, 0, 0, 640, 20); + let expected = ews._getSentData(); + + // just enough to set FBU.rects + client._sock._websocket._receiveData(new Uint8Array([0, 0, 0, 3])); + expect(client._sock._websocket._getSentData()).to.have.length(0); + + client._framebufferUpdate = function () { this._sock.rQskipBytes(1); return true; }; // we magically have enough data + // 247 should *not* be used as the message type here + client._sock._websocket._receiveData(new Uint8Array([247])); + expect(client._sock).to.have.sent(expected); + }); + + it('should not send a request in continuous updates mode', function () { + client._enabledContinuousUpdates = true; + client._framebufferUpdate = () => true; + client._sock._websocket._receiveData(new Uint8Array([0])); + + expect(client._sock).to.have.sent(new Uint8Array([])); + }); + + it('should fail on an unsupported encoding', function () { + let callback = sinon.spy(); + client.addEventListener("disconnect", callback); + + const rectInfo = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; + sendFbuMsg([rectInfo], [[]], client); + + expect(callback).to.have.been.calledOnce; + expect(callback.args[0][0].detail.clean).to.be.false; + }); + + describe('Message Encoding Handlers', function () { + beforeEach(function () { + // a really small frame + client._fbWidth = 4; + client._fbHeight = 4; + client._fbDepth = 24; + client._display.resize(4, 4); + }); + + it('should handle the DesktopSize pseduo-encoding', function () { + sinon.spy(client._display, 'resize'); + sendFbuMsg([{ x: 0, y: 0, width: 20, height: 50, encoding: -223 }], [[]], client); + + expect(client._fbWidth).to.equal(20); + expect(client._fbHeight).to.equal(50); + + expect(client._display.resize).to.have.been.calledOnce; + expect(client._display.resize).to.have.been.calledWith(20, 50); + }); + + describe('the ExtendedDesktopSize pseudo-encoding handler', function () { + beforeEach(function () { + // a really small frame + client._fbWidth = 4; + client._fbHeight = 4; + client._display.resize(4, 4); + sinon.spy(client._display, 'resize'); + }); + + function makeScreenData(nrOfScreens) { + const data = []; + push8(data, nrOfScreens); // number-of-screens + push8(data, 0); // padding + push16(data, 0); // padding + for (let i=0; i= 3.8', function () { - client._rfb_version = 3.8; - sinon.spy(client, '_fail'); - var failure_data = [0, 0, 0, 1, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); - expect(client._fail).to.have.been.calledWith( - 'Security negotiation failed on security result (reason: whoops)'); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); - it('should fail on an error code of 1 with a standard message for version < 3.8', function () { - sinon.spy(client, '_fail'); - client._rfb_version = 3.7; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 1])); - expect(client._fail).to.have.been.calledWith( - 'Security handshake failed'); - }); + pointerEvent.resetHistory(); - it('should result in securityfailure event when receiving a non zero status', function () { - var spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.status).to.equal(2); - }); + gestureMove('twodrag', 20, 40, 0, 10); + clock.tick(50); - it('should include reason when provided in securityfailure event', function () { - client._rfb_version = 3.8; - var spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - var failure_data = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, - 32, 102, 97, 105, 108, 117, 114, 101]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); - expect(spy.args[0][0].detail.status).to.equal(1); - expect(spy.args[0][0].detail.reason).to.equal('such failure'); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); - it('should not include reason when length is zero in securityfailure event', function () { - client._rfb_version = 3.9; - var spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - var failure_data = [0, 0, 0, 1, 0, 0, 0, 0]; - client._sock._websocket._receive_data(new Uint8Array(failure_data)); - expect(spy.args[0][0].detail.status).to.equal(1); - expect('reason' in spy.args[0][0].detail).to.be.false; - }); + pointerEvent.resetHistory(); - it('should not include reason in securityfailure event for version < 3.8', function () { - client._rfb_version = 3.6; - var spy = sinon.spy(); - client.addEventListener("securityfailure", spy); - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); - expect(spy.args[0][0].detail.status).to.equal(2); - expect('reason' in spy.args[0][0].detail).to.be.false; - }); - }); + gestureMove('twodrag', 20, 40, 0, 20); + clock.tick(50); - describe('ClientInitialisation', function () { - it('should transition to the ServerInitialisation state', function () { - var client = make_rfb(); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._rfb_init_state).to.equal('ServerInitialisation'); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); - it('should send 1 if we are in shared mode', function () { - var client = make_rfb('wss://host:8675', { shared: true }); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._sock).to.have.sent(new Uint8Array([1])); - }); + pointerEvent.resetHistory(); - it('should send 0 if we are not in shared mode', function () { - var client = make_rfb('wss://host:8675', { shared: false }); - client._rfb_connection_state = 'connecting'; - client._rfb_init_state = 'SecurityResult'; - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); - expect(client._sock).to.have.sent(new Uint8Array([0])); - }); - }); + gestureMove('twodrag', 20, 40, 0, 60); - describe('ServerInitialisation', function () { - beforeEach(function () { - client._rfb_init_state = 'ServerInitialisation'; + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + }); + + it('should handle large gesture twodrag events', function () { + let bmask = 0x8; // Button mask for scroll up + + gestureStart('twodrag', 30, 50, 0, 0); + + expect(pointerEvent). + to.have.been.calledOnceWith(client._sock, 30, 50, 0x0); + + pointerEvent.resetHistory(); + + gestureMove('twodrag', 30, 50, 0, 200); + + expect(pointerEvent).to.have.callCount(7); + expect(pointerEvent.getCall(0)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + expect(pointerEvent.getCall(1)).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.getCall(2)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + expect(pointerEvent.getCall(3)).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.getCall(4)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + expect(pointerEvent.getCall(5)).to.have.been.calledWith(client._sock, + 30, 50, bmask); + expect(pointerEvent.getCall(6)).to.have.been.calledWith(client._sock, + 30, 50, 0x0); + }); }); - function send_server_init(opts, client) { - var full_opts = { width: 10, height: 12, bpp: 24, depth: 24, big_endian: 0, - true_color: 1, red_max: 255, green_max: 255, blue_max: 255, - red_shift: 16, green_shift: 8, blue_shift: 0, name: 'a name' }; - for (var opt in opts) { - full_opts[opt] = opts[opt]; - } - var data = []; + describe('Gesture pinch', function () { + it('should handle gesture pinch in events', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x10; // Button mask for scroll down - push16(data, full_opts.width); - push16(data, full_opts.height); + gestureStart('pinch', 20, 40, 90, 90); - data.push(full_opts.bpp); - data.push(full_opts.depth); - data.push(full_opts.big_endian); - data.push(full_opts.true_color); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(keyEvent).to.not.have.been.called; - push16(data, full_opts.red_max); - push16(data, full_opts.green_max); - push16(data, full_opts.blue_max); - push8(data, full_opts.red_shift); - push8(data, full_opts.green_shift); - push8(data, full_opts.blue_shift); + pointerEvent.resetHistory(); - // padding - push8(data, 0); - push8(data, 0); - push8(data, 0); + gestureMove('pinch', 20, 40, 30, 30); - client._sock._websocket._receive_data(new Uint8Array(data)); + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); - var name_data = []; - push32(name_data, full_opts.name.length); - for (var i = 0; i < full_opts.name.length; i++) { - name_data.push(full_opts.name.charCodeAt(i)); - } - client._sock._websocket._receive_data(new Uint8Array(name_data)); - } + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); - it('should set the framebuffer width and height', function () { - send_server_init({ width: 32, height: 84 }, client); - expect(client._fb_width).to.equal(32); - expect(client._fb_height).to.equal(84); - }); + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); - // NB(sross): we just warn, not fail, for endian-ness and shifts, so we don't test them + pointerEvent.resetHistory(); + keyEvent.resetHistory(); - it('should set the framebuffer name and call the callback', function () { - var spy = sinon.spy(); - client.addEventListener("desktopname", spy); - send_server_init({ name: 'some name' }, client); + gestureEnd('pinch', 20, 40); - expect(client._fb_name).to.equal('some name'); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.name).to.equal('some name'); - }); + expect(pointerEvent).to.not.have.been.called; + expect(keyEvent).to.not.have.been.called; + }); - it('should handle the extended init message of the tight encoding', function () { - // NB(sross): we don't actually do anything with it, so just test that we can - // read it w/o throwing an error - client._rfb_tightvnc = true; - send_server_init({}, client); - - var tight_data = []; - push16(tight_data, 1); - push16(tight_data, 2); - push16(tight_data, 3); - push16(tight_data, 0); - for (var i = 0; i < 16 + 32 + 48; i++) { - tight_data.push(i); - } - client._sock._websocket._receive_data(tight_data); + it('should handle gesture pinch out events', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x8; // Button mask for scroll up - expect(client._rfb_connection_state).to.equal('connected'); - }); + gestureStart('pinch', 10, 20, 10, 20); - it('should call the resize callback and resize the display', function () { - var spy = sinon.spy(); - client.addEventListener("fbresize", spy); - sinon.spy(client._display, 'resize'); - send_server_init({ width: 27, height: 32 }, client); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 10, 20, 0x0); + expect(keyEvent).to.not.have.been.called; - expect(client._display.resize).to.have.been.calledOnce; - expect(client._display.resize).to.have.been.calledWith(27, 32); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.width).to.equal(27); - expect(spy.args[0][0].detail.height).to.equal(32); - }); + pointerEvent.resetHistory(); - it('should grab the mouse and keyboard', function () { - sinon.spy(client._keyboard, 'grab'); - sinon.spy(client._mouse, 'grab'); - send_server_init({}, client); - expect(client._keyboard.grab).to.have.been.calledOnce; - expect(client._mouse.grab).to.have.been.calledOnce; - }); + gestureMove('pinch', 10, 20, 70, 80); - describe('Initial Update Request', function () { - beforeEach(function () { - sinon.spy(RFB.messages, "pixelFormat"); - sinon.spy(RFB.messages, "clientEncodings"); - sinon.spy(RFB.messages, "fbUpdateRequest"); - }); + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 10, 20, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 10, 20, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 10, 20, 0x0); - afterEach(function () { - RFB.messages.pixelFormat.restore(); - RFB.messages.clientEncodings.restore(); - RFB.messages.fbUpdateRequest.restore(); - }); + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); - // TODO(directxman12): test the various options in this configuration matrix - it('should reply with the pixel format, client encodings, and initial update request', function () { - send_server_init({ width: 27, height: 32 }, client); + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); - expect(RFB.messages.pixelFormat).to.have.been.calledOnce; - expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 24, true); - expect(RFB.messages.pixelFormat).to.have.been.calledBefore(RFB.messages.clientEncodings); - expect(RFB.messages.clientEncodings).to.have.been.calledOnce; - expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.include(encodings.encodingTight); - expect(RFB.messages.clientEncodings).to.have.been.calledBefore(RFB.messages.fbUpdateRequest); - expect(RFB.messages.fbUpdateRequest).to.have.been.calledOnce; - expect(RFB.messages.fbUpdateRequest).to.have.been.calledWith(client._sock, false, 0, 0, 27, 32); - }); + pointerEvent.resetHistory(); + keyEvent.resetHistory(); - it('should reply with restricted settings for Intel AMT servers', function () { - send_server_init({ width: 27, height: 32, name: "Intel(r) AMT KVM"}, client); + gestureEnd('pinch', 10, 20); - expect(RFB.messages.pixelFormat).to.have.been.calledOnce; - expect(RFB.messages.pixelFormat).to.have.been.calledWith(client._sock, 8, true); - expect(RFB.messages.pixelFormat).to.have.been.calledBefore(RFB.messages.clientEncodings); - expect(RFB.messages.clientEncodings).to.have.been.calledOnce; - expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.not.include(encodings.encodingTight); - expect(RFB.messages.clientEncodings.getCall(0).args[1]).to.not.include(encodings.encodingHextile); - expect(RFB.messages.clientEncodings).to.have.been.calledBefore(RFB.messages.fbUpdateRequest); - expect(RFB.messages.fbUpdateRequest).to.have.been.calledOnce; - expect(RFB.messages.fbUpdateRequest).to.have.been.calledWith(client._sock, false, 0, 0, 27, 32); + expect(pointerEvent).to.not.have.been.called; + expect(keyEvent).to.not.have.been.called; }); - }); - it('should transition to the "connected" state', function () { - send_server_init({}, client); - expect(client._rfb_connection_state).to.equal('connected'); - }); - }); - }); + it('should handle large gesture pinch', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x10; // Button mask for scroll down - describe('Protocol Message Processing After Completing Initialization', function () { - var client; + gestureStart('pinch', 20, 40, 150, 150); - beforeEach(function () { - client = make_rfb(); - client._fb_name = 'some device'; - client._fb_width = 640; - client._fb_height = 20; - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(keyEvent).to.not.have.been.called; - describe('Framebuffer Update Handling', function () { - var target_data_arr = [ - 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255, - 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255 - ]; - var target_data; + pointerEvent.resetHistory(); - var target_data_check_arr = [ - 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, - 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, - 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, - 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 - ]; - var target_data_check; + gestureMove('pinch', 20, 40, 30, 30); - before(function () { - // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray - target_data = new Uint8Array(target_data_arr); - target_data_check = new Uint8Array(target_data_check_arr); - }); + expect(pointerEvent).to.have.been.callCount(5); + expect(pointerEvent.getCall(0)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.getCall(1)).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.getCall(2)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.getCall(3)).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.getCall(4)).to.have.been.calledWith(client._sock, + 20, 40, 0x0); - function send_fbu_msg (rect_info, rect_data, client, rect_cnt) { - var data = []; + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); - if (!rect_cnt || rect_cnt > -1) { - // header - data.push(0); // msg type - data.push(0); // padding - push16(data, rect_cnt || rect_data.length); - } + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); - for (var i = 0; i < rect_data.length; i++) { - if (rect_info[i]) { - push16(data, rect_info[i].x); - push16(data, rect_info[i].y); - push16(data, rect_info[i].width); - push16(data, rect_info[i].height); - push32(data, rect_info[i].encoding); - } - data = data.concat(rect_data[i]); - } + pointerEvent.resetHistory(); + keyEvent.resetHistory(); - client._sock._websocket._receive_data(new Uint8Array(data)); - } + gestureEnd('pinch', 20, 40); - it('should send an update request if there is sufficient data', function () { - var expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: function() {}}; - RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); + expect(pointerEvent).to.not.have.been.called; + expect(keyEvent).to.not.have.been.called; + }); - client._framebufferUpdate = function () { return true; }; - client._sock._websocket._receive_data(new Uint8Array([0])); + it('should handle multiple small gesture pinch out events', function () { + let keysym = KeyTable.XK_Control_L; + let bmask = 0x8; // Button mask for scroll down - expect(client._sock).to.have.sent(expected_msg._sQ); - }); + gestureStart('pinch', 20, 40, 0, 10); - it('should not send an update request if we need more data', function () { - client._sock._websocket._receive_data(new Uint8Array([0])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(keyEvent).to.not.have.been.called; - it('should resume receiving an update if we previously did not have enough data', function () { - var expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: function() {}}; - RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); + pointerEvent.resetHistory(); - // just enough to set FBU.rects - client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 3])); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); + gestureMove('pinch', 20, 40, 0, 30); + clock.tick(50); - client._framebufferUpdate = function () { this._sock.rQskip8(); return true; }; // we magically have enough data - // 247 should *not* be used as the message type here - client._sock._websocket._receive_data(new Uint8Array([247])); - expect(client._sock).to.have.sent(expected_msg._sQ); - }); + expect(pointerEvent).to.have.been.calledWith(client._sock, + 20, 40, 0x0); - it('should not send a request in continuous updates mode', function () { - client._enabledContinuousUpdates = true; - client._framebufferUpdate = function () { return true; }; - client._sock._websocket._receive_data(new Uint8Array([0])); + pointerEvent.resetHistory(); - expect(client._sock._websocket._get_sent_data()).to.have.length(0); - }); + gestureMove('pinch', 20, 40, 0, 60); + clock.tick(50); - it('should fail on an unsupported encoding', function () { - sinon.spy(client, "_fail"); - var rect_info = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; - send_fbu_msg([rect_info], [[]], client); - expect(client._fail).to.have.been.calledOnce; - }); + expect(pointerEvent).to.have.been.calledWith(client._sock, + 20, 40, 0x0); - it('should be able to pause and resume receiving rects if not enought data', function () { - // seed some initial data to copy - client._fb_width = 4; - client._fb_height = 4; - client._display.resize(4, 4); - client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); + pointerEvent.resetHistory(); + keyEvent.resetHistory(); - var info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, - { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; - // data says [{ old_x: 2, old_y: 0 }, { old_x: 0, old_y: 0 }] - var rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; - send_fbu_msg([info[0]], [rects[0]], client, 2); - send_fbu_msg([info[1]], [rects[1]], client, -1); - expect(client._display).to.have.displayed(target_data_check); - }); + gestureMove('pinch', 20, 40, 0, 90); - describe('Message Encoding Handlers', function () { - beforeEach(function () { - // a really small frame - client._fb_width = 4; - client._fb_height = 4; - client._fb_depth = 24; - client._display.resize(4, 4); + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + + expect(keyEvent).to.have.been.calledTwice; + expect(keyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, 1); + expect(keyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, 0); + + expect(keyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(keyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); + + pointerEvent.resetHistory(); + keyEvent.resetHistory(); + + gestureEnd('pinch', 20, 40); + + expect(keyEvent).to.not.have.been.called; }); - it('should handle the RAW encoding', function () { - var info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 2, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 0, y: 2, width: 4, height: 1, encoding: 0x00 }, - { x: 0, y: 3, width: 4, height: 1, encoding: 0x00 }]; - // data is in bgrx - var rects = [ - [0x00, 0x00, 0xff, 0, 0x00, 0xff, 0x00, 0, 0x00, 0xff, 0x00, 0, 0x00, 0x00, 0xff, 0], - [0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0], - [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0], - [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0]]; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data); - }); - - it('should handle the RAW encoding in low colour mode', function () { - var info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 2, y: 0, width: 2, height: 2, encoding: 0x00 }, - { x: 0, y: 2, width: 4, height: 1, encoding: 0x00 }, - { x: 0, y: 3, width: 4, height: 1, encoding: 0x00 }]; - var rects = [ - [0x03, 0x03, 0x03, 0x03], - [0x0c, 0x0c, 0x0c, 0x0c], - [0x0c, 0x0c, 0x03, 0x03], - [0x0c, 0x0c, 0x03, 0x03]]; - client._fb_depth = 8; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data_check); - }); - - it('should handle the COPYRECT encoding', function () { - // seed some initial data to copy - client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); - - var info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, - { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; - // data says [{ old_x: 0, old_y: 0 }, { old_x: 0, old_y: 0 }] - var rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; - send_fbu_msg(info, rects, client); - expect(client._display).to.have.displayed(target_data_check); - }); - - // TODO(directxman12): for encodings with subrects, test resuming on partial send? - // TODO(directxman12): test rre_chunk_sz (related to above about subrects)? - - it('should handle the RRE encoding', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x02 }]; - var rect = []; - push32(rect, 2); // 2 subrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(0xff); // becomes ff0000ff --> #0000FF color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - push16(rect, 0); // x: 0 - push16(rect, 0); // y: 0 - push16(rect, 2); // width: 2 - push16(rect, 2); // height: 2 - rect.push(0xff); // becomes ff0000ff --> #0000FF color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - push16(rect, 2); // x: 2 - push16(rect, 2); // y: 2 - push16(rect, 2); // width: 2 - push16(rect, 2); // height: 2 - - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); - }); - - describe('the HEXTILE encoding handler', function () { - it('should handle a tile with fg, bg specified, normal subrects', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; - rect.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(2); // 2 subrects - rect.push(0); // x: 0, y: 0 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - rect.push(2 | (2 << 4)); // x: 2, y: 2 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); - }); + it('should send correct key control code', function () { + let keysym = KeyTable.XK_Control_L; + let code = 0x1d; + let bmask = 0x10; // Button mask for scroll down - it('should handle a raw tile', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; - rect.push(0x01); // raw - for (var i = 0; i < target_data.length; i += 4) { - rect.push(target_data[i + 2]); - rect.push(target_data[i + 1]); - rect.push(target_data[i]); - rect.push(target_data[i + 3]); - } - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data); - }); + client._qemuExtKeyEventSupported = true; - it('should handle a tile with only bg specified (solid bg)', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; - rect.push(0x02); - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - send_fbu_msg(info, [rect], client); + gestureStart('pinch', 20, 40, 90, 90); - var expected = []; - for (var i = 0; i < 16; i++) { push32(expected, 0xff00ff); } - expect(client._display).to.have.displayed(new Uint8Array(expected)); - }); + expect(pointerEvent).to.have.been.calledOnceWith(client._sock, + 20, 40, 0x0); + expect(qemuKeyEvent).to.not.have.been.called; - it('should handle a tile with only bg specified and an empty frame afterwards', function () { - // set the width so we can have two tiles - client._fb_width = 8; - client._display.resize(8, 4); + pointerEvent.resetHistory(); - var info = [{ x: 0, y: 0, width: 32, height: 4, encoding: 0x05 }]; + gestureMove('pinch', 20, 40, 30, 30); - var rect = []; + expect(pointerEvent).to.have.been.calledThrice; + expect(pointerEvent.firstCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); + expect(pointerEvent.secondCall).to.have.been.calledWith(client._sock, + 20, 40, bmask); + expect(pointerEvent.thirdCall).to.have.been.calledWith(client._sock, + 20, 40, 0x0); - // send a bg frame - rect.push(0x02); - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color + expect(qemuKeyEvent).to.have.been.calledTwice; + expect(qemuKeyEvent.firstCall).to.have.been.calledWith(client._sock, + keysym, + true, + code); + expect(qemuKeyEvent.secondCall).to.have.been.calledWith(client._sock, + keysym, + false, + code); - // send an empty frame - rect.push(0x00); + expect(qemuKeyEvent.firstCall).to.have.been.calledBefore(pointerEvent.secondCall); + expect(qemuKeyEvent.lastCall).to.have.been.calledAfter(pointerEvent.lastCall); - send_fbu_msg(info, [rect], client); + pointerEvent.resetHistory(); + qemuKeyEvent.resetHistory(); - var expected = []; - var i; - for (i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 1: solid - for (i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 2: same bkground color - expect(client._display).to.have.displayed(new Uint8Array(expected)); - }); + gestureEnd('pinch', 20, 40); - it('should handle a tile with bg and coloured subrects', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; - rect.push(0x02 | 0x08 | 0x10); // bg spec, anysubrects, colouredsubrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(2); // 2 subrects - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(0); // x: 0, y: 0 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(2 | (2 << 4)); // x: 2, y: 2 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - expect(client._display).to.have.displayed(target_data_check); - }); + expect(pointerEvent).to.not.have.been.called; + expect(qemuKeyEvent).to.not.have.been.called; + }); + }); + }); - it('should carry over fg and bg colors from the previous tile if not specified', function () { - client._fb_width = 4; - client._fb_height = 17; - client._display.resize(4, 17); - - var info = [{ x: 0, y: 0, width: 4, height: 17, encoding: 0x05}]; - var rect = []; - rect.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects - push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color - rect.push(0xff); // becomes ff0000ff --> #0000FF fg color - rect.push(0x00); - rect.push(0x00); - rect.push(0xff); - rect.push(8); // 8 subrects - var i; - for (i = 0; i < 4; i++) { - rect.push((0 << 4) | (i * 4)); // x: 0, y: i*4 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - rect.push((2 << 4) | (i * 4 + 2)); // x: 2, y: i * 4 + 2 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - } - rect.push(0x08); // anysubrects - rect.push(1); // 1 subrect - rect.push(0); // x: 0, y: 0 - rect.push(1 | (1 << 4)); // width: 2, height: 2 - send_fbu_msg(info, [rect], client); - - var expected = []; - for (i = 0; i < 4; i++) { expected = expected.concat(target_data_check_arr); } - expected = expected.concat(target_data_check_arr.slice(0, 16)); - expect(client._display).to.have.displayed(new Uint8Array(expected)); - }); + describe('WebSocket Events', function () { + // message events + it('should do nothing if we receive an empty message and have nothing in the queue', function () { + sinon.spy(client, "_normalMsg"); + client._sock._websocket._receiveData(new Uint8Array([])); + expect(client._normalMsg).to.not.have.been.called; + }); - it('should fail on an invalid subencoding', function () { - sinon.spy(client,"_fail"); - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rects = [[45]]; // an invalid subencoding - send_fbu_msg(info, rects, client); - expect(client._fail).to.have.been.calledOnce; - }); - }); + it('should handle a message in the connected state as a normal message', function () { + sinon.spy(client, "_normalMsg"); + client._sock._websocket._receiveData(new Uint8Array([1, 2, 3])); + expect(client._normalMsg).to.have.been.called; + }); - it.skip('should handle the TIGHT encoding', function () { - // TODO(directxman12): test this - }); + it('should handle a message in any non-disconnected/failed state like an init message', function () { + client._rfbConnectionState = 'connecting'; + client._rfbInitState = 'ProtocolVersion'; + sinon.spy(client, "_initMsg"); + client._sock._websocket._receiveData(new Uint8Array([1, 2, 3])); + expect(client._initMsg).to.have.been.called; + }); - it.skip('should handle the TIGHT_PNG encoding', function () { - // TODO(directxman12): test this - }); + it('should process all normal messages directly', function () { + const spy = sinon.spy(); + client.addEventListener("bell", spy); + client._sock._websocket._receiveData(new Uint8Array([0x02, 0x02])); + expect(spy).to.have.been.calledTwice; + }); - it('should handle the DesktopSize pseduo-encoding', function () { - var spy = sinon.spy(); - client.addEventListener("fbresize", spy); - sinon.spy(client._display, 'resize'); - send_fbu_msg([{ x: 0, y: 0, width: 20, height: 50, encoding: -223 }], [[]], client); + // open events + it('should update the state to ProtocolVersion on open (if the state is "connecting")', function () { + client = new RFB(document.createElement('div'), 'wss://host:8675'); + this.clock.tick(); + client._sock._websocket._open(); + expect(client._rfbInitState).to.equal('ProtocolVersion'); + }); - expect(spy).to.have.been.calledOnce; - expect(spy.args[0][0].detail.width).to.equal(20); - expect(spy.args[0][0].detail.height).to.equal(50); + it('should fail if we are not currently ready to connect and we get an "open" event', function () { + sinon.spy(client, "_fail"); + client._rfbConnectionState = 'connected'; + client._sock._websocket._open(); + expect(client._fail).to.have.been.calledOnce; + }); - expect(client._fb_width).to.equal(20); - expect(client._fb_height).to.equal(50); + // close events + it('should transition to "disconnected" from "disconnecting" on a close event', function () { + const real = client._sock._websocket.close; + client._sock._websocket.close = () => {}; + client.disconnect(); + expect(client._rfbConnectionState).to.equal('disconnecting'); + client._sock._websocket.close = real; + client._sock._websocket.close(); + expect(client._rfbConnectionState).to.equal('disconnected'); + }); - expect(client._display.resize).to.have.been.calledOnce; - expect(client._display.resize).to.have.been.calledWith(20, 50); - }); + it('should fail if we get a close event while connecting', function () { + sinon.spy(client, "_fail"); + client._rfbConnectionState = 'connecting'; + client._sock._websocket.close(); + expect(client._fail).to.have.been.calledOnce; + }); - describe('the ExtendedDesktopSize pseudo-encoding handler', function () { - var resizeSpy; + it('should unregister close event handler', function () { + sinon.spy(client._sock, 'off'); + client.disconnect(); + client._sock._websocket.close(); + expect(client._sock.off).to.have.been.calledWith('close'); + }); - beforeEach(function () { - client._supportsSetDesktopSize = false; - // a really small frame - client._fb_width = 4; - client._fb_height = 4; - client._display.resize(4, 4); - sinon.spy(client._display, 'resize'); - resizeSpy = sinon.spy(); - client.addEventListener("fbresize", resizeSpy); - }); + // error events do nothing + }); + }); - function make_screen_data (nr_of_screens) { - var data = []; - push8(data, nr_of_screens); // number-of-screens - push8(data, 0); // padding - push16(data, 0); // padding - for (var i=0; i { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +function push16(arr, num) { + arr.push((num >> 8) & 0xFF, + num & 0xFF); +} + +function push32(arr, num) { + arr.push((num >> 24) & 0xFF, + (num >> 16) & 0xFF, + (num >> 8) & 0xFF, + num & 0xFF); +} + +describe('RRE Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new RREDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + // TODO(directxman12): test rre_chunk_sz? + + it('should handle the RRE encoding', function () { + let data = []; + push32(data, 2); // 2 subrects + push32(data, 0x00ff0000); // becomes 00ff0000 --> #00FF00 bg color + data.push(0x00); // becomes 0000ff00 --> #0000FF fg color + data.push(0x00); + data.push(0xff); + data.push(0x00); + push16(data, 0); // x: 0 + push16(data, 0); // y: 0 + push16(data, 2); // width: 2 + push16(data, 2); // height: 2 + data.push(0x00); // becomes 0000ff00 --> #0000FF fg color + data.push(0x00); + data.push(0xff); + data.push(0x00); + push16(data, 2); // x: 2 + push16(data, 2); // y: 2 + push16(data, 2); // width: 2 + push16(data, 2); // height: 2 + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle empty rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, + [ 0x00, 0x00, 0x00, 0x00, + 0xff, 0xff, 0xff, 0xff ], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); +}); diff --git a/tests/test.tight.js b/tests/test.tight.js new file mode 100644 index 000000000..b3457a88b --- /dev/null +++ b/tests/test.tight.js @@ -0,0 +1,416 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import TightDecoder from '../core/decoders/tight.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +describe('Tight Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new TightDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle fill rects', function () { + let done = testDecodeRect(decoder, 0, 0, 4, 4, + [0x80, 0xff, 0x88, 0x44], + display, 24); + + let targetData = new Uint8Array([ + 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, + 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, + 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, + 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, 0xff, 0x88, 0x44, 255, + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle uncompressed copy rects', function () { + let done; + let blueData = [ 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff ]; + let greenData = [ 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00 ]; + + done = testDecodeRect(decoder, 0, 0, 2, 1, blueData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 1, 2, 1, blueData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 0, 2, 1, greenData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 1, 2, 1, greenData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 2, 2, 1, greenData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 3, 2, 1, greenData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 2, 2, 1, blueData, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 2, 3, 2, 1, blueData, display, 24); + expect(done).to.be.true; + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(display).to.have.displayed(targetData); + }); + + it('should handle compressed copy rects', function () { + let data = [ + // Control byte + 0x00, + // Pixels (compressed) + 0x15, + 0x78, 0x9c, 0x63, 0x60, 0xf8, 0xcf, 0x00, 0x44, + 0x60, 0x82, 0x01, 0x99, 0x8d, 0x29, 0x02, 0xa6, + 0x00, 0x7e, 0xbf, 0x0f, 0xf1 ]; + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle uncompressed mono rects', function () { + let data = [ + // Control bytes + 0x40, 0x01, + // Palette + 0x01, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, + // Pixels + 0x30, 0x30, 0xc0, 0xc0 ]; + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle compressed mono rects', function () { + display.resize(4, 12); + + let data = [ + // Control bytes + 0x40, 0x01, + // Palette + 0x01, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, + // Pixels (compressed) + 0x0e, + 0x78, 0x9c, 0x33, 0x30, 0x38, 0x70, 0xc0, 0x00, + 0x8a, 0x01, 0x21, 0x3c, 0x05, 0xa1 ]; + + let done = testDecodeRect(decoder, 0, 0, 4, 12, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle uncompressed palette rects', function () { + let done; + let data1 = [ + // Control bytes + 0x40, 0x01, + // Palette + 0x02, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, + // Pixels + 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01 ]; + let data2 = [ + // Control bytes + 0x40, 0x01, + // Palette + 0x02, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, + // Pixels + 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00 ]; + + done = testDecodeRect(decoder, 0, 0, 4, 2, data1, display, 24); + expect(done).to.be.true; + done = testDecodeRect(decoder, 0, 2, 4, 2, data2, display, 24); + expect(done).to.be.true; + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(display).to.have.displayed(targetData); + }); + + it('should handle compressed palette rects', function () { + let data = [ + // Control bytes + 0x40, 0x01, + // Palette + 0x02, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, + // Pixels (compressed) + 0x12, + 0x78, 0x9c, 0x63, 0x60, 0x60, 0x64, 0x64, 0x00, + 0x62, 0x08, 0xc9, 0xc0, 0x00, 0x00, 0x00, 0x54, + 0x00, 0x09 ]; + + let done = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it.skip('should handle uncompressed gradient rects', function () { + // Not implemented yet + }); + + it.skip('should handle compressed gradient rects', function () { + // Not implemented yet + }); + + it('should handle empty copy rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, [ 0x00 ], display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle empty palette rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, + [ 0x40, 0x01, 0x01, + 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff ], display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle empty fill rects', function () { + display.fillRect(0, 0, 4, 4, [ 0x00, 0x00, 0xff ]); + display.fillRect(2, 0, 2, 2, [ 0x00, 0xff, 0x00 ]); + display.fillRect(0, 2, 2, 2, [ 0x00, 0xff, 0x00 ]); + + let done = testDecodeRect(decoder, 1, 2, 0, 0, + [ 0x80, 0xff, 0xff, 0xff ], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle JPEG rects', async function () { + let data = [ + // Control bytes + 0x90, 0xd6, 0x05, + // JPEG data + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, + 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48, + 0x00, 0x48, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x13, + 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, + 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4d, + 0x50, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xff, 0xdb, + 0x00, 0x43, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0xff, 0xc2, 0x00, 0x11, 0x08, + 0x00, 0x04, 0x00, 0x04, 0x03, 0x01, 0x11, 0x00, + 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xc4, + 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x07, 0xff, 0xc4, 0x00, 0x14, + 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x08, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, + 0x00, 0x02, 0x10, 0x03, 0x10, 0x00, 0x00, 0x01, + 0x1e, 0x0a, 0xa7, 0x7f, 0xff, 0xc4, 0x00, 0x14, + 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x05, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, + 0x00, 0x01, 0x05, 0x02, 0x5d, 0x74, 0x41, 0x47, + 0xff, 0xc4, 0x00, 0x1f, 0x11, 0x00, 0x01, 0x04, + 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x04, 0x05, + 0x07, 0x08, 0x14, 0x16, 0x03, 0x15, 0x17, 0x25, + 0x26, 0xff, 0xda, 0x00, 0x08, 0x01, 0x03, 0x01, + 0x01, 0x3f, 0x01, 0xad, 0x35, 0xa6, 0x13, 0xb8, + 0x10, 0x98, 0x5d, 0x8a, 0xb1, 0x41, 0x7e, 0x43, + 0x99, 0x24, 0x3d, 0x8f, 0x70, 0x30, 0xd8, 0xcb, + 0x44, 0xbb, 0x7d, 0x48, 0xb5, 0xf8, 0x18, 0x7f, + 0xe7, 0xc1, 0x9f, 0x86, 0x45, 0x9b, 0xfa, 0xf1, + 0x61, 0x96, 0x46, 0xbf, 0x56, 0xc8, 0x8b, 0x2b, + 0x0b, 0x35, 0x6e, 0x4b, 0x8a, 0x95, 0x6a, 0xf9, + 0xff, 0x00, 0xff, 0xc4, 0x00, 0x1f, 0x11, 0x00, + 0x01, 0x04, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, + 0x02, 0x04, 0x05, 0x12, 0x13, 0x14, 0x01, 0x06, + 0x11, 0x22, 0x23, 0xff, 0xda, 0x00, 0x08, 0x01, + 0x02, 0x01, 0x01, 0x3f, 0x01, 0x85, 0x85, 0x8c, + 0xec, 0x31, 0x8d, 0xa6, 0x26, 0x1b, 0x6e, 0x48, + 0xbc, 0xcd, 0xb0, 0xe3, 0x33, 0x86, 0xf9, 0x35, + 0xdc, 0x15, 0xa8, 0xbe, 0x4d, 0x4a, 0x10, 0x22, + 0x80, 0x00, 0x91, 0xe8, 0x24, 0xda, 0xb6, 0x57, + 0x95, 0xf2, 0xa5, 0x73, 0xff, 0xc4, 0x00, 0x1e, + 0x10, 0x00, 0x01, 0x04, 0x03, 0x00, 0x03, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x03, 0x01, 0x02, 0x04, 0x12, 0x05, 0x11, + 0x13, 0x14, 0x22, 0x23, 0xff, 0xda, 0x00, 0x08, + 0x01, 0x01, 0x00, 0x06, 0x3f, 0x02, 0x91, 0x89, + 0xc4, 0xc8, 0xf1, 0x60, 0x45, 0xe5, 0xc0, 0x1c, + 0x80, 0x7a, 0x77, 0x00, 0xe4, 0x97, 0xeb, 0x24, + 0x66, 0x33, 0xac, 0x63, 0x11, 0xfe, 0xe4, 0x76, + 0xad, 0x56, 0xe9, 0xa8, 0x88, 0x9f, 0xff, 0xc4, + 0x00, 0x14, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xff, 0xda, 0x00, 0x08, + 0x01, 0x01, 0x00, 0x01, 0x3f, 0x21, 0x68, 0x3f, + 0x92, 0x17, 0x81, 0x1f, 0x7f, 0xff, 0xda, 0x00, + 0x0c, 0x03, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, + 0x00, 0x00, 0x10, 0x5f, 0xff, 0xc4, 0x00, 0x14, + 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xda, 0x00, 0x08, 0x01, 0x03, + 0x01, 0x01, 0x3f, 0x10, 0x03, 0xeb, 0x11, 0xe4, + 0xa7, 0xe3, 0xff, 0x00, 0xff, 0xc4, 0x00, 0x14, + 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xda, 0x00, 0x08, 0x01, 0x02, + 0x01, 0x01, 0x3f, 0x10, 0x6b, 0xd3, 0x02, 0xdc, + 0x9a, 0xf4, 0xff, 0x00, 0xff, 0xc4, 0x00, 0x14, + 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, + 0x00, 0x01, 0x3f, 0x10, 0x62, 0x7b, 0x3a, 0xd0, + 0x3f, 0xeb, 0xff, 0x00, 0xff, 0xd9, + ]; + + let decodeDone = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + expect(decodeDone).to.be.true; + + let targetData = new Uint8Array([ + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255 + ]); + + // Browsers have rounding errors, so we need an approximate + // comparing function + function almost(a, b) { + let diff = Math.abs(a - b); + return diff < 5; + } + + await display.flush(); + expect(display).to.have.displayed(targetData, almost); + }); +}); diff --git a/tests/test.tightpng.js b/tests/test.tightpng.js new file mode 100644 index 000000000..02c66d93b --- /dev/null +++ b/tests/test.tightpng.js @@ -0,0 +1,145 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import TightPngDecoder from '../core/decoders/tightpng.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +describe('TightPng Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new TightPngDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle the TightPng encoding', async function () { + let data = [ + // Control bytes + 0xa0, 0xb4, 0x04, + // PNG data + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, + 0x08, 0x02, 0x00, 0x00, 0x00, 0x26, 0x93, 0x09, + 0x29, 0x00, 0x00, 0x01, 0x84, 0x69, 0x43, 0x43, + 0x50, 0x49, 0x43, 0x43, 0x20, 0x70, 0x72, 0x6f, + 0x66, 0x69, 0x6c, 0x65, 0x00, 0x00, 0x28, 0x91, + 0x7d, 0x91, 0x3d, 0x48, 0xc3, 0x40, 0x18, 0x86, + 0xdf, 0xa6, 0x6a, 0x45, 0x2a, 0x0e, 0x76, 0x10, + 0x71, 0x08, 0x52, 0x9d, 0x2c, 0x88, 0x8a, 0x38, + 0x6a, 0x15, 0x8a, 0x50, 0x21, 0xd4, 0x0a, 0xad, + 0x3a, 0x98, 0x5c, 0xfa, 0x07, 0x4d, 0x1a, 0x92, + 0x14, 0x17, 0x47, 0xc1, 0xb5, 0xe0, 0xe0, 0xcf, + 0x62, 0xd5, 0xc1, 0xc5, 0x59, 0x57, 0x07, 0x57, + 0x41, 0x10, 0xfc, 0x01, 0x71, 0x72, 0x74, 0x52, + 0x74, 0x91, 0x12, 0xbf, 0x4b, 0x0a, 0x2d, 0x62, + 0xbc, 0xe3, 0xb8, 0x87, 0xf7, 0xbe, 0xf7, 0xe5, + 0xee, 0x3b, 0x40, 0xa8, 0x97, 0x99, 0x66, 0x75, + 0x8c, 0x03, 0x9a, 0x6e, 0x9b, 0xa9, 0x44, 0x5c, + 0xcc, 0x64, 0x57, 0xc5, 0xd0, 0x2b, 0xba, 0x68, + 0x86, 0x31, 0x8c, 0x2e, 0x99, 0x59, 0xc6, 0x9c, + 0x24, 0x25, 0xe1, 0x3b, 0xbe, 0xee, 0x11, 0xe0, + 0xfb, 0x5d, 0x8c, 0x67, 0xf9, 0xd7, 0xfd, 0x39, + 0x7a, 0xd5, 0x9c, 0xc5, 0x80, 0x80, 0x48, 0x3c, + 0xcb, 0x0c, 0xd3, 0x26, 0xde, 0x20, 0x9e, 0xde, + 0xb4, 0x0d, 0xce, 0xfb, 0xc4, 0x11, 0x56, 0x94, + 0x55, 0xe2, 0x73, 0xe2, 0x31, 0x93, 0x2e, 0x48, + 0xfc, 0xc8, 0x75, 0xc5, 0xe3, 0x37, 0xce, 0x05, + 0x97, 0x05, 0x9e, 0x19, 0x31, 0xd3, 0xa9, 0x79, + 0xe2, 0x08, 0xb1, 0x58, 0x68, 0x63, 0xa5, 0x8d, + 0x59, 0xd1, 0xd4, 0x88, 0xa7, 0x88, 0xa3, 0xaa, + 0xa6, 0x53, 0xbe, 0x90, 0xf1, 0x58, 0xe5, 0xbc, + 0xc5, 0x59, 0x2b, 0x57, 0x59, 0xf3, 0x9e, 0xfc, + 0x85, 0xe1, 0x9c, 0xbe, 0xb2, 0xcc, 0x75, 0x5a, + 0x43, 0x48, 0x60, 0x11, 0x4b, 0x90, 0x20, 0x42, + 0x41, 0x15, 0x25, 0x94, 0x61, 0x23, 0x46, 0xbb, + 0x4e, 0x8a, 0x85, 0x14, 0x9d, 0xc7, 0x7d, 0xfc, + 0x83, 0xae, 0x5f, 0x22, 0x97, 0x42, 0xae, 0x12, + 0x18, 0x39, 0x16, 0x50, 0x81, 0x06, 0xd9, 0xf5, + 0x83, 0xff, 0xc1, 0xef, 0xde, 0x5a, 0xf9, 0xc9, + 0x09, 0x2f, 0x29, 0x1c, 0x07, 0x3a, 0x5f, 0x1c, + 0xe7, 0x63, 0x04, 0x08, 0xed, 0x02, 0x8d, 0x9a, + 0xe3, 0x7c, 0x1f, 0x3b, 0x4e, 0xe3, 0x04, 0x08, + 0x3e, 0x03, 0x57, 0x7a, 0xcb, 0x5f, 0xa9, 0x03, + 0x33, 0x9f, 0xa4, 0xd7, 0x5a, 0x5a, 0xf4, 0x08, + 0xe8, 0xdb, 0x06, 0x2e, 0xae, 0x5b, 0x9a, 0xb2, + 0x07, 0x5c, 0xee, 0x00, 0x03, 0x4f, 0x86, 0x6c, + 0xca, 0xae, 0x14, 0xa4, 0x25, 0xe4, 0xf3, 0xc0, + 0xfb, 0x19, 0x7d, 0x53, 0x16, 0xe8, 0xbf, 0x05, + 0x7a, 0xd6, 0xbc, 0xbe, 0x35, 0xcf, 0x71, 0xfa, + 0x00, 0xa4, 0xa9, 0x57, 0xc9, 0x1b, 0xe0, 0xe0, + 0x10, 0x18, 0x2d, 0x50, 0xf6, 0xba, 0xcf, 0xbb, + 0xbb, 0xdb, 0xfb, 0xf6, 0x6f, 0x4d, 0xb3, 0x7f, + 0x3f, 0x0a, 0x27, 0x72, 0x7d, 0x49, 0x29, 0x8b, + 0xbb, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, + 0x73, 0x00, 0x00, 0x2e, 0x23, 0x00, 0x00, 0x2e, + 0x23, 0x01, 0x78, 0xa5, 0x3f, 0x76, 0x00, 0x00, + 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xe4, + 0x06, 0x06, 0x0c, 0x23, 0x1d, 0x3f, 0x9f, 0xbb, + 0x94, 0x00, 0x00, 0x00, 0x19, 0x74, 0x45, 0x58, + 0x74, 0x43, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, + 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, + 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, + 0x4d, 0x50, 0x57, 0x81, 0x0e, 0x17, 0x00, 0x00, + 0x00, 0x1e, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, + 0x65, 0xc9, 0xb1, 0x0d, 0x00, 0x00, 0x08, 0x03, + 0x20, 0xea, 0xff, 0x3f, 0xd7, 0xd5, 0x44, 0x56, + 0x52, 0x90, 0xc2, 0x38, 0xa2, 0xd0, 0xbc, 0x59, + 0x8a, 0x9f, 0x04, 0x05, 0x6b, 0x38, 0x7b, 0xb2, + 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, + 0xae, 0x42, 0x60, 0x82, + ]; + + let decodeDone = testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24); + expect(decodeDone).to.be.true; + + let targetData = new Uint8Array([ + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255, + 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0xff, 0x00, 0x00, 255 + ]); + + // Firefox currently has some very odd rounding bug: + // https://bugzilla.mozilla.org/show_bug.cgi?id=1667747 + function almost(a, b) { + let diff = Math.abs(a - b); + return diff < 30; + } + + await display.flush(); + expect(display).to.have.displayed(targetData, almost); + }); +}); diff --git a/tests/test.util.js b/tests/test.util.js index 1eab1e99b..cd61f248a 100644 --- a/tests/test.util.js +++ b/tests/test.util.js @@ -1,13 +1,10 @@ -/* jshint expr: true */ - -var assert = chai.assert; -var expect = chai.expect; +/* eslint-disable no-console */ +const expect = chai.expect; import * as Log from '../core/util/logging.js'; +import { encodeUTF8, decodeUTF8 } from '../core/util/strings.js'; -import sinon from '../vendor/sinon.js'; - -describe('Utils', function() { +describe('Utils', function () { "use strict"; describe('logging functions', function () { @@ -25,48 +22,68 @@ describe('Utils', function() { console.warn.restore(); console.error.restore(); console.info.restore(); - Log.init_logging(); + Log.initLogging(); }); it('should use noop for levels lower than the min level', function () { - Log.init_logging('warn'); + Log.initLogging('warn'); Log.Debug('hi'); Log.Info('hello'); expect(console.log).to.not.have.been.called; }); it('should use console.debug for Debug', function () { - Log.init_logging('debug'); + Log.initLogging('debug'); Log.Debug('dbg'); expect(console.debug).to.have.been.calledWith('dbg'); }); it('should use console.info for Info', function () { - Log.init_logging('debug'); + Log.initLogging('debug'); Log.Info('inf'); expect(console.info).to.have.been.calledWith('inf'); }); it('should use console.warn for Warn', function () { - Log.init_logging('warn'); + Log.initLogging('warn'); Log.Warn('wrn'); expect(console.warn).to.have.been.called; expect(console.warn).to.have.been.calledWith('wrn'); }); it('should use console.error for Error', function () { - Log.init_logging('error'); + Log.initLogging('error'); Log.Error('err'); expect(console.error).to.have.been.called; expect(console.error).to.have.been.calledWith('err'); }); }); + describe('string functions', function () { + it('should decode UTF-8 to DOMString correctly', function () { + const utf8string = '\xd0\x9f'; + const domstring = decodeUTF8(utf8string); + expect(domstring).to.equal("П"); + }); + + it('should encode DOMString to UTF-8 correctly', function () { + const domstring = "åäöa"; + const utf8string = encodeUTF8(domstring); + expect(utf8string).to.equal('\xc3\xa5\xc3\xa4\xc3\xb6\x61'); + }); + + it('should allow Latin-1 strings if allowLatin1 is set when decoding', function () { + const latin1string = '\xe5\xe4\xf6'; + expect(() => decodeUTF8(latin1string)).to.throw(Error); + expect(decodeUTF8(latin1string, true)).to.equal('åäö'); + }); + }); + // TODO(directxman12): test the conf_default and conf_defaults methods - // TODO(directxman12): test decodeUTF8 // TODO(directxman12): test the event methods (addEvent, removeEvent, stopEvent) // TODO(directxman12): figure out a good way to test getPosition and getEventPosition // TODO(directxman12): figure out how to test the browser detection functions properly // (we can't really test them against the browsers, except for Gecko // via PhantomJS, the default test driver) }); +/* eslint-enable no-console */ diff --git a/tests/test.websock.js b/tests/test.websock.js index 211ab6017..dc361b749 100644 --- a/tests/test.websock.js +++ b/tests/test.websock.js @@ -1,249 +1,372 @@ -/* jshint expr: true */ -var assert = chai.assert; -var expect = chai.expect; +const expect = chai.expect; import Websock from '../core/websock.js'; import FakeWebSocket from './fake.websocket.js'; -import sinon from '../vendor/sinon.js'; - -describe('Websock', function() { +describe('Websock', function () { "use strict"; - describe('Queue methods', function () { - var sock; - var RQ_TEMPLATE = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); + describe('Receive queue methods', function () { + let sock, websock; beforeEach(function () { sock = new Websock(); - // skip init - sock._allocate_buffers(); - sock._rQ.set(RQ_TEMPLATE); - sock._rQlen = RQ_TEMPLATE.length; - }); - describe('rQlen', function () { - it('should return the length of the receive queue', function () { - sock.set_rQi(0); - - expect(sock.rQlen()).to.equal(RQ_TEMPLATE.length); - }); - - it("should return the proper length if we read some from the receive queue", function () { - sock.set_rQi(1); - - expect(sock.rQlen()).to.equal(RQ_TEMPLATE.length - 1); - }); + websock = new FakeWebSocket(); + websock._open(); + sock.attach(websock); }); describe('rQpeek8', function () { it('should peek at the next byte without poping it off the queue', function () { - var bef_len = sock.rQlen(); - var peek = sock.rQpeek8(); - expect(sock.rQpeek8()).to.equal(peek); - expect(sock.rQlen()).to.equal(bef_len); + websock._receiveData(new Uint8Array([0xab, 0xcd])); + expect(sock.rQpeek8()).to.equal(0xab); + expect(sock.rQpeek8()).to.equal(0xab); }); }); - describe('rQshift8', function () { + describe('rQshift8()', function () { it('should pop a single byte from the receive queue', function () { - var peek = sock.rQpeek8(); - var bef_len = sock.rQlen(); - expect(sock.rQshift8()).to.equal(peek); - expect(sock.rQlen()).to.equal(bef_len - 1); + websock._receiveData(new Uint8Array([0xab, 0xcd])); + expect(sock.rQshift8()).to.equal(0xab); + expect(sock.rQshift8()).to.equal(0xcd); }); }); - describe('rQshift16', function () { + describe('rQshift16()', function () { it('should pop two bytes from the receive queue and return a single number', function () { - var bef_len = sock.rQlen(); - var expected = (RQ_TEMPLATE[0] << 8) + RQ_TEMPLATE[1]; - expect(sock.rQshift16()).to.equal(expected); - expect(sock.rQlen()).to.equal(bef_len - 2); + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34])); + expect(sock.rQshift16()).to.equal(0xabcd); + expect(sock.rQshift16()).to.equal(0x1234); }); }); - describe('rQshift32', function () { + describe('rQshift32()', function () { it('should pop four bytes from the receive queue and return a single number', function () { - var bef_len = sock.rQlen(); - var expected = (RQ_TEMPLATE[0] << 24) + - (RQ_TEMPLATE[1] << 16) + - (RQ_TEMPLATE[2] << 8) + - RQ_TEMPLATE[3]; - expect(sock.rQshift32()).to.equal(expected); - expect(sock.rQlen()).to.equal(bef_len - 4); + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + expect(sock.rQshift32()).to.equal(0xabcd1234); + expect(sock.rQshift32()).to.equal(0x88ee1133); }); }); describe('rQshiftStr', function () { it('should shift the given number of bytes off of the receive queue and return a string', function () { - var bef_len = sock.rQlen(); - var bef_rQi = sock.get_rQi(); - var shifted = sock.rQshiftStr(3); - expect(shifted).to.be.a('string'); - expect(shifted).to.equal(String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3)))); - expect(sock.rQlen()).to.equal(bef_len - 3); - }); + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + expect(sock.rQshiftStr(4)).to.equal('\xab\xcd\x12\x34'); + expect(sock.rQshiftStr(4)).to.equal('\x88\xee\x11\x33'); + }); + + it('should be able to handle very large strings', function () { + const BIG_LEN = 500000; + const incoming = new Uint8Array(BIG_LEN); + let expected = ""; + let letterCode = 'a'.charCodeAt(0); + for (let i = 0; i < BIG_LEN; i++) { + incoming[i] = letterCode; + expected += String.fromCharCode(letterCode); + + if (letterCode < 'z'.charCodeAt(0)) { + letterCode++; + } else { + letterCode = 'a'.charCodeAt(0); + } + } + websock._receiveData(incoming); - it('should shift the entire rest of the queue off if no length is given', function () { - sock.rQshiftStr(); - expect(sock.rQlen()).to.equal(0); + const shifted = sock.rQshiftStr(BIG_LEN); + + expect(shifted).to.be.equal(expected); }); }); describe('rQshiftBytes', function () { it('should shift the given number of bytes of the receive queue and return an array', function () { - var bef_len = sock.rQlen(); - var bef_rQi = sock.get_rQi(); - var shifted = sock.rQshiftBytes(3); - expect(shifted).to.be.an.instanceof(Uint8Array); - expect(shifted).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3)); - expect(sock.rQlen()).to.equal(bef_len - 3); + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + expect(sock.rQshiftBytes(4)).to.array.equal(new Uint8Array([0xab, 0xcd, 0x12, 0x34])); + expect(sock.rQshiftBytes(4)).to.array.equal(new Uint8Array([0x88, 0xee, 0x11, 0x33])); }); - it('should shift the entire rest of the queue off if no length is given', function () { - sock.rQshiftBytes(); - expect(sock.rQlen()).to.equal(0); + it('should return a shared array if requested', function () { + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + const bytes = sock.rQshiftBytes(4, false); + expect(bytes).to.array.equal(new Uint8Array([0xab, 0xcd, 0x12, 0x34])); + expect(bytes.buffer.byteLength).to.not.equal(bytes.length); }); }); - describe('rQslice', function () { - beforeEach(function () { - sock.set_rQi(0); - }); - + describe('rQpeekBytes', function () { it('should not modify the receive queue', function () { - var bef_len = sock.rQlen(); - sock.rQslice(0, 2); - expect(sock.rQlen()).to.equal(bef_len); - }); - - it('should return an array containing the given slice of the receive queue', function () { - var sl = sock.rQslice(0, 2); - expect(sl).to.be.an.instanceof(Uint8Array); - expect(sl).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 0, 2)); - }); - - it('should use the rest of the receive queue if no end is given', function () { - var sl = sock.rQslice(1); - expect(sl).to.have.length(RQ_TEMPLATE.length - 1); - expect(sl).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 1)); + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + expect(sock.rQpeekBytes(4)).to.array.equal(new Uint8Array([0xab, 0xcd, 0x12, 0x34])); + expect(sock.rQpeekBytes(4)).to.array.equal(new Uint8Array([0xab, 0xcd, 0x12, 0x34])); }); - it('should take the current rQi in to account', function () { - sock.set_rQi(1); - expect(sock.rQslice(0, 2)).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 1, 2)); + it('should return a shared array if requested', function () { + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); + const bytes = sock.rQpeekBytes(4, false); + expect(bytes).to.array.equal(new Uint8Array([0xab, 0xcd, 0x12, 0x34])); + expect(bytes.buffer.byteLength).to.not.equal(bytes.length); }); }); describe('rQwait', function () { beforeEach(function () { - sock.set_rQi(0); + websock._receiveData(new Uint8Array([0xab, 0xcd, 0x12, 0x34, + 0x88, 0xee, 0x11, 0x33])); }); it('should return true if there are not enough bytes in the receive queue', function () { - expect(sock.rQwait('hi', RQ_TEMPLATE.length + 1)).to.be.true; + expect(sock.rQwait('hi', 9)).to.be.true; }); it('should return false if there are enough bytes in the receive queue', function () { - expect(sock.rQwait('hi', RQ_TEMPLATE.length)).to.be.false; + expect(sock.rQwait('hi', 8)).to.be.false; }); it('should return true and reduce rQi by "goback" if there are not enough bytes', function () { - sock.set_rQi(5); - expect(sock.rQwait('hi', RQ_TEMPLATE.length, 4)).to.be.true; - expect(sock.get_rQi()).to.equal(1); + expect(sock.rQshift32()).to.equal(0xabcd1234); + expect(sock.rQwait('hi', 8, 2)).to.be.true; + expect(sock.rQshift32()).to.equal(0x123488ee); }); it('should raise an error if we try to go back more than possible', function () { - sock.set_rQi(5); - expect(function () { sock.rQwait('hi', RQ_TEMPLATE.length, 6); }).to.throw(Error); + expect(sock.rQshift32()).to.equal(0xabcd1234); + expect(() => sock.rQwait('hi', 8, 6)).to.throw(Error); }); it('should not reduce rQi if there are enough bytes', function () { - sock.set_rQi(5); - sock.rQwait('hi', 1, 6); - expect(sock.get_rQi()).to.equal(5); + expect(sock.rQshift32()).to.equal(0xabcd1234); + expect(sock.rQwait('hi', 4, 2)).to.be.false; + expect(sock.rQshift32()).to.equal(0x88ee1133); }); }); + }); - describe('flush', function () { - beforeEach(function () { - sock._websocket = { - send: sinon.spy() - }; + describe('Send queue methods', function () { + let sock; + + const bufferSize = 10 * 1024; + + beforeEach(function () { + let websock = new FakeWebSocket(); + websock._open(); + sock = new Websock(); + sock.attach(websock); + }); + + describe('sQpush8()', function () { + it('should send a single byte', function () { + sock.sQpush8(42); + sock.flush(); + expect(sock).to.have.sent(new Uint8Array([42])); + }); + it('should not send any data until flushing', function () { + sock.sQpush8(42); + expect(sock).to.have.sent(new Uint8Array([])); }); + it('should implicitly flush if the queue is full', function () { + for (let i = 0;i <= bufferSize;i++) { + sock.sQpush8(42); + } - it('should actually send on the websocket', function () { - sock._websocket.bufferedAmount = 8; - sock._websocket.readyState = WebSocket.OPEN - sock._sQ = new Uint8Array([1, 2, 3]); - sock._sQlen = 3; - var encoded = sock._encode_message(); + let expected = []; + for (let i = 0;i < bufferSize;i++) { + expected.push(42); + } + expect(sock).to.have.sent(new Uint8Array(expected)); + }); + }); + + describe('sQpush16()', function () { + it('should send a number as two bytes', function () { + sock.sQpush16(420); sock.flush(); - expect(sock._websocket.send).to.have.been.calledOnce; - expect(sock._websocket.send).to.have.been.calledWith(encoded); + expect(sock).to.have.sent(new Uint8Array([1, 164])); + }); + it('should not send any data until flushing', function () { + sock.sQpush16(420); + expect(sock).to.have.sent(new Uint8Array([])); }); + it('should implicitly flush if the queue is full', function () { + for (let i = 0;i <= bufferSize/2;i++) { + sock.sQpush16(420); + } - it('should not call send if we do not have anything queued up', function () { - sock._sQlen = 0; - sock._websocket.bufferedAmount = 8; + let expected = []; + for (let i = 0;i < bufferSize/2;i++) { + expected.push(1); + expected.push(164); + } + expect(sock).to.have.sent(new Uint8Array(expected)); + }); + }); + + describe('sQpush32()', function () { + it('should send a number as two bytes', function () { + sock.sQpush32(420420); sock.flush(); + expect(sock).to.have.sent(new Uint8Array([0, 6, 106, 68])); + }); + it('should not send any data until flushing', function () { + sock.sQpush32(420420); + expect(sock).to.have.sent(new Uint8Array([])); + }); + it('should implicitly flush if the queue is full', function () { + for (let i = 0;i <= bufferSize/4;i++) { + sock.sQpush32(420420); + } - expect(sock._websocket.send).not.to.have.been.called; + let expected = []; + for (let i = 0;i < bufferSize/4;i++) { + expected.push(0); + expected.push(6); + expected.push(106); + expected.push(68); + } + + expect(sock).to.have.sent(new Uint8Array(expected)); }); }); - describe('send', function () { - beforeEach(function () { - sock.flush = sinon.spy(); + describe('sQpushString()', function () { + it('should send a string buffer', function () { + sock.sQpushString('\x12\x34\x56\x78\x90'); + sock.flush(); + expect(sock).to.have.sent(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90])); }); + it('should not send any data until flushing', function () { + sock.sQpushString('\x12\x34\x56\x78\x90'); + expect(sock).to.have.sent(new Uint8Array([])); + }); + it('should implicitly flush if the queue is full', function () { + for (let i = 0;i <= bufferSize/5;i++) { + sock.sQpushString('\x12\x34\x56\x78\x90'); + } + + let expected = []; + for (let i = 0;i < bufferSize/5;i++) { + expected.push(0x12); + expected.push(0x34); + expected.push(0x56); + expected.push(0x78); + expected.push(0x90); + } - it('should add to the send queue', function () { - sock.send([1, 2, 3]); - var sq = sock.get_sQ(); - expect(new Uint8Array(sq.buffer, sock._sQlen - 3, 3)).to.array.equal(new Uint8Array([1, 2, 3])); + expect(sock).to.have.sent(new Uint8Array(expected)); }); + it('should implicitly split a large buffer', function () { + let str = ''; + for (let i = 0;i <= bufferSize/5;i++) { + str += '\x12\x34\x56\x78\x90'; + } + + sock.sQpushString(str); + + let expected = []; + for (let i = 0;i < bufferSize/5;i++) { + expected.push(0x12); + expected.push(0x34); + expected.push(0x56); + expected.push(0x78); + expected.push(0x90); + } - it('should call flush', function () { - sock.send([1, 2, 3]); - expect(sock.flush).to.have.been.calledOnce; + expect(sock).to.have.sent(new Uint8Array(expected)); }); }); - describe('send_string', function () { - beforeEach(function () { - sock.send = sinon.spy(); + describe('sQpushBytes()', function () { + it('should send a byte buffer', function () { + sock.sQpushBytes(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90])); + sock.flush(); + expect(sock).to.have.sent(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90])); + }); + it('should not send any data until flushing', function () { + sock.sQpushBytes(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90])); + expect(sock).to.have.sent(new Uint8Array([])); + }); + it('should implicitly flush if the queue is full', function () { + for (let i = 0;i <= bufferSize/5;i++) { + sock.sQpushBytes(new Uint8Array([0x12, 0x34, 0x56, 0x78, 0x90])); + } + + let expected = []; + for (let i = 0;i < bufferSize/5;i++) { + expected.push(0x12); + expected.push(0x34); + expected.push(0x56); + expected.push(0x78); + expected.push(0x90); + } + + expect(sock).to.have.sent(new Uint8Array(expected)); }); + it('should implicitly split a large buffer', function () { + let buffer = []; + for (let i = 0;i <= bufferSize/5;i++) { + buffer.push(0x12); + buffer.push(0x34); + buffer.push(0x56); + buffer.push(0x78); + buffer.push(0x90); + } + + sock.sQpushBytes(new Uint8Array(buffer)); + + let expected = []; + for (let i = 0;i < bufferSize/5;i++) { + expected.push(0x12); + expected.push(0x34); + expected.push(0x56); + expected.push(0x78); + expected.push(0x90); + } + + expect(sock).to.have.sent(new Uint8Array(expected)); + }); + }); + + describe('flush', function () { + it('should actually send on the websocket', function () { + sock._sQ = new Uint8Array([1, 2, 3]); + sock._sQlen = 3; + + sock.flush(); + expect(sock).to.have.sent(new Uint8Array([1, 2, 3])); + }); + + it('should not call send if we do not have anything queued up', function () { + sock._sQlen = 0; + + sock.flush(); - it('should call send after converting the string to an array', function () { - sock.send_string("\x01\x02\x03"); - expect(sock.send).to.have.been.calledWith([1, 2, 3]); + expect(sock).to.have.sent(new Uint8Array([])); }); }); }); describe('lifecycle methods', function () { - var old_WS; + let oldWS; before(function () { - old_WS = WebSocket; + oldWS = WebSocket; }); - var sock; + let sock; beforeEach(function () { - sock = new Websock(); - WebSocket = sinon.spy(); - WebSocket.OPEN = old_WS.OPEN; - WebSocket.CONNECTING = old_WS.CONNECTING; - WebSocket.CLOSING = old_WS.CLOSING; - WebSocket.CLOSED = old_WS.CLOSED; - - WebSocket.prototype.binaryType = 'arraybuffer'; + sock = new Websock(); + // eslint-disable-next-line no-global-assign + WebSocket = sinon.spy(FakeWebSocket); }); describe('opening', function () { - it('should pick the correct protocols if none are given' , function () { + it('should pick the correct protocols if none are given', function () { }); @@ -255,9 +378,17 @@ describe('Websock', function() { // it('should initialize the event handlers')? }); + describe('attaching', function () { + it('should attach to an existing websocket', function () { + let ws = new FakeWebSocket('ws://localhost:8675'); + sock.attach(ws); + expect(WebSocket).to.not.have.been.called; + }); + }); + describe('closing', function () { beforeEach(function () { - sock.open('ws://'); + sock.open('ws://localhost'); sock._websocket.close = sinon.spy(); }); @@ -285,30 +416,30 @@ describe('Websock', function() { expect(sock._websocket.close).not.to.have.been.called; }); - it('should reset onmessage to not call _recv_message', function () { - sinon.spy(sock, '_recv_message'); + it('should reset onmessage to not call _recvMessage', function () { + sinon.spy(sock, '_recvMessage'); sock.close(); sock._websocket.onmessage(null); try { - expect(sock._recv_message).not.to.have.been.called; + expect(sock._recvMessage).not.to.have.been.called; } finally { - sock._recv_message.restore(); + sock._recvMessage.restore(); } }); }); describe('event handlers', function () { beforeEach(function () { - sock._recv_message = sinon.spy(); + sock._recvMessage = sinon.spy(); sock.on('open', sinon.spy()); sock.on('close', sinon.spy()); sock.on('error', sinon.spy()); - sock.open('ws://'); + sock.open('ws://localhost'); }); - it('should call _recv_message on a message', function () { + it('should call _recvMessage on a message', function () { sock._websocket.onmessage(null); - expect(sock._recv_message).to.have.been.calledOnce; + expect(sock._recvMessage).to.have.been.calledOnce; }); it('should call the open event handler on opening', function () { @@ -327,93 +458,171 @@ describe('Websock', function() { }); }); + describe('ready state', function () { + it('should be "unused" after construction', function () { + let sock = new Websock(); + expect(sock.readyState).to.equal('unused'); + }); + + it('should be "connecting" if WebSocket is connecting', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = WebSocket.CONNECTING; + sock.attach(ws); + expect(sock.readyState).to.equal('connecting'); + }); + + it('should be "open" if WebSocket is open', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = WebSocket.OPEN; + sock.attach(ws); + expect(sock.readyState).to.equal('open'); + }); + + it('should be "closing" if WebSocket is closing', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = WebSocket.CLOSING; + sock.attach(ws); + expect(sock.readyState).to.equal('closing'); + }); + + it('should be "closed" if WebSocket is closed', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = WebSocket.CLOSED; + sock.attach(ws); + expect(sock.readyState).to.equal('closed'); + }); + + it('should be "unknown" if WebSocket state is unknown', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = 666; + sock.attach(ws); + expect(sock.readyState).to.equal('unknown'); + }); + + it('should be "connecting" if RTCDataChannel is connecting', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = 'connecting'; + sock.attach(ws); + expect(sock.readyState).to.equal('connecting'); + }); + + it('should be "open" if RTCDataChannel is open', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = 'open'; + sock.attach(ws); + expect(sock.readyState).to.equal('open'); + }); + + it('should be "closing" if RTCDataChannel is closing', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = 'closing'; + sock.attach(ws); + expect(sock.readyState).to.equal('closing'); + }); + + it('should be "closed" if RTCDataChannel is closed', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = 'closed'; + sock.attach(ws); + expect(sock.readyState).to.equal('closed'); + }); + + it('should be "unknown" if RTCDataChannel state is unknown', function () { + let sock = new Websock(); + let ws = new FakeWebSocket(); + ws.readyState = 'foobar'; + sock.attach(ws); + expect(sock.readyState).to.equal('unknown'); + }); + }); + after(function () { - WebSocket = old_WS; + // eslint-disable-next-line no-global-assign + WebSocket = oldWS; }); }); describe('WebSocket Receiving', function () { - var sock; + let sock; beforeEach(function () { - sock = new Websock(); - sock._allocate_buffers(); + sock = new Websock(); + sock._allocateBuffers(); }); - it('should support adding binary Uint8Array data to the receive queue', function () { - var msg = { data: new Uint8Array([1, 2, 3]) }; - sock._mode = 'binary'; - sock._recv_message(msg); + it('should support adding data to the receive queue', function () { + const msg = { data: new Uint8Array([1, 2, 3]) }; + sock._recvMessage(msg); expect(sock.rQshiftStr(3)).to.equal('\x01\x02\x03'); }); it('should call the message event handler if present', function () { sock._eventHandlers.message = sinon.spy(); - var msg = { data: new Uint8Array([1, 2, 3]).buffer }; + const msg = { data: new Uint8Array([1, 2, 3]).buffer }; sock._mode = 'binary'; - sock._recv_message(msg); + sock._recvMessage(msg); expect(sock._eventHandlers.message).to.have.been.calledOnce; }); it('should not call the message event handler if there is nothing in the receive queue', function () { sock._eventHandlers.message = sinon.spy(); - var msg = { data: new Uint8Array([]).buffer }; + const msg = { data: new Uint8Array([]).buffer }; sock._mode = 'binary'; - sock._recv_message(msg); + sock._recvMessage(msg); expect(sock._eventHandlers.message).not.to.have.been.called; }); - it('should compact the receive queue', function () { - // NB(sross): while this is an internal implementation detail, it's important to - // test, otherwise the receive queue could become very large very quickly + it('should compact the receive queue when fully read', function () { sock._rQ = new Uint8Array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0]); sock._rQlen = 6; - sock.set_rQi(6); - sock._rQmax = 3; - var msg = { data: new Uint8Array([1, 2, 3]).buffer }; - sock._mode = 'binary'; - sock._recv_message(msg); + sock._rQi = 6; + const msg = { data: new Uint8Array([1, 2, 3]).buffer }; + sock._recvMessage(msg); expect(sock._rQlen).to.equal(3); - expect(sock.get_rQi()).to.equal(0); + expect(sock._rQi).to.equal(0); }); - it('should automatically resize the receive queue if the incoming message is too large', function () { + it('should compact the receive queue when we reach the end of the buffer', function () { + sock._rQ = new Uint8Array(20); + sock._rQbufferSize = 20; + sock._rQlen = 20; + sock._rQi = 10; + const msg = { data: new Uint8Array([1, 2]).buffer }; + sock._recvMessage(msg); + expect(sock._rQlen).to.equal(12); + expect(sock._rQi).to.equal(0); + }); + + it('should automatically resize the receive queue if the incoming message is larger than the buffer', function () { sock._rQ = new Uint8Array(20); sock._rQlen = 0; - sock.set_rQi(0); + sock._rQi = 0; sock._rQbufferSize = 20; - sock._rQmax = 2; - var msg = { data: new Uint8Array(30).buffer }; - sock._mode = 'binary'; - sock._recv_message(msg); + const msg = { data: new Uint8Array(30).buffer }; + sock._recvMessage(msg); expect(sock._rQlen).to.equal(30); - expect(sock.get_rQi()).to.equal(0); + expect(sock._rQi).to.equal(0); expect(sock._rQ.length).to.equal(240); // keep the invariant that rQbufferSize / 8 >= rQlen }); - }); - - describe('Data encoding', function () { - before(function () { FakeWebSocket.replace(); }); - after(function () { FakeWebSocket.restore(); }); - - describe('as binary data', function () { - var sock; - beforeEach(function () { - sock = new Websock(); - sock.open('ws://', 'binary'); - sock._websocket._open(); - }); - - it('should only send the send queue up to the send queue length', function () { - sock._sQ = new Uint8Array([1, 2, 3, 4, 5]); - sock._sQlen = 3; - var res = sock._encode_message(); - expect(res).to.array.equal(new Uint8Array([1, 2, 3])); - }); - it('should properly pass the encoded data off to the actual WebSocket', function () { - sock.send([1, 2, 3]); - expect(sock._websocket._get_sent_data()).to.array.equal(new Uint8Array([1, 2, 3])); - }); + it('should automatically resize the receive queue if the incoming message is larger than 1/8th of the buffer and we reach the end of the buffer', function () { + sock._rQ = new Uint8Array(20); + sock._rQlen = 16; + sock._rQi = 15; + sock._rQbufferSize = 20; + const msg = { data: new Uint8Array(6).buffer }; + sock._recvMessage(msg); + expect(sock._rQlen).to.equal(7); + expect(sock._rQi).to.equal(0); + expect(sock._rQ.length).to.equal(56); }); }); }); diff --git a/tests/test.webutil.js b/tests/test.webutil.js new file mode 100644 index 000000000..df8227aef --- /dev/null +++ b/tests/test.webutil.js @@ -0,0 +1,240 @@ +/* jshint expr: true */ + +const expect = chai.expect; + +import * as WebUtil from '../app/webutil.js'; + +describe('WebUtil', function () { + "use strict"; + + describe('config variables', function () { + let origState, origHref; + beforeEach(function () { + origState = history.state; + origHref = location.href; + }); + afterEach(function () { + history.replaceState(origState, '', origHref); + }); + + it('should parse query string variables', function () { + // history.pushState() will not cause the browser to attempt loading + // the URL, this is exactly what we want here for the tests. + history.replaceState({}, '', "test?myvar=myval"); + expect(WebUtil.getConfigVar("myvar")).to.be.equal("myval"); + }); + it('should return default value when no query match', function () { + history.replaceState({}, '', "test?myvar=myval"); + expect(WebUtil.getConfigVar("other", "def")).to.be.equal("def"); + }); + it('should handle no query match and no default value', function () { + history.replaceState({}, '', "test?myvar=myval"); + expect(WebUtil.getConfigVar("other")).to.be.equal(null); + }); + it('should parse fragment variables', function () { + history.replaceState({}, '', "test#myvar=myval"); + expect(WebUtil.getConfigVar("myvar")).to.be.equal("myval"); + }); + it('should return default value when no fragment match', function () { + history.replaceState({}, '', "test#myvar=myval"); + expect(WebUtil.getConfigVar("other", "def")).to.be.equal("def"); + }); + it('should handle no fragment match and no default value', function () { + history.replaceState({}, '', "test#myvar=myval"); + expect(WebUtil.getConfigVar("other")).to.be.equal(null); + }); + it('should handle both query and fragment', function () { + history.replaceState({}, '', "test?myquery=1#myhash=2"); + expect(WebUtil.getConfigVar("myquery")).to.be.equal("1"); + expect(WebUtil.getConfigVar("myhash")).to.be.equal("2"); + }); + it('should prioritize fragment if both provide same var', function () { + history.replaceState({}, '', "test?myvar=1#myvar=2"); + expect(WebUtil.getConfigVar("myvar")).to.be.equal("2"); + }); + }); + + describe('cookies', function () { + // TODO + }); + + describe('settings', function () { + + describe('localStorage', function () { + let chrome = window.chrome; + before(function () { + chrome = window.chrome; + window.chrome = null; + }); + after(function () { + window.chrome = chrome; + }); + + let origLocalStorage; + beforeEach(function () { + origLocalStorage = Object.getOwnPropertyDescriptor(window, "localStorage"); + + Object.defineProperty(window, "localStorage", {value: {}}); + + window.localStorage.setItem = sinon.stub(); + window.localStorage.getItem = sinon.stub(); + window.localStorage.removeItem = sinon.stub(); + + return WebUtil.initSettings(); + }); + afterEach(function () { + Object.defineProperty(window, "localStorage", origLocalStorage); + }); + + describe('writeSetting', function () { + it('should save the setting value to local storage', function () { + WebUtil.writeSetting('test', 'value'); + expect(window.localStorage.setItem).to.have.been.calledWithExactly('test', 'value'); + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + + it('should not crash when local storage save fails', function () { + localStorage.setItem.throws(new DOMException()); + expect(WebUtil.writeSetting('test', 'value')).to.not.throw; + }); + }); + + describe('setSetting', function () { + it('should update the setting but not save to local storage', function () { + WebUtil.setSetting('test', 'value'); + expect(window.localStorage.setItem).to.not.have.been.called; + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + }); + + describe('readSetting', function () { + it('should read the setting value from local storage', function () { + localStorage.getItem.returns('value'); + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + + it('should return the default value when not in local storage', function () { + expect(WebUtil.readSetting('test', 'default')).to.equal('default'); + }); + + it('should return the cached value even if local storage changed', function () { + localStorage.getItem.returns('value'); + expect(WebUtil.readSetting('test')).to.equal('value'); + localStorage.getItem.returns('something else'); + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + + it('should cache the value even if it is not initially in local storage', function () { + expect(WebUtil.readSetting('test')).to.be.null; + localStorage.getItem.returns('value'); + expect(WebUtil.readSetting('test')).to.be.null; + }); + + it('should return the default value always if the first read was not in local storage', function () { + expect(WebUtil.readSetting('test', 'default')).to.equal('default'); + localStorage.getItem.returns('value'); + expect(WebUtil.readSetting('test', 'another default')).to.equal('another default'); + }); + + it('should return the last local written value', function () { + localStorage.getItem.returns('value'); + expect(WebUtil.readSetting('test')).to.equal('value'); + WebUtil.writeSetting('test', 'something else'); + expect(WebUtil.readSetting('test')).to.equal('something else'); + }); + + it('should not crash when local storage read fails', function () { + localStorage.getItem.throws(new DOMException()); + expect(WebUtil.readSetting('test')).to.not.throw; + }); + }); + + // this doesn't appear to be used anywhere + describe('eraseSetting', function () { + it('should remove the setting from local storage', function () { + WebUtil.eraseSetting('test'); + expect(window.localStorage.removeItem).to.have.been.calledWithExactly('test'); + }); + + it('should not crash when local storage remove fails', function () { + localStorage.removeItem.throws(new DOMException()); + expect(WebUtil.eraseSetting('test')).to.not.throw; + }); + }); + }); + + describe('chrome.storage', function () { + let chrome = window.chrome; + let settings = {}; + before(function () { + chrome = window.chrome; + window.chrome = { + storage: { + sync: { + get(cb) { cb(settings); }, + set() {}, + remove() {} + } + } + }; + }); + after(function () { + window.chrome = chrome; + }); + + const csSandbox = sinon.createSandbox(); + + beforeEach(function () { + settings = {}; + csSandbox.spy(window.chrome.storage.sync, 'set'); + csSandbox.spy(window.chrome.storage.sync, 'remove'); + return WebUtil.initSettings(); + }); + afterEach(function () { + csSandbox.restore(); + }); + + describe('writeSetting', function () { + it('should save the setting value to chrome storage', function () { + WebUtil.writeSetting('test', 'value'); + expect(window.chrome.storage.sync.set).to.have.been.calledWithExactly(sinon.match({ test: 'value' })); + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + }); + + describe('setSetting', function () { + it('should update the setting but not save to chrome storage', function () { + WebUtil.setSetting('test', 'value'); + expect(window.chrome.storage.sync.set).to.not.have.been.called; + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + }); + + describe('readSetting', function () { + it('should read the setting value from chrome storage', function () { + settings.test = 'value'; + expect(WebUtil.readSetting('test')).to.equal('value'); + }); + + it('should return the default value when not in chrome storage', function () { + expect(WebUtil.readSetting('test', 'default')).to.equal('default'); + }); + + it('should return the last local written value', function () { + settings.test = 'value'; + expect(WebUtil.readSetting('test')).to.equal('value'); + WebUtil.writeSetting('test', 'something else'); + expect(WebUtil.readSetting('test')).to.equal('something else'); + }); + }); + + // this doesn't appear to be used anywhere + describe('eraseSetting', function () { + it('should remove the setting from chrome storage', function () { + WebUtil.eraseSetting('test'); + expect(window.chrome.storage.sync.remove).to.have.been.calledWithExactly('test'); + }); + }); + }); + }); +}); diff --git a/tests/test.zrle.js b/tests/test.zrle.js new file mode 100644 index 000000000..be0464093 --- /dev/null +++ b/tests/test.zrle.js @@ -0,0 +1,144 @@ +const expect = chai.expect; + +import Websock from '../core/websock.js'; +import Display from '../core/display.js'; + +import ZRLEDecoder from '../core/decoders/zrle.js'; + +import FakeWebSocket from './fake.websocket.js'; + +function testDecodeRect(decoder, x, y, width, height, data, display, depth) { + let sock; + let done = false; + + sock = new Websock; + sock.open("ws://example.com"); + + sock.on('message', () => { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + }); + + // Empty messages are filtered at multiple layers, so we need to + // do a direct call + if (data.length === 0) { + done = decoder.decodeRect(x, y, width, height, sock, display, depth); + } else { + sock._websocket._receiveData(new Uint8Array(data)); + } + + display.flip(); + + return done; +} + +describe('ZRLE Decoder', function () { + let decoder; + let display; + + before(FakeWebSocket.replace); + after(FakeWebSocket.restore); + + beforeEach(function () { + decoder = new ZRLEDecoder(); + display = new Display(document.createElement('canvas')); + display.resize(4, 4); + }); + + it('should handle the Raw subencoding', function () { + let done = testDecodeRect(decoder, 0, 0, 4, 4, + [0x00, 0x00, 0x00, 0x0e, 0x78, 0x5e, + 0x62, 0x60, 0x60, 0xf8, 0x4f, 0x12, + 0x02, 0x00, 0x00, 0x00, 0xff, 0xff], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle the Solid subencoding', function () { + let done = testDecodeRect(decoder, 0, 0, 4, 4, + [0x00, 0x00, 0x00, 0x0c, 0x78, 0x5e, + 0x62, 0x64, 0x60, 0xf8, 0x0f, 0x00, + 0x00, 0x00, 0xff, 0xff], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + + it('should handle the Palette Tile subencoding', function () { + let done = testDecodeRect(decoder, 0, 0, 4, 4, + [0x00, 0x00, 0x00, 0x12, 0x78, 0x5E, + 0x62, 0x62, 0x60, 248, 0xff, 0x9F, + 0x01, 0x08, 0x3E, 0x7C, 0x00, 0x00, + 0x00, 0x00, 0xff, 0xff], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, + 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle the RLE Tile subencoding', function () { + let done = testDecodeRect(decoder, 0, 0, 4, 4, + [0x00, 0x00, 0x00, 0x0d, 0x78, 0x5e, + 0x6a, 0x60, 0x60, 0xf8, 0x2f, 0x00, + 0x00, 0x00, 0x00, 0xff, 0xff], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should handle the RLE Palette Tile subencoding', function () { + let done = testDecodeRect(decoder, 0, 0, 4, 4, + [0x00, 0x00, 0x00, 0x11, 0x78, 0x5e, + 0x6a, 0x62, 0x60, 0xf8, 0xff, 0x9f, + 0x81, 0xa1, 0x81, 0x1f, 0x00, 0x00, + 0x00, 0xff, 0xff], + display, 24); + + let targetData = new Uint8Array([ + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff + ]); + + expect(done).to.be.true; + expect(display).to.have.displayed(targetData); + }); + + it('should fail on an invalid subencoding', function () { + let data = [0x00, 0x00, 0x00, 0x0c, 0x78, 0x5e, 0x6a, 0x64, 0x60, 0xf8, 0x0f, 0x00, 0x00, 0x00, 0xff, 0xff]; + expect(() => testDecodeRect(decoder, 0, 0, 4, 4, data, display, 24)).to.throw(); + }); +}); diff --git a/tests/vnc_perf.html b/tests/vnc_perf.html deleted file mode 100644 index 6e4f4a31d..000000000 --- a/tests/vnc_perf.html +++ /dev/null @@ -1,206 +0,0 @@ - - - - VNC Performance Benchmark - - - - Passes:   - -   - -

- - Results:
- - -

- -
-
- - -
Loading
-
- - Canvas not supported. - -
- - - - - - - - - - - diff --git a/tests/vnc_playback.html b/tests/vnc_playback.html index 66f405765..ffa69906d 100644 --- a/tests/vnc_playback.html +++ b/tests/vnc_playback.html @@ -1,42 +1,26 @@ - + VNC Playback - - + - Iterations:   + Iterations:   Perftest:  Realtime:   -   +  

Results:
- +

-
- - -
Loading
-
- - Canvas not supported. - +
Loading
- - - - - `; - }, - noCopyOverride: () => {}, - }, - 'commonjs': { - optionsOverride: (opts) => { - // CommonJS supports properly shifting the default export to work as normal - opts.plugins.unshift("add-module-exports"); - }, - appWriter: (base_out_path, out_path) => { - var browserify = require('browserify'); - var b = browserify(path.join(base_out_path, 'app/ui.js'), {}); - b.bundle().pipe(fs.createWriteStream(out_path)); - return ``; - }, - noCopyOverride: () => {}, - }, - 'systemjs': { - appWriter: (base_out_path, out_path) => { - fs.writeFile(out_path, 'SystemJS.import("./app/ui.js");', (err) => { if (err) throw err; }); - console.log(`Please place SystemJS in ${path.join(base_out_path, 'system-production.js')}`); - return ` -\n`; - }, - noCopyOverride: (paths, no_copy_files) => { - no_copy_files.delete(path.join(paths.vendor, 'promise.js')); - }, - }, - 'umd': { - optionsOverride: (opts) => { - // umd supports properly shifting the default export to work as normal - opts.plugins.unshift("add-module-exports"); - }, - }, -} diff --git a/utils/validate b/utils/validate new file mode 100755 index 000000000..a6b5507d2 --- /dev/null +++ b/utils/validate @@ -0,0 +1,45 @@ +#!/bin/bash + +set -e + +RET=0 + +OUT=`mktemp` + +for fn in "$@"; do + echo "Validating $fn..." + echo + + case $fn in + *.html) + type="text/html" + ;; + *.css) + type="text/css" + ;; + *) + echo "Unknown format!" + echo + RET=1 + continue + ;; + esac + + curl --silent \ + --header "Content-Type: ${type}; charset=utf-8" \ + --data-binary @${fn} \ + https://validator.w3.org/nu/?out=text > $OUT + cat $OUT + echo + + # We don't fail the check for warnings as some warnings are + # not relevant for us, and we don't currently have a way to + # ignore just those + if grep -q -s -E "^Error:" $OUT; then + RET=1 + fi +done + +rm $OUT + +exit $RET diff --git a/vendor/browser-es-module-loader/.npmignore b/vendor/browser-es-module-loader/.npmignore deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/browser-es-module-loader/README.md b/vendor/browser-es-module-loader/README.md deleted file mode 100644 index c26867f97..000000000 --- a/vendor/browser-es-module-loader/README.md +++ /dev/null @@ -1,15 +0,0 @@ -Custom Browser ES Module Loader -=============================== - -This is a module loader using babel and the ES Module Loader polyfill. -It's based heavily on -https://github.com/ModuleLoader/browser-es-module-loader, but uses -WebWorkers to compile the modules in the background. - -To generate, run `rollup -c` in this directory, and then run `browserify -src/babel-worker.js > dist/babel-worker.js`. - -LICENSE -------- - -MIT diff --git a/vendor/browser-es-module-loader/dist/babel-worker.js b/vendor/browser-es-module-loader/dist/babel-worker.js deleted file mode 100644 index 6c40dccf1..000000000 --- a/vendor/browser-es-module-loader/dist/babel-worker.js +++ /dev/null @@ -1,44024 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<]/g; -}; - -},{}],2:[function(require,module,exports){ -'use strict'; - -function assembleStyles () { - var styles = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39] - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49] - } - }; - - // fix humans - styles.colors.grey = styles.colors.gray; - - Object.keys(styles).forEach(function (groupName) { - var group = styles[groupName]; - - Object.keys(group).forEach(function (styleName) { - var style = group[styleName]; - - styles[styleName] = group[styleName] = { - open: '\u001b[' + style[0] + 'm', - close: '\u001b[' + style[1] + 'm' - }; - }); - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - }); - - return styles; -} - -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - -},{}],3:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (rawLines, lineNumber, colNumber) { - var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - - colNumber = Math.max(colNumber, 0); - - var highlighted = opts.highlightCode && _chalk2.default.supportsColor || opts.forceColor; - var chalk = _chalk2.default; - if (opts.forceColor) { - chalk = new _chalk2.default.constructor({ enabled: true }); - } - var maybeHighlight = function maybeHighlight(chalkFn, string) { - return highlighted ? chalkFn(string) : string; - }; - var defs = getDefs(chalk); - if (highlighted) rawLines = highlight(defs, rawLines); - - var linesAbove = opts.linesAbove || 2; - var linesBelow = opts.linesBelow || 3; - - var lines = rawLines.split(NEWLINE); - var start = Math.max(lineNumber - (linesAbove + 1), 0); - var end = Math.min(lines.length, lineNumber + linesBelow); - - if (!lineNumber && !colNumber) { - start = 0; - end = lines.length; - } - - var numberMaxWidth = String(end).length; - - var frame = lines.slice(start, end).map(function (line, index) { - var number = start + 1 + index; - var paddedNumber = (" " + number).slice(-numberMaxWidth); - var gutter = " " + paddedNumber + " | "; - if (number === lineNumber) { - var markerLine = ""; - if (colNumber) { - var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); - markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join(""); - } - return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); - } else { - return " " + maybeHighlight(defs.gutter, gutter) + line; - } - }).join("\n"); - - if (highlighted) { - return chalk.reset(frame); - } else { - return frame; - } -}; - -var _jsTokens = require("js-tokens"); - -var _jsTokens2 = _interopRequireDefault(_jsTokens); - -var _esutils = require("esutils"); - -var _esutils2 = _interopRequireDefault(_esutils); - -var _chalk = require("chalk"); - -var _chalk2 = _interopRequireDefault(_chalk); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getDefs(chalk) { - return { - keyword: chalk.cyan, - capitalized: chalk.yellow, - jsx_tag: chalk.yellow, - punctuator: chalk.yellow, - - number: chalk.magenta, - string: chalk.green, - regex: chalk.magenta, - comment: chalk.grey, - invalid: chalk.white.bgRed.bold, - gutter: chalk.grey, - marker: chalk.red.bold - }; -} - -var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; - -var JSX_TAG = /^[a-z][\w-]*$/i; - -var BRACKET = /^[()\[\]{}]$/; - -function getTokenType(match) { - var _match$slice = match.slice(-2), - offset = _match$slice[0], - text = _match$slice[1]; - - var token = (0, _jsTokens.matchToToken)(match); - - if (token.type === "name") { - if (_esutils2.default.keyword.isReservedWordES6(token.value)) { - return "keyword"; - } - - if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " 1 && arguments[1] !== undefined ? arguments[1] : {}; - - opts.filename = filename; - return transform(_fs2.default.readFileSync(filename, "utf8"), opts); -} -},{"../../package":31,"../helpers/resolve-plugin":11,"../helpers/resolve-preset":12,"../tools/build-external-helpers":15,"../transformation/file":16,"../transformation/file/options/config":20,"../transformation/file/options/option-manager":22,"../transformation/pipeline":27,"../util":30,"babel-messages":53,"babel-template":75,"babel-traverse":79,"babel-types":112,"fs":120}],6:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = getPossiblePluginNames; -function getPossiblePluginNames(pluginName) { - return ["babel-plugin-" + pluginName, pluginName]; -} -module.exports = exports["default"]; -},{}],7:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = getPossiblePresetNames; -function getPossiblePresetNames(presetName) { - var possibleNames = ["babel-preset-" + presetName, presetName]; - - var matches = presetName.match(/^(@[^/]+)\/(.+)$/); - if (matches) { - var orgName = matches[1], - presetPath = matches[2]; - - possibleNames.push(orgName + "/babel-preset-" + presetPath); - } - - return possibleNames; -} -module.exports = exports["default"]; -},{}],8:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (dest, src) { - if (!dest || !src) return; - - return (0, _mergeWith2.default)(dest, src, function (a, b) { - if (b && Array.isArray(a)) { - var newArray = b.slice(0); - - for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var item = _ref; - - if (newArray.indexOf(item) < 0) { - newArray.push(item); - } - } - - return newArray; - } - }); -}; - -var _mergeWith = require("lodash/mergeWith"); - -var _mergeWith2 = _interopRequireDefault(_mergeWith); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":56,"lodash/mergeWith":451}],9:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (ast, comments, tokens) { - if (ast) { - if (ast.type === "Program") { - return t.file(ast, comments || [], tokens || []); - } else if (ast.type === "File") { - return ast; - } - } - - throw new Error("Not a valid ast?"); -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -module.exports = exports["default"]; -},{"babel-types":112}],10:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.default = resolveFromPossibleNames; - -var _resolve = require("./resolve"); - -var _resolve2 = _interopRequireDefault(_resolve); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function resolveFromPossibleNames(possibleNames, dirname) { - return possibleNames.reduce(function (accum, curr) { - return accum || (0, _resolve2.default)(curr, dirname); - }, null); -} -module.exports = exports["default"]; -},{"./resolve":13}],11:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; -exports.default = resolvePlugin; - -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); - -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); - -var _getPossiblePluginNames = require("./get-possible-plugin-names"); - -var _getPossiblePluginNames2 = _interopRequireDefault(_getPossiblePluginNames); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function resolvePlugin(pluginName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); - - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePluginNames2.default)(pluginName), dirname); -} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-plugin-names":6,"./resolve-from-possible-names":10,"_process":471}],12:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; -exports.default = resolvePreset; - -var _resolveFromPossibleNames = require("./resolve-from-possible-names"); - -var _resolveFromPossibleNames2 = _interopRequireDefault(_resolveFromPossibleNames); - -var _getPossiblePresetNames = require("./get-possible-preset-names"); - -var _getPossiblePresetNames2 = _interopRequireDefault(_getPossiblePresetNames); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function resolvePreset(presetName) { - var dirname = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); - - return (0, _resolveFromPossibleNames2.default)((0, _getPossiblePresetNames2.default)(presetName), dirname); -} -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./get-possible-preset-names":7,"./resolve-from-possible-names":10,"_process":471}],13:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -exports.default = function (loc) { - var relative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.cwd(); - - if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null; - - var relativeMod = relativeModules[relative]; - - if (!relativeMod) { - relativeMod = new _module2.default(); - - var filename = _path2.default.join(relative, ".babelrc"); - relativeMod.id = filename; - relativeMod.filename = filename; - - relativeMod.paths = _module2.default._nodeModulePaths(relative); - relativeModules[relative] = relativeMod; - } - - try { - return _module2.default._resolveFilename(loc, relativeMod); - } catch (err) { - return null; - } -}; - -var _module = require("module"); - -var _module2 = _interopRequireDefault(_module); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var relativeModules = {}; - -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"_process":471,"babel-runtime/helpers/typeof":74,"module":120,"path":469}],14:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Store = function (_Map) { - (0, _inherits3.default)(Store, _Map); - - function Store() { - (0, _classCallCheck3.default)(this, Store); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this)); - - _this.dynamicData = {}; - return _this; - } - - Store.prototype.setDynamic = function setDynamic(key, fn) { - this.dynamicData[key] = fn; - }; - - Store.prototype.get = function get(key) { - if (this.has(key)) { - return _Map.prototype.get.call(this, key); - } else { - if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) { - var val = this.dynamicData[key](); - this.set(key, val); - return val; - } - } - }; - - return Store; -}(_map2.default); - -exports.default = Store; -module.exports = exports["default"]; -},{"babel-runtime/core-js/map":58,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/inherits":71,"babel-runtime/helpers/possibleConstructorReturn":73}],15:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (whitelist) { - var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "global"; - - var namespace = t.identifier("babelHelpers"); - - var builder = function builder(body) { - return buildHelpers(body, namespace, whitelist); - }; - - var tree = void 0; - - var build = { - global: buildGlobal, - umd: buildUmd, - var: buildVar - }[outputType]; - - if (build) { - tree = build(namespace, builder); - } else { - throw new Error(messages.get("unsupportedOutputType", outputType)); - } - - return (0, _babelGenerator2.default)(tree).code; -}; - -var _babelHelpers = require("babel-helpers"); - -var helpers = _interopRequireWildcard(_babelHelpers); - -var _babelGenerator = require("babel-generator"); - -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var buildUmdWrapper = (0, _babelTemplate2.default)("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n"); - -function buildGlobal(namespace, builder) { - var body = []; - var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); - var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]); - - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))])); - - builder(body); - - return tree; -} - -function buildUmd(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))])); - - builder(body); - - return t.program([buildUmdWrapper({ - FACTORY_PARAMETERS: t.identifier("global"), - BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])), - COMMON_ARGUMENTS: t.identifier("exports"), - AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]), - FACTORY_BODY: body, - UMD_ROOT: t.identifier("this") - })]); -} - -function buildVar(namespace, builder) { - var body = []; - body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))])); - builder(body); - body.push(t.expressionStatement(namespace)); - return t.program(body); -} - -function buildHelpers(body, namespace, whitelist) { - helpers.list.forEach(function (name) { - if (whitelist && whitelist.indexOf(name) < 0) return; - - var key = t.identifier(name); - body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name)))); - }); -} -module.exports = exports["default"]; -},{"babel-generator":43,"babel-helpers":52,"babel-messages":53,"babel-template":75,"babel-types":112}],16:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; -exports.File = undefined; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _babelHelpers = require("babel-helpers"); - -var _babelHelpers2 = _interopRequireDefault(_babelHelpers); - -var _metadata = require("./metadata"); - -var metadataVisitor = _interopRequireWildcard(_metadata); - -var _convertSourceMap = require("convert-source-map"); - -var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap); - -var _optionManager = require("./options/option-manager"); - -var _optionManager2 = _interopRequireDefault(_optionManager); - -var _pluginPass = require("../plugin-pass"); - -var _pluginPass2 = _interopRequireDefault(_pluginPass); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _sourceMap = require("source-map"); - -var _sourceMap2 = _interopRequireDefault(_sourceMap); - -var _babelGenerator = require("babel-generator"); - -var _babelGenerator2 = _interopRequireDefault(_babelGenerator); - -var _babelCodeFrame = require("babel-code-frame"); - -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); - -var _defaults = require("lodash/defaults"); - -var _defaults2 = _interopRequireDefault(_defaults); - -var _logger = require("./logger"); - -var _logger2 = _interopRequireDefault(_logger); - -var _store = require("../../store"); - -var _store2 = _interopRequireDefault(_store); - -var _babylon = require("babylon"); - -var _util = require("../../util"); - -var util = _interopRequireWildcard(_util); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _resolve = require("../../helpers/resolve"); - -var _resolve2 = _interopRequireDefault(_resolve); - -var _blockHoist = require("../internal-plugins/block-hoist"); - -var _blockHoist2 = _interopRequireDefault(_blockHoist); - -var _shadowFunctions = require("../internal-plugins/shadow-functions"); - -var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var shebangRegex = /^#!.*/; - -var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]]; - -var errorVisitor = { - enter: function enter(path, state) { - var loc = path.node.loc; - if (loc) { - state.loc = loc; - path.stop(); - } - } -}; - -var File = function (_Store) { - (0, _inherits3.default)(File, _Store); - - function File() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var pipeline = arguments[1]; - (0, _classCallCheck3.default)(this, File); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.pipeline = pipeline; - - _this.log = new _logger2.default(_this, opts.filename || "unknown"); - _this.opts = _this.initOptions(opts); - - _this.parserOpts = { - sourceType: _this.opts.sourceType, - sourceFileName: _this.opts.filename, - plugins: [] - }; - - _this.pluginVisitors = []; - _this.pluginPasses = []; - - _this.buildPluginsForOptions(_this.opts); - - if (_this.opts.passPerPreset) { - _this.perPresetOpts = []; - _this.opts.presets.forEach(function (presetOpts) { - var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_this.opts), presetOpts); - _this.perPresetOpts.push(perPresetOpts); - _this.buildPluginsForOptions(perPresetOpts); - }); - } - - _this.metadata = { - usedHelpers: [], - marked: [], - modules: { - imports: [], - exports: { - exported: [], - specifiers: [] - } - } - }; - - _this.dynamicImportTypes = {}; - _this.dynamicImportIds = {}; - _this.dynamicImports = []; - _this.declarations = {}; - _this.usedHelpers = {}; - - _this.path = null; - _this.ast = {}; - - _this.code = ""; - _this.shebang = ""; - - _this.hub = new _babelTraverse.Hub(_this); - return _this; - } - - File.prototype.getMetadata = function getMetadata() { - var has = false; - for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var node = _ref; - - if (t.isModuleDeclaration(node)) { - has = true; - break; - } - } - if (has) { - this.path.traverse(metadataVisitor, this); - } - }; - - File.prototype.initOptions = function initOptions(opts) { - opts = new _optionManager2.default(this.log, this.pipeline).init(opts); - - if (opts.inputSourceMap) { - opts.sourceMaps = true; - } - - if (opts.moduleId) { - opts.moduleIds = true; - } - - opts.basename = _path2.default.basename(opts.filename, _path2.default.extname(opts.filename)); - - opts.ignore = util.arrayify(opts.ignore, util.regexify); - - if (opts.only) opts.only = util.arrayify(opts.only, util.regexify); - - (0, _defaults2.default)(opts, { - moduleRoot: opts.sourceRoot - }); - - (0, _defaults2.default)(opts, { - sourceRoot: opts.moduleRoot - }); - - (0, _defaults2.default)(opts, { - filenameRelative: opts.filename - }); - - var basenameRelative = _path2.default.basename(opts.filenameRelative); - - (0, _defaults2.default)(opts, { - sourceFileName: basenameRelative, - sourceMapTarget: basenameRelative - }); - - return opts; - }; - - File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) { - if (!Array.isArray(opts.plugins)) { - return; - } - - var plugins = opts.plugins.concat(INTERNAL_PLUGINS); - var currentPluginVisitors = []; - var currentPluginPasses = []; - - for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var ref = _ref2; - var plugin = ref[0], - pluginOpts = ref[1]; - - - currentPluginVisitors.push(plugin.visitor); - currentPluginPasses.push(new _pluginPass2.default(this, plugin, pluginOpts)); - - if (plugin.manipulateOptions) { - plugin.manipulateOptions(opts, this.parserOpts, this); - } - } - - this.pluginVisitors.push(currentPluginVisitors); - this.pluginPasses.push(currentPluginPasses); - }; - - File.prototype.getModuleName = function getModuleName() { - var opts = this.opts; - if (!opts.moduleIds) { - return null; - } - - if (opts.moduleId != null && !opts.getModuleId) { - return opts.moduleId; - } - - var filenameRelative = opts.filenameRelative; - var moduleName = ""; - - if (opts.moduleRoot != null) { - moduleName = opts.moduleRoot + "/"; - } - - if (!opts.filenameRelative) { - return moduleName + opts.filename.replace(/^\//, ""); - } - - if (opts.sourceRoot != null) { - var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); - filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); - } - - filenameRelative = filenameRelative.replace(/\.(\w*?)$/, ""); - - moduleName += filenameRelative; - - moduleName = moduleName.replace(/\\/g, "/"); - - if (opts.getModuleId) { - return opts.getModuleId(moduleName) || moduleName; - } else { - return moduleName; - } - }; - - File.prototype.resolveModuleSource = function resolveModuleSource(source) { - var resolveModuleSource = this.opts.resolveModuleSource; - if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename); - return source; - }; - - File.prototype.addImport = function addImport(source, imported) { - var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : imported; - - var alias = source + ":" + imported; - var id = this.dynamicImportIds[alias]; - - if (!id) { - source = this.resolveModuleSource(source); - id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name); - - var specifiers = []; - - if (imported === "*") { - specifiers.push(t.importNamespaceSpecifier(id)); - } else if (imported === "default") { - specifiers.push(t.importDefaultSpecifier(id)); - } else { - specifiers.push(t.importSpecifier(id, t.identifier(imported))); - } - - var declar = t.importDeclaration(specifiers, t.stringLiteral(source)); - declar._blockHoist = 3; - - this.path.unshiftContainer("body", declar); - } - - return id; - }; - - File.prototype.addHelper = function addHelper(name) { - var declar = this.declarations[name]; - if (declar) return declar; - - if (!this.usedHelpers[name]) { - this.metadata.usedHelpers.push(name); - this.usedHelpers[name] = true; - } - - var generator = this.get("helperGenerator"); - var runtime = this.get("helpersNamespace"); - if (generator) { - var res = generator(name); - if (res) return res; - } else if (runtime) { - return t.memberExpression(runtime, t.identifier(name)); - } - - var ref = (0, _babelHelpers2.default)(name); - var uid = this.declarations[name] = this.scope.generateUidIdentifier(name); - - if (t.isFunctionExpression(ref) && !ref.id) { - ref.body._compact = true; - ref._generated = true; - ref.id = uid; - ref.type = "FunctionDeclaration"; - this.path.unshiftContainer("body", ref); - } else { - ref._compact = true; - this.scope.push({ - id: uid, - init: ref, - unique: true - }); - } - - return uid; - }; - - File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) { - var stringIds = raw.elements.map(function (string) { - return string.value; - }); - var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(","); - - var declar = this.declarations[name]; - if (declar) return declar; - - var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject"); - - var helperId = this.addHelper(helperName); - var init = t.callExpression(helperId, [strings, raw]); - init._compact = true; - this.scope.push({ - id: uid, - init: init, - _blockHoist: 1.9 }); - return uid; - }; - - File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) { - var Error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SyntaxError; - - var loc = node && (node.loc || node._loc); - - var err = new Error(msg); - - if (loc) { - err.loc = loc.start; - } else { - (0, _babelTraverse2.default)(node, errorVisitor, this.scope, err); - - err.message += " (This is an error on an internal node. Probably an internal error"; - - if (err.loc) { - err.message += ". Location has been estimated."; - } - - err.message += ")"; - } - - return err; - }; - - File.prototype.mergeSourceMap = function mergeSourceMap(map) { - var inputMap = this.opts.inputSourceMap; - - if (inputMap) { - var _ret = function () { - var inputMapConsumer = new _sourceMap2.default.SourceMapConsumer(inputMap); - var outputMapConsumer = new _sourceMap2.default.SourceMapConsumer(map); - - var mergedGenerator = new _sourceMap2.default.SourceMapGenerator({ - file: inputMapConsumer.file, - sourceRoot: inputMapConsumer.sourceRoot - }); - - var source = outputMapConsumer.sources[0]; - - inputMapConsumer.eachMapping(function (mapping) { - var generatedPosition = outputMapConsumer.generatedPositionFor({ - line: mapping.generatedLine, - column: mapping.generatedColumn, - source: source - }); - if (generatedPosition.column != null) { - mergedGenerator.addMapping({ - source: mapping.source, - - original: mapping.source == null ? null : { - line: mapping.originalLine, - column: mapping.originalColumn - }, - - generated: generatedPosition - }); - } - }); - - var mergedMap = mergedGenerator.toJSON(); - inputMap.mappings = mergedMap.mappings; - return { - v: inputMap - }; - }(); - - if ((typeof _ret === "undefined" ? "undefined" : (0, _typeof3.default)(_ret)) === "object") return _ret.v; - } else { - return map; - } - }; - - File.prototype.parse = function parse(code) { - var parseCode = _babylon.parse; - var parserOpts = this.opts.parserOpts; - - if (parserOpts) { - parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts); - - if (parserOpts.parser) { - if (typeof parserOpts.parser === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var parser = (0, _resolve2.default)(parserOpts.parser, dirname); - if (parser) { - parseCode = require(parser).parse; - } else { - throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method " + ("relative to directory " + dirname)); - } - } else { - parseCode = parserOpts.parser; - } - - parserOpts.parser = { - parse: function parse(source) { - return (0, _babylon.parse)(source, parserOpts); - } - }; - } - } - - this.log.debug("Parse start"); - var ast = parseCode(code, parserOpts || this.parserOpts); - this.log.debug("Parse stop"); - return ast; - }; - - File.prototype._addAst = function _addAst(ast) { - this.path = _babelTraverse.NodePath.get({ - hub: this.hub, - parentPath: null, - parent: ast, - container: ast, - key: "program" - }).setContext(); - this.scope = this.path.scope; - this.ast = ast; - this.getMetadata(); - }; - - File.prototype.addAst = function addAst(ast) { - this.log.debug("Start set AST"); - this._addAst(ast); - this.log.debug("End set AST"); - }; - - File.prototype.transform = function transform() { - for (var i = 0; i < this.pluginPasses.length; i++) { - var pluginPasses = this.pluginPasses[i]; - this.call("pre", pluginPasses); - this.log.debug("Start transform traverse"); - - var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); - (0, _babelTraverse2.default)(this.ast, visitor, this.scope); - - this.log.debug("End transform traverse"); - this.call("post", pluginPasses); - } - - return this.generate(); - }; - - File.prototype.wrap = function wrap(code, callback) { - code = code + ""; - - try { - if (this.shouldIgnore()) { - return this.makeResult({ code: code, ignored: true }); - } else { - return callback(); - } - } catch (err) { - if (err._babel) { - throw err; - } else { - err._babel = true; - } - - var message = err.message = this.opts.filename + ": " + err.message; - - var loc = err.loc; - if (loc) { - err.codeFrame = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts); - message += "\n" + err.codeFrame; - } - - if (process.browser) { - err.message = message; - } - - if (err.stack) { - var newStack = err.stack.replace(err.message, message); - err.stack = newStack; - } - - throw err; - } - }; - - File.prototype.addCode = function addCode(code) { - code = (code || "") + ""; - code = this.parseInputSourceMap(code); - this.code = code; - }; - - File.prototype.parseCode = function parseCode() { - this.parseShebang(); - var ast = this.parse(this.code); - this.addAst(ast); - }; - - File.prototype.shouldIgnore = function shouldIgnore() { - var opts = this.opts; - return util.shouldIgnore(opts.filename, opts.ignore, opts.only); - }; - - File.prototype.call = function call(key, pluginPasses) { - for (var _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var pass = _ref3; - - var plugin = pass.plugin; - var fn = plugin[key]; - if (fn) fn.call(pass, this); - } - }; - - File.prototype.parseInputSourceMap = function parseInputSourceMap(code) { - var opts = this.opts; - - if (opts.inputSourceMap !== false) { - var inputMap = _convertSourceMap2.default.fromSource(code); - if (inputMap) { - opts.inputSourceMap = inputMap.toObject(); - code = _convertSourceMap2.default.removeComments(code); - } - } - - return code; - }; - - File.prototype.parseShebang = function parseShebang() { - var shebangMatch = shebangRegex.exec(this.code); - if (shebangMatch) { - this.shebang = shebangMatch[0]; - this.code = this.code.replace(shebangRegex, ""); - } - }; - - File.prototype.makeResult = function makeResult(_ref4) { - var code = _ref4.code, - map = _ref4.map, - ast = _ref4.ast, - ignored = _ref4.ignored; - - var result = { - metadata: null, - options: this.opts, - ignored: !!ignored, - code: null, - ast: null, - map: map || null - }; - - if (this.opts.code) { - result.code = code; - } - - if (this.opts.ast) { - result.ast = ast; - } - - if (this.opts.metadata) { - result.metadata = this.metadata; - } - - return result; - }; - - File.prototype.generate = function generate() { - var opts = this.opts; - var ast = this.ast; - - var result = { ast: ast }; - if (!opts.code) return this.makeResult(result); - - var gen = _babelGenerator2.default; - if (opts.generatorOpts.generator) { - gen = opts.generatorOpts.generator; - - if (typeof gen === "string") { - var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); - var generator = (0, _resolve2.default)(gen, dirname); - if (generator) { - gen = require(generator).print; - } else { - throw new Error("Couldn't find generator " + gen + " with \"print\" method relative " + ("to directory " + dirname)); - } - } - } - - this.log.debug("Generation start"); - - var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code); - result.code = _result.code; - result.map = _result.map; - - this.log.debug("Generation end"); - - if (this.shebang) { - result.code = this.shebang + "\n" + result.code; - } - - if (result.map) { - result.map = this.mergeSourceMap(result.map); - } - - if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { - result.code += "\n" + _convertSourceMap2.default.fromObject(result.map).toComment(); - } - - if (opts.sourceMaps === "inline") { - result.map = null; - } - - return this.makeResult(result); - }; - - return File; -}(_store2.default); - -exports.default = File; -exports.File = File; -}).call(this,require('_process')) -},{"../../helpers/resolve":13,"../../store":14,"../../util":30,"../internal-plugins/block-hoist":25,"../internal-plugins/shadow-functions":26,"../plugin-pass":28,"./logger":17,"./metadata":18,"./options/option-manager":22,"_process":471,"babel-code-frame":3,"babel-generator":43,"babel-helpers":52,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/object/assign":60,"babel-runtime/core-js/object/create":61,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/inherits":71,"babel-runtime/helpers/possibleConstructorReturn":73,"babel-runtime/helpers/typeof":74,"babel-traverse":79,"babel-types":112,"babylon":116,"convert-source-map":124,"lodash/defaults":420,"path":469,"source-map":484}],17:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _node = require("debug/node"); - -var _node2 = _interopRequireDefault(_node); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var verboseDebug = (0, _node2.default)("babel:verbose"); -var generalDebug = (0, _node2.default)("babel"); - -var seenDeprecatedMessages = []; - -var Logger = function () { - function Logger(file, filename) { - (0, _classCallCheck3.default)(this, Logger); - - this.filename = filename; - this.file = file; - } - - Logger.prototype._buildMessage = function _buildMessage(msg) { - var parts = "[BABEL] " + this.filename; - if (msg) parts += ": " + msg; - return parts; - }; - - Logger.prototype.warn = function warn(msg) { - console.warn(this._buildMessage(msg)); - }; - - Logger.prototype.error = function error(msg) { - var Constructor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error; - - throw new Constructor(this._buildMessage(msg)); - }; - - Logger.prototype.deprecate = function deprecate(msg) { - if (this.file.opts && this.file.opts.suppressDeprecationMessages) return; - - msg = this._buildMessage(msg); - - if (seenDeprecatedMessages.indexOf(msg) >= 0) return; - - seenDeprecatedMessages.push(msg); - - console.error(msg); - }; - - Logger.prototype.verbose = function verbose(msg) { - if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg)); - }; - - Logger.prototype.debug = function debug(msg) { - if (generalDebug.enabled) generalDebug(this._buildMessage(msg)); - }; - - Logger.prototype.deopt = function deopt(node, msg) { - this.debug(msg); - }; - - return Logger; -}(); - -exports.default = Logger; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":70,"debug/node":231}],18:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ImportDeclaration = exports.ModuleDeclaration = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.ExportDeclaration = ExportDeclaration; -exports.Scope = Scope; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var ModuleDeclaration = exports.ModuleDeclaration = { - enter: function enter(path, file) { - var node = path.node; - - if (node.source) { - node.source.value = file.resolveModuleSource(node.source.value); - } - } -}; - -var ImportDeclaration = exports.ImportDeclaration = { - exit: function exit(path, file) { - var node = path.node; - - - var specifiers = []; - var imported = []; - file.metadata.modules.imports.push({ - source: node.source.value, - imported: imported, - specifiers: specifiers - }); - - for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var specifier = _ref; - - var local = specifier.node.local.name; - - if (specifier.isImportDefaultSpecifier()) { - imported.push("default"); - specifiers.push({ - kind: "named", - imported: "default", - local: local - }); - } - - if (specifier.isImportSpecifier()) { - var importedName = specifier.node.imported.name; - imported.push(importedName); - specifiers.push({ - kind: "named", - imported: importedName, - local: local - }); - } - - if (specifier.isImportNamespaceSpecifier()) { - imported.push("*"); - specifiers.push({ - kind: "namespace", - local: local - }); - } - } - } -}; - -function ExportDeclaration(path, file) { - var node = path.node; - - - var source = node.source ? node.source.value : null; - var exports = file.metadata.modules.exports; - - var declar = path.get("declaration"); - if (declar.isStatement()) { - var bindings = declar.getBindingIdentifiers(); - - for (var name in bindings) { - exports.exported.push(name); - exports.specifiers.push({ - kind: "local", - local: name, - exported: path.isExportDefaultDeclaration() ? "default" : name - }); - } - } - - if (path.isExportNamedDeclaration() && node.specifiers) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var specifier = _ref2; - - var exported = specifier.exported.name; - exports.exported.push(exported); - - if (t.isExportDefaultSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external", - local: exported, - exported: exported, - source: source - }); - } - - if (t.isExportNamespaceSpecifier(specifier)) { - exports.specifiers.push({ - kind: "external-namespace", - exported: exported, - source: source - }); - } - - var local = specifier.local; - if (!local) continue; - - if (source) { - exports.specifiers.push({ - kind: "external", - local: local.name, - exported: exported, - source: source - }); - } - - if (!source) { - exports.specifiers.push({ - kind: "local", - local: local.name, - exported: exported - }); - } - } - } - - if (path.isExportAllDeclaration()) { - exports.specifiers.push({ - kind: "external-all", - source: source - }); - } -} - -function Scope(path) { - path.skip(); -} -},{"babel-runtime/core-js/get-iterator":56,"babel-types":112}],19:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -exports.default = buildConfigChain; - -var _resolve = require("../../../helpers/resolve"); - -var _resolve2 = _interopRequireDefault(_resolve); - -var _json = require("json5"); - -var _json2 = _interopRequireDefault(_json); - -var _pathIsAbsolute = require("path-is-absolute"); - -var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -var _fs = require("fs"); - -var _fs2 = _interopRequireDefault(_fs); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var existsCache = {}; -var jsonCache = {}; - -var BABELIGNORE_FILENAME = ".babelignore"; -var BABELRC_FILENAME = ".babelrc"; -var PACKAGE_FILENAME = "package.json"; - -function exists(filename) { - var cached = existsCache[filename]; - if (cached == null) { - return existsCache[filename] = _fs2.default.existsSync(filename); - } else { - return cached; - } -} - -function buildConfigChain() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var log = arguments[1]; - - var filename = opts.filename; - var builder = new ConfigChainBuilder(log); - - if (opts.babelrc !== false) { - builder.findConfigs(filename); - } - - builder.mergeConfig({ - options: opts, - alias: "base", - dirname: filename && _path2.default.dirname(filename) - }); - - return builder.configs; -} - -var ConfigChainBuilder = function () { - function ConfigChainBuilder(log) { - (0, _classCallCheck3.default)(this, ConfigChainBuilder); - - this.resolvedConfigs = []; - this.configs = []; - this.log = log; - } - - ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) { - if (!loc) return; - - if (!(0, _pathIsAbsolute2.default)(loc)) { - loc = _path2.default.join(process.cwd(), loc); - } - - var foundConfig = false; - var foundIgnore = false; - - while (loc !== (loc = _path2.default.dirname(loc))) { - if (!foundConfig) { - var configLoc = _path2.default.join(loc, BABELRC_FILENAME); - if (exists(configLoc)) { - this.addConfig(configLoc); - foundConfig = true; - } - - var pkgLoc = _path2.default.join(loc, PACKAGE_FILENAME); - if (!foundConfig && exists(pkgLoc)) { - foundConfig = this.addConfig(pkgLoc, "babel", JSON); - } - } - - if (!foundIgnore) { - var ignoreLoc = _path2.default.join(loc, BABELIGNORE_FILENAME); - if (exists(ignoreLoc)) { - this.addIgnoreConfig(ignoreLoc); - foundIgnore = true; - } - } - - if (foundIgnore && foundConfig) return; - } - }; - - ConfigChainBuilder.prototype.addIgnoreConfig = function addIgnoreConfig(loc) { - var file = _fs2.default.readFileSync(loc, "utf8"); - var lines = file.split("\n"); - - lines = lines.map(function (line) { - return line.replace(/#(.*?)$/, "").trim(); - }).filter(function (line) { - return !!line; - }); - - if (lines.length) { - this.mergeConfig({ - options: { ignore: lines }, - alias: loc, - dirname: _path2.default.dirname(loc) - }); - } - }; - - ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) { - var json = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _json2.default; - - if (this.resolvedConfigs.indexOf(loc) >= 0) { - return false; - } - - this.resolvedConfigs.push(loc); - - var content = _fs2.default.readFileSync(loc, "utf8"); - var options = void 0; - - try { - options = jsonCache[content] = jsonCache[content] || json.parse(content); - if (key) options = options[key]; - } catch (err) { - err.message = loc + ": Error while parsing JSON - " + err.message; - throw err; - } - - this.mergeConfig({ - options: options, - alias: loc, - dirname: _path2.default.dirname(loc) - }); - - return !!options; - }; - - ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) { - var options = _ref.options, - alias = _ref.alias, - loc = _ref.loc, - dirname = _ref.dirname; - - if (!options) { - return false; - } - - options = (0, _assign2.default)({}, options); - - dirname = dirname || process.cwd(); - loc = loc || alias; - - if (options.extends) { - var extendsLoc = (0, _resolve2.default)(options.extends, dirname); - if (extendsLoc) { - this.addConfig(extendsLoc); - } else { - if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias); - } - delete options.extends; - } - - this.configs.push({ - options: options, - alias: alias, - loc: loc, - dirname: dirname - }); - - var envOpts = void 0; - var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; - if (options.env) { - envOpts = options.env[envKey]; - delete options.env; - } - - this.mergeConfig({ - options: envOpts, - alias: alias + ".env." + envKey, - dirname: dirname - }); - }; - - return ConfigChainBuilder; -}(); - -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../helpers/resolve":13,"_process":471,"babel-runtime/core-js/object/assign":60,"babel-runtime/helpers/classCallCheck":70,"fs":120,"json5":250,"path":469,"path-is-absolute":470}],20:[function(require,module,exports){ -"use strict"; - -module.exports = { - filename: { - type: "filename", - description: "filename to use when reading from stdin - this will be used in source-maps, errors etc", - default: "unknown", - shorthand: "f" - }, - - filenameRelative: { - hidden: true, - type: "string" - }, - - inputSourceMap: { - hidden: true - }, - - env: { - hidden: true, - default: {} - }, - - mode: { - description: "", - hidden: true - }, - - retainLines: { - type: "boolean", - default: false, - description: "retain line numbers - will result in really ugly code" - }, - - highlightCode: { - description: "enable/disable ANSI syntax highlighting of code frames (on by default)", - type: "boolean", - default: true - }, - - suppressDeprecationMessages: { - type: "boolean", - default: false, - hidden: true - }, - - presets: { - type: "list", - description: "", - default: [] - }, - - plugins: { - type: "list", - default: [], - description: "" - }, - - ignore: { - type: "list", - description: "list of glob paths to **not** compile", - default: [] - }, - - only: { - type: "list", - description: "list of glob paths to **only** compile" - }, - - code: { - hidden: true, - default: true, - type: "boolean" - }, - - metadata: { - hidden: true, - default: true, - type: "boolean" - }, - - ast: { - hidden: true, - default: true, - type: "boolean" - }, - - extends: { - type: "string", - hidden: true - }, - - comments: { - type: "boolean", - default: true, - description: "write comments to generated output (true by default)" - }, - - shouldPrintComment: { - hidden: true, - description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored" - }, - - wrapPluginVisitorMethod: { - hidden: true, - description: "optional callback to wrap all visitor methods" - }, - - compact: { - type: "booleanString", - default: "auto", - description: "do not include superfluous whitespace characters and line terminators [true|false|auto]" - }, - - minified: { - type: "boolean", - default: false, - description: "save as much bytes when printing [true|false]" - }, - - sourceMap: { - alias: "sourceMaps", - hidden: true - }, - - sourceMaps: { - type: "booleanString", - description: "[true|false|inline]", - default: false, - shorthand: "s" - }, - - sourceMapTarget: { - type: "string", - description: "set `file` on returned source map" - }, - - sourceFileName: { - type: "string", - description: "set `sources[0]` on returned source map" - }, - - sourceRoot: { - type: "filename", - description: "the root from which all sources are relative" - }, - - babelrc: { - description: "Whether or not to look up .babelrc and .babelignore files", - type: "boolean", - default: true - }, - - sourceType: { - description: "", - default: "module" - }, - - auxiliaryCommentBefore: { - type: "string", - description: "print a comment before any injected non-user code" - }, - - auxiliaryCommentAfter: { - type: "string", - description: "print a comment after any injected non-user code" - }, - - resolveModuleSource: { - hidden: true - }, - - getModuleId: { - hidden: true - }, - - moduleRoot: { - type: "filename", - description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions" - }, - - moduleIds: { - type: "boolean", - default: false, - shorthand: "M", - description: "insert an explicit id for modules" - }, - - moduleId: { - description: "specify a custom name for module ids", - type: "string" - }, - - passPerPreset: { - description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.", - type: "boolean", - default: false, - hidden: true - }, - - parserOpts: { - description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", - default: false - }, - - generatorOpts: { - description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", - default: false - } -}; -},{}],21:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.config = undefined; -exports.normaliseOptions = normaliseOptions; - -var _parsers = require("./parsers"); - -var parsers = _interopRequireWildcard(_parsers); - -var _config = require("./config"); - -var _config2 = _interopRequireDefault(_config); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -exports.config = _config2.default; -function normaliseOptions() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - for (var key in options) { - var val = options[key]; - if (val == null) continue; - - var opt = _config2.default[key]; - if (opt && opt.alias) opt = _config2.default[opt.alias]; - if (!opt) continue; - - var parser = parsers[opt.type]; - if (parser) val = parser(val); - - options[key] = val; - } - - return options; -} -},{"./config":20,"./parsers":23}],22:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _objectWithoutProperties2 = require("babel-runtime/helpers/objectWithoutProperties"); - -var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _node = require("../../../api/node"); - -var context = _interopRequireWildcard(_node); - -var _plugin2 = require("../../plugin"); - -var _plugin3 = _interopRequireDefault(_plugin2); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _index = require("./index"); - -var _resolvePlugin = require("../../../helpers/resolve-plugin"); - -var _resolvePlugin2 = _interopRequireDefault(_resolvePlugin); - -var _resolvePreset = require("../../../helpers/resolve-preset"); - -var _resolvePreset2 = _interopRequireDefault(_resolvePreset); - -var _cloneDeepWith = require("lodash/cloneDeepWith"); - -var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -var _merge = require("../../../helpers/merge"); - -var _merge2 = _interopRequireDefault(_merge); - -var _config2 = require("./config"); - -var _config3 = _interopRequireDefault(_config2); - -var _removed = require("./removed"); - -var _removed2 = _interopRequireDefault(_removed); - -var _buildConfigChain = require("./build-config-chain"); - -var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var OptionManager = function () { - function OptionManager(log) { - (0, _classCallCheck3.default)(this, OptionManager); - - this.resolvedConfigs = []; - this.options = OptionManager.createBareOptions(); - this.log = log; - } - - OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) { - for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var cache = _ref; - - if (cache.container === fn) return cache.plugin; - } - - var obj = void 0; - - if (typeof fn === "function") { - obj = fn(context); - } else { - obj = fn; - } - - if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) === "object") { - var _plugin = new _plugin3.default(obj, alias); - OptionManager.memoisedPlugins.push({ - container: fn, - plugin: _plugin - }); - return _plugin; - } else { - throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i); - } - }; - - OptionManager.createBareOptions = function createBareOptions() { - var opts = {}; - - for (var _key in _config3.default) { - var opt = _config3.default[_key]; - opts[_key] = (0, _clone2.default)(opt.default); - } - - return opts; - }; - - OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) { - plugin = plugin.__esModule ? plugin.default : plugin; - - if (!(plugin instanceof _plugin3.default)) { - if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") { - plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias); - } else { - throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin))); - } - } - - plugin.init(loc, i); - - return plugin; - }; - - OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) { - return plugins.map(function (val, i) { - var plugin = void 0, - options = void 0; - - if (!val) { - throw new TypeError("Falsy value found in plugins"); - } - - if (Array.isArray(val)) { - plugin = val[0]; - options = val[1]; - } else { - plugin = val; - } - - var alias = typeof plugin === "string" ? plugin : loc + "$" + i; - - if (typeof plugin === "string") { - var pluginLoc = (0, _resolvePlugin2.default)(plugin, dirname); - if (pluginLoc) { - plugin = require(pluginLoc); - } else { - throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname)); - } - } - - plugin = OptionManager.normalisePlugin(plugin, loc, i, alias); - - return [plugin, options]; - }); - }; - - OptionManager.prototype.mergeOptions = function mergeOptions(_ref2) { - var _this = this; - - var rawOpts = _ref2.options, - extendingOpts = _ref2.extending, - alias = _ref2.alias, - loc = _ref2.loc, - dirname = _ref2.dirname; - - alias = alias || "foreign"; - if (!rawOpts) return; - - if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) { - this.log.error("Invalid options type for " + alias, TypeError); - } - - var opts = (0, _cloneDeepWith2.default)(rawOpts, function (val) { - if (val instanceof _plugin3.default) { - return val; - } - }); - - dirname = dirname || process.cwd(); - loc = loc || alias; - - for (var _key2 in opts) { - var option = _config3.default[_key2]; - - if (!option && this.log) { - if (_removed2.default[_key2]) { - this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2.default[_key2].message, ReferenceError); - } else { - var unknownOptErr = "Unknown option: " + alias + "." + _key2 + ". Check out http://babeljs.io/docs/usage/options/ for more information about options."; - var presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options."; - - - this.log.error(unknownOptErr + "\n\n" + presetConfigErr, ReferenceError); - } - } - } - - (0, _index.normaliseOptions)(opts); - - if (opts.plugins) { - opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins); - } - - if (opts.presets) { - if (opts.passPerPreset) { - opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) { - _this.mergeOptions({ - options: preset, - extending: preset, - alias: presetLoc, - loc: presetLoc, - dirname: dirname - }); - }); - } else { - this.mergePresets(opts.presets, dirname); - delete opts.presets; - } - } - - if (rawOpts === extendingOpts) { - (0, _assign2.default)(extendingOpts, opts); - } else { - (0, _merge2.default)(extendingOpts || this.options, opts); - } - }; - - OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) { - var _this2 = this; - - this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) { - _this2.mergeOptions({ - options: presetOpts, - alias: presetLoc, - loc: presetLoc, - dirname: _path2.default.dirname(presetLoc || "") - }); - }); - }; - - OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) { - return presets.map(function (val) { - var options = void 0; - if (Array.isArray(val)) { - if (val.length > 2) { - throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset."); - } - - var _val = val; - val = _val[0]; - options = _val[1]; - } - - var presetLoc = void 0; - try { - if (typeof val === "string") { - presetLoc = (0, _resolvePreset2.default)(val, dirname); - - if (!presetLoc) { - throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname)); - } - - val = require(presetLoc); - } - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) { - if (val.default) { - val = val.default; - } else { - var _val2 = val, - __esModule = _val2.__esModule, - rest = (0, _objectWithoutProperties3.default)(_val2, ["__esModule"]); - - val = rest; - } - } - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset; - - if (typeof val !== "function" && options !== undefined) { - throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options."); - } - - if (typeof val === "function") val = val(context, options); - - if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") { - throw new Error("Unsupported preset format: " + val + "."); - } - - onResolve && onResolve(val, presetLoc); - } catch (e) { - if (presetLoc) { - e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")"; - } - throw e; - } - return val; - }); - }; - - OptionManager.prototype.normaliseOptions = function normaliseOptions() { - var opts = this.options; - - for (var _key3 in _config3.default) { - var option = _config3.default[_key3]; - var val = opts[_key3]; - - if (!val && option.optional) continue; - - if (option.alias) { - opts[option.alias] = opts[option.alias] || val; - } else { - opts[_key3] = val; - } - } - }; - - OptionManager.prototype.init = function init() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - var _config = _ref3; - - this.mergeOptions(_config); - } - - this.normaliseOptions(opts); - - return this.options; - }; - - return OptionManager; -}(); - -exports.default = OptionManager; - - -OptionManager.memoisedPlugins = []; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"../../../api/node":5,"../../../helpers/merge":8,"../../../helpers/resolve-plugin":11,"../../../helpers/resolve-preset":12,"../../plugin":29,"./build-config-chain":19,"./config":20,"./index":21,"./removed":24,"_process":471,"babel-messages":53,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/json/stringify":57,"babel-runtime/core-js/object/assign":60,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/objectWithoutProperties":72,"babel-runtime/helpers/typeof":74,"lodash/clone":416,"lodash/cloneDeepWith":418,"path":469}],23:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.filename = undefined; -exports.boolean = boolean; -exports.booleanString = booleanString; -exports.list = list; - -var _slash = require("slash"); - -var _slash2 = _interopRequireDefault(_slash); - -var _util = require("../../../util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var filename = exports.filename = _slash2.default; - -function boolean(val) { - return !!val; -} - -function booleanString(val) { - return util.booleanify(val); -} - -function list(val) { - return util.list(val); -} -},{"../../../util":30,"slash":473}],24:[function(require,module,exports){ -"use strict"; - -module.exports = { - "auxiliaryComment": { - "message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" - }, - "blacklist": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "breakConfig": { - "message": "This is not a necessary option in Babel 6" - }, - "experimental": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "externalHelpers": { - "message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/" - }, - "extra": { - "message": "" - }, - "jsxPragma": { - "message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/" - }, - - "loose": { - "message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option." - }, - "metadataUsedHelpers": { - "message": "Not required anymore as this is enabled by default" - }, - "modules": { - "message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules" - }, - "nonStandard": { - "message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" - }, - "optional": { - "message": "Put the specific transforms you want in the `plugins` option" - }, - "sourceMapName": { - "message": "Use the `sourceMapTarget` option" - }, - "stage": { - "message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" - }, - "whitelist": { - "message": "Put the specific transforms you want in the `plugins` option" - } -}; -},{}],25:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _plugin = require("../plugin"); - -var _plugin2 = _interopRequireDefault(_plugin); - -var _sortBy = require("lodash/sortBy"); - -var _sortBy2 = _interopRequireDefault(_sortBy); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = new _plugin2.default({ - - name: "internal.blockHoist", - - visitor: { - Block: { - exit: function exit(_ref) { - var node = _ref.node; - - var hasChange = false; - for (var i = 0; i < node.body.length; i++) { - var bodyNode = node.body[i]; - if (bodyNode && bodyNode._blockHoist != null) { - hasChange = true; - break; - } - } - if (!hasChange) return; - - node.body = (0, _sortBy2.default)(node.body, function (bodyNode) { - var priority = bodyNode && bodyNode._blockHoist; - if (priority == null) priority = 1; - if (priority === true) priority = 2; - - return -1 * priority; - }); - } - } - } -}); -module.exports = exports["default"]; -},{"../plugin":29,"lodash/sortBy":455}],26:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _plugin = require("../plugin"); - -var _plugin2 = _interopRequireDefault(_plugin); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound"); - -var superVisitor = { - CallExpression: function CallExpression(path) { - if (!path.get("callee").isSuper()) return; - - var node = path.node; - - if (node[SUPER_THIS_BOUND]) return; - node[SUPER_THIS_BOUND] = true; - - path.replaceWith(t.assignmentExpression("=", this.id, node)); - } -}; - -exports.default = new _plugin2.default({ - name: "internal.shadowFunctions", - - visitor: { - ThisExpression: function ThisExpression(path) { - remap(path, "this"); - }, - ReferencedIdentifier: function ReferencedIdentifier(path) { - if (path.node.name === "arguments") { - remap(path, "arguments"); - } - } - } -}); - - -function shouldShadow(path, shadowPath) { - if (path.is("_forceShadow")) { - return true; - } else { - return shadowPath; - } -} - -function remap(path, key) { - var shadowPath = path.inShadow(key); - if (!shouldShadow(path, shadowPath)) return; - - var shadowFunction = path.node._shadowedFunctionLiteral; - - var currentFunction = void 0; - var passedShadowFunction = false; - - var fnPath = path.find(function (innerPath) { - if (innerPath.parentPath && innerPath.parentPath.isClassProperty() && innerPath.key === "value") { - return true; - } - if (path === innerPath) return false; - if (innerPath.isProgram() || innerPath.isFunction()) { - currentFunction = currentFunction || innerPath; - } - - if (innerPath.isProgram()) { - passedShadowFunction = true; - - return true; - } else if (innerPath.isFunction() && !innerPath.isArrowFunctionExpression()) { - if (shadowFunction) { - if (innerPath === shadowFunction || innerPath.node === shadowFunction.node) return true; - } else { - if (!innerPath.is("shadow")) return true; - } - - passedShadowFunction = true; - return false; - } - - return false; - }); - - if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) { - fnPath = path.findParent(function (p) { - return p.isProgram() || p.isFunction(); - }); - } - - if (fnPath === currentFunction) return; - - if (!passedShadowFunction) return; - - var cached = fnPath.getData(key); - if (cached) return path.replaceWith(cached); - - var id = path.scope.generateUidIdentifier(key); - - fnPath.setData(key, id); - - var classPath = fnPath.findParent(function (p) { - return p.isClass(); - }); - var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); - - if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) { - fnPath.scope.push({ id: id }); - - fnPath.traverse(superVisitor, { id: id }); - } else { - var init = key === "this" ? t.thisExpression() : t.identifier(key); - - if (shadowFunction) init._shadowedFunctionLiteral = shadowFunction; - - fnPath.scope.push({ id: id, init: init }); - } - - return path.replaceWith(id); -} -module.exports = exports["default"]; -},{"../plugin":29,"babel-runtime/core-js/symbol":65,"babel-types":112}],27:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _normalizeAst = require("../helpers/normalize-ast"); - -var _normalizeAst2 = _interopRequireDefault(_normalizeAst); - -var _plugin = require("./plugin"); - -var _plugin2 = _interopRequireDefault(_plugin); - -var _file = require("./file"); - -var _file2 = _interopRequireDefault(_file); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Pipeline = function () { - function Pipeline() { - (0, _classCallCheck3.default)(this, Pipeline); - } - - Pipeline.prototype.lint = function lint(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - opts.code = false; - opts.mode = "lint"; - return this.transform(code, opts); - }; - - Pipeline.prototype.pretransform = function pretransform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file; - }); - }; - - Pipeline.prototype.transform = function transform(code, opts) { - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.parseCode(code); - return file.transform(); - }); - }; - - Pipeline.prototype.analyse = function analyse(code) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var visitor = arguments[2]; - - opts.code = false; - if (visitor) { - opts.plugins = opts.plugins || []; - opts.plugins.push(new _plugin2.default({ visitor: visitor })); - } - return this.transform(code, opts).metadata; - }; - - Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) { - ast = (0, _normalizeAst2.default)(ast); - - var file = new _file2.default(opts, this); - return file.wrap(code, function () { - file.addCode(code); - file.addAst(ast); - return file.transform(); - }); - }; - - return Pipeline; -}(); - -exports.default = Pipeline; -module.exports = exports["default"]; -},{"../helpers/normalize-ast":9,"./file":16,"./plugin":29,"babel-runtime/helpers/classCallCheck":70}],28:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _store = require("../store"); - -var _store2 = _interopRequireDefault(_store); - -var _file5 = require("./file"); - -var _file6 = _interopRequireDefault(_file5); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var PluginPass = function (_Store) { - (0, _inherits3.default)(PluginPass, _Store); - - function PluginPass(file, plugin) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - (0, _classCallCheck3.default)(this, PluginPass); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.plugin = plugin; - _this.key = plugin.key; - _this.file = file; - _this.opts = options; - return _this; - } - - PluginPass.prototype.addHelper = function addHelper() { - var _file; - - return (_file = this.file).addHelper.apply(_file, arguments); - }; - - PluginPass.prototype.addImport = function addImport() { - var _file2; - - return (_file2 = this.file).addImport.apply(_file2, arguments); - }; - - PluginPass.prototype.getModuleName = function getModuleName() { - var _file3; - - return (_file3 = this.file).getModuleName.apply(_file3, arguments); - }; - - PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() { - var _file4; - - return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments); - }; - - return PluginPass; -}(_store2.default); - -exports.default = PluginPass; -module.exports = exports["default"]; -},{"../store":14,"./file":16,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/inherits":71,"babel-runtime/helpers/possibleConstructorReturn":73}],29:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -var _optionManager = require("./file/options/option-manager"); - -var _optionManager2 = _interopRequireDefault(_optionManager); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _store = require("../store"); - -var _store2 = _interopRequireDefault(_store); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _assign = require("lodash/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var GLOBAL_VISITOR_PROPS = ["enter", "exit"]; - -var Plugin = function (_Store) { - (0, _inherits3.default)(Plugin, _Store); - - function Plugin(plugin, key) { - (0, _classCallCheck3.default)(this, Plugin); - - var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); - - _this.initialized = false; - _this.raw = (0, _assign2.default)({}, plugin); - _this.key = _this.take("name") || key; - - _this.manipulateOptions = _this.take("manipulateOptions"); - _this.post = _this.take("post"); - _this.pre = _this.take("pre"); - _this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {}); - return _this; - } - - Plugin.prototype.take = function take(key) { - var val = this.raw[key]; - delete this.raw[key]; - return val; - }; - - Plugin.prototype.chain = function chain(target, key) { - if (!target[key]) return this[key]; - if (!this[key]) return target[key]; - - var fns = [target[key], this[key]]; - - return function () { - var val = void 0; - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var fn = _ref; - - if (fn) { - var ret = fn.apply(this, args); - if (ret != null) val = ret; - } - } - return val; - }; - }; - - Plugin.prototype.maybeInherit = function maybeInherit(loc) { - var inherits = this.take("inherits"); - if (!inherits) return; - - inherits = _optionManager2.default.normalisePlugin(inherits, loc, "inherits"); - - this.manipulateOptions = this.chain(inherits, "manipulateOptions"); - this.post = this.chain(inherits, "post"); - this.pre = this.chain(inherits, "pre"); - this.visitor = _babelTraverse2.default.visitors.merge([inherits.visitor, this.visitor]); - }; - - Plugin.prototype.init = function init(loc, i) { - if (this.initialized) return; - this.initialized = true; - - this.maybeInherit(loc); - - for (var key in this.raw) { - throw new Error(messages.get("pluginInvalidProperty", loc, i, key)); - } - }; - - Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) { - for (var _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var key = _ref2; - - if (visitor[key]) { - throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. " + "Please target individual nodes."); - } - } - - _babelTraverse2.default.explode(visitor); - return visitor; - }; - - return Plugin; -}(_store2.default); - -exports.default = Plugin; -module.exports = exports["default"]; -},{"../store":14,"./file/options/option-manager":22,"babel-messages":53,"babel-runtime/core-js/get-iterator":56,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/inherits":71,"babel-runtime/helpers/possibleConstructorReturn":73,"babel-traverse":79,"lodash/assign":414,"lodash/clone":416}],30:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.inspect = exports.inherits = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _util = require("util"); - -Object.defineProperty(exports, "inherits", { - enumerable: true, - get: function get() { - return _util.inherits; - } -}); -Object.defineProperty(exports, "inspect", { - enumerable: true, - get: function get() { - return _util.inspect; - } -}); -exports.canCompile = canCompile; -exports.list = list; -exports.regexify = regexify; -exports.arrayify = arrayify; -exports.booleanify = booleanify; -exports.shouldIgnore = shouldIgnore; - -var _escapeRegExp = require("lodash/escapeRegExp"); - -var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp); - -var _startsWith = require("lodash/startsWith"); - -var _startsWith2 = _interopRequireDefault(_startsWith); - -var _minimatch = require("minimatch"); - -var _minimatch2 = _interopRequireDefault(_minimatch); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _isRegExp = require("lodash/isRegExp"); - -var _isRegExp2 = _interopRequireDefault(_isRegExp); - -var _path = require("path"); - -var _path2 = _interopRequireDefault(_path); - -var _slash = require("slash"); - -var _slash2 = _interopRequireDefault(_slash); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function canCompile(filename, altExts) { - var exts = altExts || canCompile.EXTENSIONS; - var ext = _path2.default.extname(filename); - return (0, _includes2.default)(exts, ext); -} - -canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"]; - -function list(val) { - if (!val) { - return []; - } else if (Array.isArray(val)) { - return val; - } else if (typeof val === "string") { - return val.split(","); - } else { - return [val]; - } -} - -function regexify(val) { - if (!val) { - return new RegExp(/.^/); - } - - if (Array.isArray(val)) { - val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i"); - } - - if (typeof val === "string") { - val = (0, _slash2.default)(val); - - if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2); - if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3); - - var regex = _minimatch2.default.makeRe(val, { nocase: true }); - return new RegExp(regex.source.slice(1, -1), "i"); - } - - if ((0, _isRegExp2.default)(val)) { - return val; - } - - throw new TypeError("illegal type for regexify"); -} - -function arrayify(val, mapFn) { - if (!val) return []; - if (typeof val === "boolean") return arrayify([val], mapFn); - if (typeof val === "string") return arrayify(list(val), mapFn); - - if (Array.isArray(val)) { - if (mapFn) val = val.map(mapFn); - return val; - } - - return [val]; -} - -function booleanify(val) { - if (val === "true" || val == 1) { - return true; - } - - if (val === "false" || val == 0 || !val) { - return false; - } - - return val; -} - -function shouldIgnore(filename) { - var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var only = arguments[2]; - - filename = filename.replace(/\\/g, "/"); - - if (only) { - for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var pattern = _ref; - - if (_shouldIgnore(pattern, filename)) return false; - } - return true; - } else if (ignore.length) { - for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _pattern = _ref2; - - if (_shouldIgnore(_pattern, filename)) return true; - } - } - - return false; -} - -function _shouldIgnore(pattern, filename) { - if (typeof pattern === "function") { - return pattern(filename); - } else { - return pattern.test(filename); - } -} -},{"babel-runtime/core-js/get-iterator":56,"lodash/escapeRegExp":422,"lodash/includes":431,"lodash/isRegExp":443,"lodash/startsWith":456,"minimatch":466,"path":469,"slash":473,"util":492}],31:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "babel-core@^6.22.1", - "scope": null, - "escapedName": "babel-core", - "name": "babel-core", - "rawSpec": "^6.22.1", - "spec": ">=6.22.1 <7.0.0", - "type": "range" - }, - "/home/directxman12/dev/noVNC" - ] - ], - "_from": "babel-core@>=6.22.1 <7.0.0", - "_id": "babel-core@6.23.1", - "_inCache": true, - "_location": "/babel-core", - "_nodeVersion": "6.9.1", - "_npmOperationalInternal": { - "host": "packages-12-west.internal.npmjs.com", - "tmp": "tmp/babel-core-6.23.1.tgz_1487038699717_0.8698694983031601" - }, - "_npmUser": { - "name": "loganfsmyth", - "email": "loganfsmyth@gmail.com" - }, - "_npmVersion": "3.10.8", - "_phantomChildren": {}, - "_requested": { - "raw": "babel-core@^6.22.1", - "scope": null, - "escapedName": "babel-core", - "name": "babel-core", - "rawSpec": "^6.22.1", - "spec": ">=6.22.1 <7.0.0", - "type": "range" - }, - "_requiredBy": [ - "#DEV:/", - "/babel-register", - "/babelify", - "/karma-babel-preprocessor" - ], - "_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.23.1.tgz", - "_shasum": "c143cb621bb2f621710c220c5d579d15b8a442df", - "_shrinkwrap": null, - "_spec": "babel-core@^6.22.1", - "_where": "/home/directxman12/dev/noVNC", - "author": { - "name": "Sebastian McKenzie", - "email": "sebmck@gmail.com" - }, - "dependencies": { - "babel-code-frame": "^6.22.0", - "babel-generator": "^6.23.0", - "babel-helpers": "^6.23.0", - "babel-messages": "^6.23.0", - "babel-register": "^6.23.0", - "babel-runtime": "^6.22.0", - "babel-template": "^6.23.0", - "babel-traverse": "^6.23.1", - "babel-types": "^6.23.0", - "babylon": "^6.11.0", - "convert-source-map": "^1.1.0", - "debug": "^2.1.1", - "json5": "^0.5.0", - "lodash": "^4.2.0", - "minimatch": "^3.0.2", - "path-is-absolute": "^1.0.0", - "private": "^0.1.6", - "slash": "^1.0.0", - "source-map": "^0.5.0" - }, - "description": "Babel compiler core.", - "devDependencies": { - "babel-helper-fixtures": "^6.22.0", - "babel-helper-transform-fixture-test-runner": "^6.23.0", - "babel-polyfill": "^6.23.0" - }, - "directories": {}, - "dist": { - "shasum": "c143cb621bb2f621710c220c5d579d15b8a442df", - "tarball": "https://registry.npmjs.org/babel-core/-/babel-core-6.23.1.tgz" - }, - "homepage": "https://babeljs.io/", - "keywords": [ - "6to5", - "babel", - "classes", - "const", - "es6", - "harmony", - "let", - "modules", - "transpile", - "transpiler", - "var", - "babel-core", - "compiler" - ], - "license": "MIT", - "maintainers": [ - { - "name": "amasad", - "email": "amjad.masad@gmail.com" - }, - { - "name": "hzoo", - "email": "hi@henryzoo.com" - }, - { - "name": "jmm", - "email": "npm-public@jessemccarthy.net" - }, - { - "name": "loganfsmyth", - "email": "loganfsmyth@gmail.com" - }, - { - "name": "sebmck", - "email": "sebmck@gmail.com" - }, - { - "name": "thejameskyle", - "email": "me@thejameskyle.com" - } - ], - "name": "babel-core", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "https://github.com/babel/babel/tree/master/packages/babel-core" - }, - "scripts": { - "bench": "make bench", - "test": "make test" - }, - "version": "6.23.1" -} - -},{}],32:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _trimRight = require("trim-right"); - -var _trimRight2 = _interopRequireDefault(_trimRight); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SPACES_RE = /^[ \t]+$/; - -var Buffer = function () { - function Buffer(map) { - (0, _classCallCheck3.default)(this, Buffer); - this._map = null; - this._buf = []; - this._last = ""; - this._queue = []; - this._position = { - line: 1, - column: 0 - }; - this._sourcePosition = { - identifierName: null, - line: null, - column: null, - filename: null - }; - - this._map = map; - } - - Buffer.prototype.get = function get() { - this._flush(); - - var map = this._map; - var result = { - code: (0, _trimRight2.default)(this._buf.join("")), - map: null, - rawMappings: map && map.getRawMappings() - }; - - if (map) { - Object.defineProperty(result, "map", { - configurable: true, - enumerable: true, - get: function get() { - return this.map = map.get(); - }, - set: function set(value) { - Object.defineProperty(this, "map", { value: value, writable: true }); - } - }); - } - - return result; - }; - - Buffer.prototype.append = function append(str) { - this._flush(); - var _sourcePosition = this._sourcePosition, - line = _sourcePosition.line, - column = _sourcePosition.column, - filename = _sourcePosition.filename, - identifierName = _sourcePosition.identifierName; - - this._append(str, line, column, identifierName, filename); - }; - - Buffer.prototype.queue = function queue(str) { - if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { - this._queue.shift(); - }var _sourcePosition2 = this._sourcePosition, - line = _sourcePosition2.line, - column = _sourcePosition2.column, - filename = _sourcePosition2.filename, - identifierName = _sourcePosition2.identifierName; - - this._queue.unshift([str, line, column, identifierName, filename]); - }; - - Buffer.prototype._flush = function _flush() { - var item = void 0; - while (item = this._queue.pop()) { - this._append.apply(this, item); - } - }; - - Buffer.prototype._append = function _append(str, line, column, identifierName, filename) { - if (this._map && str[0] !== "\n") { - this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename); - } - - this._buf.push(str); - this._last = str[str.length - 1]; - - for (var i = 0; i < str.length; i++) { - if (str[i] === "\n") { - this._position.line++; - this._position.column = 0; - } else { - this._position.column++; - } - } - }; - - Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() { - if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift(); - }; - - Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() { - if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift(); - }; - - Buffer.prototype.endsWith = function endsWith(suffix) { - if (suffix.length === 1) { - var last = void 0; - if (this._queue.length > 0) { - var str = this._queue[0][0]; - last = str[str.length - 1]; - } else { - last = this._last; - } - - return last === suffix; - } - - var end = this._last + this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - if (suffix.length <= end.length) { - return end.slice(-suffix.length) === suffix; - } - - return false; - }; - - Buffer.prototype.hasContent = function hasContent() { - return this._queue.length > 0 || !!this._last; - }; - - Buffer.prototype.source = function source(prop, loc) { - if (prop && !loc) return; - - var pos = loc ? loc[prop] : null; - - this._sourcePosition.identifierName = loc && loc.identifierName || null; - this._sourcePosition.line = pos ? pos.line : null; - this._sourcePosition.column = pos ? pos.column : null; - this._sourcePosition.filename = loc && loc.filename || null; - }; - - Buffer.prototype.withSource = function withSource(prop, loc, cb) { - if (!this._map) return cb(); - - var originalLine = this._sourcePosition.line; - var originalColumn = this._sourcePosition.column; - var originalFilename = this._sourcePosition.filename; - var originalIdentifierName = this._sourcePosition.identifierName; - - this.source(prop, loc); - - cb(); - - this._sourcePosition.line = originalLine; - this._sourcePosition.column = originalColumn; - this._sourcePosition.filename = originalFilename; - this._sourcePosition.identifierName = originalIdentifierName; - }; - - Buffer.prototype.getCurrentColumn = function getCurrentColumn() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - var lastIndex = extra.lastIndexOf("\n"); - - return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; - }; - - Buffer.prototype.getCurrentLine = function getCurrentLine() { - var extra = this._queue.reduce(function (acc, item) { - return item[0] + acc; - }, ""); - - var count = 0; - for (var i = 0; i < extra.length; i++) { - if (extra[i] === "\n") count++; - } - - return this._position.line + count; - }; - - return Buffer; -}(); - -exports.default = Buffer; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":70,"trim-right":488}],33:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.File = File; -exports.Program = Program; -exports.BlockStatement = BlockStatement; -exports.Noop = Noop; -exports.Directive = Directive; - -var _types = require("./types"); - -Object.defineProperty(exports, "DirectiveLiteral", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -function File(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) { - this.token("{"); - this.printInnerComments(node); - - var hasDirectives = node.directives && 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("\n")) this.newline(); - - this.rightBrace(); - } else { - this.source("end", node.loc); - this.token("}"); - } -} - -function Noop() {} - -function Directive(node) { - this.print(node.value, node); - this.semicolon(); -} -},{"./types":42}],34:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ClassDeclaration = ClassDeclaration; -exports.ClassBody = ClassBody; -exports.ClassProperty = ClassProperty; -exports.ClassMethod = ClassMethod; -function ClassDeclaration(node) { - this.printJoin(node.decorators, node); - this.word("class"); - - 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); -} - -exports.ClassExpression = ClassDeclaration; -function ClassBody(node) { - this.token("{"); - this.printInnerComments(node); - if (node.body.length === 0) { - this.token("}"); - } else { - this.newline(); - - this.indent(); - this.printSequence(node.body, node); - this.dedent(); - - if (!this.endsWith("\n")) this.newline(); - - this.rightBrace(); - } -} - -function ClassProperty(node) { - this.printJoin(node.decorators, node); - - if (node.static) { - this.word("static"); - this.space(); - } - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - this._variance(node); - this.print(node.key, node); - } - this.print(node.typeAnnotation, node); - if (node.value) { - this.space(); - this.token("="); - this.space(); - this.print(node.value, node); - } - this.semicolon(); -} - -function ClassMethod(node) { - this.printJoin(node.decorators, node); - - if (node.static) { - this.word("static"); - this.space(); - } - - if (node.kind === "constructorCall") { - this.word("call"); - this.space(); - } - - this._method(node); -} -},{}],35:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined; -exports.UnaryExpression = UnaryExpression; -exports.DoExpression = DoExpression; -exports.ParenthesizedExpression = ParenthesizedExpression; -exports.UpdateExpression = UpdateExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.NewExpression = NewExpression; -exports.SequenceExpression = SequenceExpression; -exports.ThisExpression = ThisExpression; -exports.Super = Super; -exports.Decorator = Decorator; -exports.CallExpression = CallExpression; -exports.Import = Import; -exports.EmptyStatement = EmptyStatement; -exports.ExpressionStatement = ExpressionStatement; -exports.AssignmentPattern = AssignmentPattern; -exports.AssignmentExpression = AssignmentExpression; -exports.BindExpression = BindExpression; -exports.MemberExpression = MemberExpression; -exports.MetaProperty = MetaProperty; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _node = require("../node"); - -var n = _interopRequireWildcard(_node); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function UnaryExpression(node) { - if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") { - this.word(node.operator); - this.space(); - } else { - this.token(node.operator); - } - - this.print(node.argument, node); -} - -function DoExpression(node) { - this.word("do"); - this.space(); - this.print(node.body, node); -} - -function ParenthesizedExpression(node) { - this.token("("); - this.print(node.expression, node); - this.token(")"); -} - -function UpdateExpression(node) { - if (node.prefix) { - this.token(node.operator); - this.print(node.argument, node); - } else { - this.print(node.argument, node); - this.token(node.operator); - } -} - -function ConditionalExpression(node) { - this.print(node.test, node); - this.space(); - this.token("?"); - this.space(); - this.print(node.consequent, node); - this.space(); - this.token(":"); - this.space(); - this.print(node.alternate, node); -} - -function NewExpression(node, parent) { - this.word("new"); - this.space(); - this.print(node.callee, node); - if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return; - - this.token("("); - this.printList(node.arguments, node); - this.token(")"); -} - -function SequenceExpression(node) { - this.printList(node.expressions, node); -} - -function ThisExpression() { - this.word("this"); -} - -function Super() { - this.word("super"); -} - -function Decorator(node) { - this.token("@"); - this.print(node.expression, node); - this.newline(); -} - -function commaSeparatorNewline() { - this.token(","); - this.newline(); - - if (!this.endsWith("\n")) this.space(); -} - -function CallExpression(node) { - this.print(node.callee, node); - - this.token("("); - - var isPrettyCall = node._prettyCall; - - var separator = void 0; - if (isPrettyCall) { - separator = commaSeparatorNewline; - this.newline(); - this.indent(); - } - - this.printList(node.arguments, node, { separator: separator }); - - if (isPrettyCall) { - this.newline(); - this.dedent(); - } - - this.token(")"); -} - -function Import() { - this.word("import"); -} - -function buildYieldAwait(keyword) { - return function (node) { - this.word(keyword); - - if (node.delegate) { - this.token("*"); - } - - if (node.argument) { - this.space(); - var terminatorState = this.startTerminatorless(); - this.print(node.argument, node); - this.endTerminatorless(terminatorState); - } - }; -} - -var YieldExpression = exports.YieldExpression = buildYieldAwait("yield"); -var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await"); - -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.token("?"); - this.print(node.left.typeAnnotation, node); - this.space(); - this.token("="); - this.space(); - this.print(node.right, node); -} - -function AssignmentExpression(node, parent) { - var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); - - if (parens) { - this.token("("); - } - - 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.token(")"); - } -} - -function BindExpression(node) { - this.print(node.object, node); - this.token("::"); - this.print(node.callee, node); -} - -exports.BinaryExpression = AssignmentExpression; -exports.LogicalExpression = AssignmentExpression; -function MemberExpression(node) { - this.print(node.object, node); - - if (!node.computed && t.isMemberExpression(node.property)) { - throw new TypeError("Got a MemberExpression for MemberExpression property"); - } - - var computed = node.computed; - if (t.isLiteral(node.property) && typeof node.property.value === "number") { - computed = true; - } - - if (computed) { - this.token("["); - this.print(node.property, node); - this.token("]"); - } else { - this.token("."); - this.print(node.property, node); - } -} - -function MetaProperty(node) { - this.print(node.meta, node); - this.token("."); - this.print(node.property, node); -} -},{"../node":44,"babel-types":112}],36:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.AnyTypeAnnotation = AnyTypeAnnotation; -exports.ArrayTypeAnnotation = ArrayTypeAnnotation; -exports.BooleanTypeAnnotation = BooleanTypeAnnotation; -exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; -exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; -exports.DeclareClass = DeclareClass; -exports.DeclareFunction = DeclareFunction; -exports.DeclareInterface = DeclareInterface; -exports.DeclareModule = DeclareModule; -exports.DeclareModuleExports = DeclareModuleExports; -exports.DeclareTypeAlias = DeclareTypeAlias; -exports.DeclareVariable = DeclareVariable; -exports.ExistentialTypeParam = ExistentialTypeParam; -exports.FunctionTypeAnnotation = FunctionTypeAnnotation; -exports.FunctionTypeParam = FunctionTypeParam; -exports.InterfaceExtends = InterfaceExtends; -exports._interfaceish = _interfaceish; -exports._variance = _variance; -exports.InterfaceDeclaration = InterfaceDeclaration; -exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; -exports.MixedTypeAnnotation = MixedTypeAnnotation; -exports.EmptyTypeAnnotation = EmptyTypeAnnotation; -exports.NullableTypeAnnotation = NullableTypeAnnotation; - -var _types = require("./types"); - -Object.defineProperty(exports, "NumericLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.NumericLiteral; - } -}); -Object.defineProperty(exports, "StringLiteralTypeAnnotation", { - enumerable: true, - get: function get() { - return _types.StringLiteral; - } -}); -exports.NumberTypeAnnotation = NumberTypeAnnotation; -exports.StringTypeAnnotation = StringTypeAnnotation; -exports.ThisTypeAnnotation = ThisTypeAnnotation; -exports.TupleTypeAnnotation = TupleTypeAnnotation; -exports.TypeofTypeAnnotation = TypeofTypeAnnotation; -exports.TypeAlias = TypeAlias; -exports.TypeAnnotation = TypeAnnotation; -exports.TypeParameter = TypeParameter; -exports.TypeParameterInstantiation = TypeParameterInstantiation; -exports.ObjectTypeAnnotation = ObjectTypeAnnotation; -exports.ObjectTypeCallProperty = ObjectTypeCallProperty; -exports.ObjectTypeIndexer = ObjectTypeIndexer; -exports.ObjectTypeProperty = ObjectTypeProperty; -exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; -exports.UnionTypeAnnotation = UnionTypeAnnotation; -exports.TypeCastExpression = TypeCastExpression; -exports.VoidTypeAnnotation = VoidTypeAnnotation; -function AnyTypeAnnotation() { - this.word("any"); -} - -function ArrayTypeAnnotation(node) { - this.print(node.elementType, node); - this.token("["); - this.token("]"); -} - -function BooleanTypeAnnotation() { - this.word("boolean"); -} - -function BooleanLiteralTypeAnnotation(node) { - this.word(node.value ? "true" : "false"); -} - -function NullLiteralTypeAnnotation() { - this.word("null"); -} - -function DeclareClass(node) { - this.word("declare"); - this.space(); - this.word("class"); - this.space(); - this._interfaceish(node); -} - -function DeclareFunction(node) { - this.word("declare"); - this.space(); - this.word("function"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation.typeAnnotation, node); - this.semicolon(); -} - -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.token("."); - this.word("exports"); - this.print(node.typeAnnotation, node); -} - -function DeclareTypeAlias(node) { - this.word("declare"); - this.space(); - this.TypeAlias(node); -} - -function DeclareVariable(node) { - this.word("declare"); - this.space(); - this.word("var"); - this.space(); - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - this.semicolon(); -} - -function ExistentialTypeParam() { - this.token("*"); -} - -function FunctionTypeAnnotation(node, parent) { - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node); - - if (node.rest) { - if (node.params.length) { - this.token(","); - this.space(); - } - this.token("..."); - this.print(node.rest, node); - } - - this.token(")"); - - if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { - this.token(":"); - } else { - this.space(); - this.token("=>"); - } - - this.space(); - this.print(node.returnType, node); -} - -function FunctionTypeParam(node) { - this.print(node.name, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.typeAnnotation, node); -} - -function InterfaceExtends(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); -} - -exports.ClassImplements = InterfaceExtends; -exports.GenericTypeAnnotation = InterfaceExtends; -function _interfaceish(node) { - this.print(node.id, node); - this.print(node.typeParameters, node); - if (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); - } - this.space(); - this.print(node.body, node); -} - -function _variance(node) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } -} - -function InterfaceDeclaration(node) { - this.word("interface"); - this.space(); - this._interfaceish(node); -} - -function andSeparator() { - this.space(); - this.token("&"); - this.space(); -} - -function IntersectionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: andSeparator }); -} - -function MixedTypeAnnotation() { - this.word("mixed"); -} - -function EmptyTypeAnnotation() { - this.word("empty"); -} - -function NullableTypeAnnotation(node) { - this.token("?"); - this.print(node.typeAnnotation, node); -} - -function NumberTypeAnnotation() { - this.word("number"); -} - -function StringTypeAnnotation() { - this.word("string"); -} - -function ThisTypeAnnotation() { - this.word("this"); -} - -function TupleTypeAnnotation(node) { - this.token("["); - this.printList(node.types, node); - this.token("]"); -} - -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.token("="); - this.space(); - this.print(node.right, node); - this.semicolon(); -} - -function TypeAnnotation(node) { - this.token(":"); - this.space(); - if (node.optional) this.token("?"); - this.print(node.typeAnnotation, node); -} - -function TypeParameter(node) { - this._variance(node); - - this.word(node.name); - - if (node.bound) { - this.print(node.bound, node); - } - - if (node.default) { - this.space(); - this.token("="); - this.space(); - this.print(node.default, node); - } -} - -function TypeParameterInstantiation(node) { - this.token("<"); - this.printList(node.params, node, {}); - this.token(">"); -} - -exports.TypeParameterDeclaration = TypeParameterInstantiation; -function ObjectTypeAnnotation(node) { - var _this = this; - - if (node.exact) { - this.token("{|"); - } else { - this.token("{"); - } - - var props = node.properties.concat(node.callProperties, node.indexers); - - if (props.length) { - this.space(); - - this.printJoin(props, node, { - addNewlines: function addNewlines(leading) { - if (leading && !props[0]) return 1; - }, - - indent: true, - statement: true, - iterator: function iterator() { - if (props.length !== 1) { - if (_this.format.flowCommaSeparator) { - _this.token(","); - } else { - _this.semicolon(); - } - _this.space(); - } - } - }); - - this.space(); - } - - if (node.exact) { - this.token("|}"); - } else { - this.token("}"); - } -} - -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.token("["); - this.print(node.id, node); - this.token(":"); - this.space(); - this.print(node.key, node); - this.token("]"); - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ObjectTypeProperty(node) { - if (node.static) { - this.word("static"); - this.space(); - } - this._variance(node); - this.print(node.key, node); - if (node.optional) this.token("?"); - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function QualifiedTypeIdentifier(node) { - this.print(node.qualification, node); - this.token("."); - this.print(node.id, node); -} - -function orSeparator() { - this.space(); - this.token("|"); - this.space(); -} - -function UnionTypeAnnotation(node) { - this.printJoin(node.types, node, { separator: orSeparator }); -} - -function TypeCastExpression(node) { - this.token("("); - this.print(node.expression, node); - this.print(node.typeAnnotation, node); - this.token(")"); -} - -function VoidTypeAnnotation() { - this.word("void"); -} -},{"./types":42}],37:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.JSXAttribute = JSXAttribute; -exports.JSXIdentifier = JSXIdentifier; -exports.JSXNamespacedName = JSXNamespacedName; -exports.JSXMemberExpression = JSXMemberExpression; -exports.JSXSpreadAttribute = JSXSpreadAttribute; -exports.JSXExpressionContainer = JSXExpressionContainer; -exports.JSXSpreadChild = JSXSpreadChild; -exports.JSXText = JSXText; -exports.JSXElement = JSXElement; -exports.JSXOpeningElement = JSXOpeningElement; -exports.JSXClosingElement = JSXClosingElement; -exports.JSXEmptyExpression = JSXEmptyExpression; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function JSXAttribute(node) { - this.print(node.name, node); - if (node.value) { - this.token("="); - this.print(node.value, node); - } -} - -function JSXIdentifier(node) { - this.word(node.name); -} - -function JSXNamespacedName(node) { - this.print(node.namespace, node); - this.token(":"); - this.print(node.name, node); -} - -function JSXMemberExpression(node) { - this.print(node.object, node); - this.token("."); - this.print(node.property, node); -} - -function JSXSpreadAttribute(node) { - this.token("{"); - this.token("..."); - this.print(node.argument, node); - this.token("}"); -} - -function JSXExpressionContainer(node) { - this.token("{"); - this.print(node.expression, node); - this.token("}"); -} - -function JSXSpreadChild(node) { - this.token("{"); - this.token("..."); - this.print(node.expression, node); - this.token("}"); -} - -function JSXText(node) { - this.token(node.value); -} - -function JSXElement(node) { - var open = node.openingElement; - this.print(open, node); - if (open.selfClosing) return; - - this.indent(); - for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var child = _ref; - - this.print(child, node); - } - this.dedent(); - - this.print(node.closingElement, node); -} - -function spaceSeparator() { - this.space(); -} - -function JSXOpeningElement(node) { - this.token("<"); - this.print(node.name, node); - if (node.attributes.length > 0) { - this.space(); - this.printJoin(node.attributes, node, { separator: spaceSeparator }); - } - if (node.selfClosing) { - this.space(); - this.token("/>"); - } else { - this.token(">"); - } -} - -function JSXClosingElement(node) { - this.token(""); -} - -function JSXEmptyExpression() {} -},{"babel-runtime/core-js/get-iterator":56}],38:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.FunctionDeclaration = undefined; -exports._params = _params; -exports._method = _method; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _params(node) { - var _this = this; - - this.print(node.typeParameters, node); - this.token("("); - this.printList(node.params, node, { - iterator: function iterator(node) { - if (node.optional) _this.token("?"); - _this.print(node.typeAnnotation, node); - } - }); - this.token(")"); - - if (node.returnType) { - this.print(node.returnType, node); - } -} - -function _method(node) { - var kind = node.kind; - var key = node.key; - - if (kind === "method" || kind === "init") { - if (node.generator) { - this.token("*"); - } - } - - if (kind === "get" || kind === "set") { - this.word(kind); - this.space(); - } - - if (node.async) { - this.word("async"); - this.space(); - } - - if (node.computed) { - this.token("["); - this.print(key, node); - this.token("]"); - } else { - this.print(key, node); - } - - this._params(node); - this.space(); - this.print(node.body, node); -} - -function FunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } - this.word("function"); - if (node.generator) this.token("*"); - - if (node.id) { - this.space(); - this.print(node.id, node); - } else { - this.space(); - } - - this._params(node); - this.space(); - this.print(node.body, node); -} - -exports.FunctionDeclaration = FunctionExpression; -function ArrowFunctionExpression(node) { - if (node.async) { - this.word("async"); - this.space(); - } - - var firstParam = node.params[0]; - - if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { - this.print(firstParam, node); - } else { - this._params(node); - } - - this.space(); - this.token("=>"); - this.space(); - - this.print(node.body, node); -} - -function hasTypes(node, param) { - return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; -} -},{"babel-types":112}],39:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ImportSpecifier = ImportSpecifier; -exports.ImportDefaultSpecifier = ImportDefaultSpecifier; -exports.ExportDefaultSpecifier = ExportDefaultSpecifier; -exports.ExportSpecifier = ExportSpecifier; -exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; -exports.ExportAllDeclaration = ExportAllDeclaration; -exports.ExportNamedDeclaration = ExportNamedDeclaration; -exports.ExportDefaultDeclaration = ExportDefaultDeclaration; -exports.ImportDeclaration = ImportDeclaration; -exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -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) { - 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.token("*"); - this.space(); - this.word("as"); - this.space(); - this.print(node.exported, node); -} - -function ExportAllDeclaration(node) { - this.word("export"); - this.space(); - this.token("*"); - if (node.exported) { - this.space(); - this.word("as"); - this.space(); - this.print(node.exported, node); - } - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); - this.semicolon(); -} - -function ExportNamedDeclaration() { - this.word("export"); - this.space(); - ExportDeclaration.apply(this, arguments); -} - -function ExportDefaultDeclaration() { - this.word("export"); - this.space(); - this.word("default"); - this.space(); - ExportDeclaration.apply(this, arguments); -} - -function ExportDeclaration(node) { - if (node.declaration) { - var declar = node.declaration; - this.print(declar, node); - if (!t.isStatement(declar)) this.semicolon(); - } else { - if (node.exportKind === "type") { - this.word("type"); - this.space(); - } - - var specifiers = node.specifiers.slice(0); - - var hasSpecial = false; - while (true) { - var first = specifiers[0]; - if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) { - hasSpecial = true; - this.print(specifiers.shift(), node); - if (specifiers.length) { - this.token(","); - this.space(); - } - } else { - break; - } - } - - if (specifiers.length || !specifiers.length && !hasSpecial) { - this.token("{"); - if (specifiers.length) { - this.space(); - this.printList(specifiers, node); - this.space(); - } - this.token("}"); - } - - if (node.source) { - this.space(); - this.word("from"); - this.space(); - this.print(node.source, node); - } - - this.semicolon(); - } -} - -function ImportDeclaration(node) { - this.word("import"); - this.space(); - - if (node.importKind === "type" || node.importKind === "typeof") { - this.word(node.importKind); - this.space(); - } - - var specifiers = node.specifiers.slice(0); - if (specifiers && specifiers.length) { - while (true) { - var first = specifiers[0]; - if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { - this.print(specifiers.shift(), node); - if (specifiers.length) { - this.token(","); - this.space(); - } - } else { - break; - } - } - - if (specifiers.length) { - this.token("{"); - this.space(); - this.printList(specifiers, node); - this.space(); - this.token("}"); - } - - this.space(); - this.word("from"); - this.space(); - } - - this.print(node.source, node); - this.semicolon(); -} - -function ImportNamespaceSpecifier(node) { - this.token("*"); - this.space(); - this.word("as"); - this.space(); - this.print(node.local, node); -} -},{"babel-types":112}],40:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForAwaitStatement = exports.ForOfStatement = exports.ForInStatement = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.WithStatement = WithStatement; -exports.IfStatement = IfStatement; -exports.ForStatement = ForStatement; -exports.WhileStatement = WhileStatement; -exports.DoWhileStatement = DoWhileStatement; -exports.LabeledStatement = LabeledStatement; -exports.TryStatement = TryStatement; -exports.CatchClause = CatchClause; -exports.SwitchStatement = SwitchStatement; -exports.SwitchCase = SwitchCase; -exports.DebuggerStatement = DebuggerStatement; -exports.VariableDeclaration = VariableDeclaration; -exports.VariableDeclarator = VariableDeclarator; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function WithStatement(node) { - this.word("with"); - this.space(); - this.token("("); - this.print(node.object, node); - this.token(")"); - this.printBlock(node); -} - -function IfStatement(node) { - this.word("if"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.space(); - - var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); - if (needsBlock) { - this.token("{"); - this.newline(); - this.indent(); - } - - this.printAndIndentOnComments(node.consequent, node); - - if (needsBlock) { - this.dedent(); - this.newline(); - this.token("}"); - } - - if (node.alternate) { - if (this.endsWith("}")) this.space(); - this.word("else"); - this.space(); - this.printAndIndentOnComments(node.alternate, node); - } -} - -function getLastStatement(statement) { - if (!t.isStatement(statement.body)) return statement; - return getLastStatement(statement.body); -} - -function ForStatement(node) { - this.word("for"); - this.space(); - this.token("("); - - this.inForStatementInitCounter++; - this.print(node.init, node); - this.inForStatementInitCounter--; - this.token(";"); - - if (node.test) { - this.space(); - this.print(node.test, node); - } - this.token(";"); - - if (node.update) { - this.space(); - this.print(node.update, node); - } - - this.token(")"); - this.printBlock(node); -} - -function WhileStatement(node) { - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.printBlock(node); -} - -var buildForXStatement = function buildForXStatement(op) { - return function (node) { - this.word("for"); - this.space(); - if (op === "await") { - this.word("await"); - this.space(); - op = "of"; - } - this.token("("); - - this.print(node.left, node); - this.space(); - this.word(op); - this.space(); - this.print(node.right, node); - this.token(")"); - this.printBlock(node); - }; -}; - -var ForInStatement = exports.ForInStatement = buildForXStatement("in"); -var ForOfStatement = exports.ForOfStatement = buildForXStatement("of"); -var ForAwaitStatement = exports.ForAwaitStatement = buildForXStatement("await"); - -function DoWhileStatement(node) { - this.word("do"); - this.space(); - this.print(node.body, node); - this.space(); - this.word("while"); - this.space(); - this.token("("); - this.print(node.test, node); - this.token(")"); - this.semicolon(); -} - -function buildLabelStatement(prefix) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "label"; - - return function (node) { - this.word(prefix); - - var label = node[key]; - if (label) { - this.space(); - - var terminatorState = this.startTerminatorless(); - this.print(label, node); - this.endTerminatorless(terminatorState); - } - - this.semicolon(); - }; -} - -var ContinueStatement = exports.ContinueStatement = buildLabelStatement("continue"); -var ReturnStatement = exports.ReturnStatement = buildLabelStatement("return", "argument"); -var BreakStatement = exports.BreakStatement = buildLabelStatement("break"); -var ThrowStatement = exports.ThrowStatement = buildLabelStatement("throw", "argument"); - -function LabeledStatement(node) { - this.print(node.label, node); - this.token(":"); - 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(); - this.token("("); - this.print(node.param, node); - this.token(")"); - this.space(); - this.print(node.body, node); -} - -function SwitchStatement(node) { - this.word("switch"); - this.space(); - this.token("("); - this.print(node.discriminant, node); - this.token(")"); - this.space(); - this.token("{"); - - this.printSequence(node.cases, node, { - indent: true, - addNewlines: function addNewlines(leading, cas) { - if (!leading && node.cases[node.cases.length - 1] === cas) return -1; - } - }); - - this.token("}"); -} - -function SwitchCase(node) { - if (node.test) { - this.word("case"); - this.space(); - this.print(node.test, node); - this.token(":"); - } else { - this.word("default"); - this.token(":"); - } - - if (node.consequent.length) { - this.newline(); - this.printSequence(node.consequent, node, { indent: true }); - } -} - -function DebuggerStatement() { - this.word("debugger"); - this.semicolon(); -} - -function variableDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { - this.space(true); - } -} - -function constDeclarationIdent() { - this.token(","); - this.newline(); - if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { - this.space(true); - } -} - -function VariableDeclaration(node, parent) { - this.word(node.kind); - this.space(); - - var hasInits = false; - - if (!t.isFor(parent)) { - for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var declar = _ref; - - if (declar.init) { - hasInits = true; - } - } - } - - var separator = void 0; - if (hasInits) { - separator = node.kind === "const" ? constDeclarationIdent : variableDeclarationIdent; - } - - this.printList(node.declarations, node, { separator: separator }); - - if (t.isFor(parent)) { - if (parent.left === node || parent.init === node) return; - } - - this.semicolon(); -} - -function VariableDeclarator(node) { - this.print(node.id, node); - this.print(node.id.typeAnnotation, node); - if (node.init) { - this.space(); - this.token("="); - this.space(); - this.print(node.init, node); - } -} -},{"babel-runtime/core-js/get-iterator":56,"babel-types":112}],41:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.TaggedTemplateExpression = TaggedTemplateExpression; -exports.TemplateElement = TemplateElement; -exports.TemplateLiteral = TemplateLiteral; -function TaggedTemplateExpression(node) { - this.print(node.tag, node); - this.print(node.quasi, node); -} - -function TemplateElement(node, parent) { - var isFirst = parent.quasis[0] === node; - var isLast = parent.quasis[parent.quasis.length - 1] === node; - - var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); - - this.token(value); -} - -function TemplateLiteral(node) { - var quasis = node.quasis; - - for (var i = 0; i < quasis.length; i++) { - this.print(quasis[i], node); - - if (i + 1 < quasis.length) { - this.print(node.expressions[i], node); - } - } -} -},{}],42:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ArrayPattern = exports.ObjectPattern = exports.RestProperty = exports.SpreadProperty = exports.SpreadElement = undefined; -exports.Identifier = Identifier; -exports.RestElement = RestElement; -exports.ObjectExpression = ObjectExpression; -exports.ObjectMethod = ObjectMethod; -exports.ObjectProperty = ObjectProperty; -exports.ArrayExpression = ArrayExpression; -exports.RegExpLiteral = RegExpLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.NumericLiteral = NumericLiteral; -exports.StringLiteral = StringLiteral; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _jsesc = require("jsesc"); - -var _jsesc2 = _interopRequireDefault(_jsesc); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function Identifier(node) { - if (node.variance) { - if (node.variance === "plus") { - this.token("+"); - } else if (node.variance === "minus") { - this.token("-"); - } - } - - this.word(node.name); -} - -function RestElement(node) { - this.token("..."); - this.print(node.argument, node); -} - -exports.SpreadElement = RestElement; -exports.SpreadProperty = RestElement; -exports.RestProperty = RestElement; -function ObjectExpression(node) { - var props = node.properties; - - this.token("{"); - this.printInnerComments(node); - - if (props.length) { - this.space(); - this.printList(props, node, { indent: true, statement: true }); - this.space(); - } - - this.token("}"); -} - -exports.ObjectPattern = ObjectExpression; -function ObjectMethod(node) { - this.printJoin(node.decorators, node); - this._method(node); -} - -function ObjectProperty(node) { - this.printJoin(node.decorators, node); - - if (node.computed) { - this.token("["); - this.print(node.key, node); - this.token("]"); - } else { - if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) { - this.print(node.value, node); - return; - } - - this.print(node.key, node); - - if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { - return; - } - } - - this.token(":"); - this.space(); - this.print(node.value, node); -} - -function ArrayExpression(node) { - var elems = node.elements; - var len = elems.length; - - this.token("["); - this.printInnerComments(node); - - for (var i = 0; i < elems.length; i++) { - var elem = elems[i]; - if (elem) { - if (i > 0) this.space(); - this.print(elem, node); - if (i < len - 1) this.token(","); - } else { - this.token(","); - } - } - - this.token("]"); -} - -exports.ArrayPattern = ArrayExpression; -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) { - var raw = this.getPossibleRaw(node); - var value = node.value + ""; - 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, parent) { - var raw = this.getPossibleRaw(node); - if (!this.format.minified && raw != null) { - this.token(raw); - return; - } - - var opts = { - quotes: t.isJSX(parent) ? "double" : this.format.quotes, - wrap: true - }; - if (this.format.jsonCompatibleStrings) { - opts.json = true; - } - var val = (0, _jsesc2.default)(node.value, opts); - - return this.token(val); -} -},{"babel-types":112,"jsesc":249}],43:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.CodeGenerator = undefined; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); - -var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); - -var _inherits2 = require("babel-runtime/helpers/inherits"); - -var _inherits3 = _interopRequireDefault(_inherits2); - -exports.default = function (ast, opts, code) { - var gen = new Generator(ast, opts, code); - return gen.generate(); -}; - -var _detectIndent = require("detect-indent"); - -var _detectIndent2 = _interopRequireDefault(_detectIndent); - -var _sourceMap = require("./source-map"); - -var _sourceMap2 = _interopRequireDefault(_sourceMap); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _printer = require("./printer"); - -var _printer2 = _interopRequireDefault(_printer); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Generator = function (_Printer) { - (0, _inherits3.default)(Generator, _Printer); - - function Generator(ast, opts, code) { - (0, _classCallCheck3.default)(this, Generator); - - opts = opts || {}; - - var tokens = ast.tokens || []; - var format = normalizeOptions(code, opts, tokens); - var map = opts.sourceMaps ? new _sourceMap2.default(opts, code) : null; - - var _this = (0, _possibleConstructorReturn3.default)(this, _Printer.call(this, format, map, tokens)); - - _this.ast = ast; - return _this; - } - - Generator.prototype.generate = function generate() { - return _Printer.prototype.generate.call(this, this.ast); - }; - - return Generator; -}(_printer2.default); - -function normalizeOptions(code, opts, tokens) { - var style = " "; - if (code && typeof code === "string") { - var indent = (0, _detectIndent2.default)(code).indent; - if (indent && indent !== " ") style = indent; - } - - var 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, - quotes: opts.quotes || findCommonStringDelimiter(code, tokens), - jsonCompatibleStrings: opts.jsonCompatibleStrings, - indent: { - adjustMultilineComment: true, - style: style, - base: 0 - }, - flowCommaSeparator: opts.flowCommaSeparator - }; - - if (format.minified) { - format.compact = true; - - format.shouldPrintComment = format.shouldPrintComment || function () { - return format.comments; - }; - } else { - format.shouldPrintComment = format.shouldPrintComment || function (value) { - return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; - }; - } - - if (format.compact === "auto") { - format.compact = code.length > 500000; - - if (format.compact) { - console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "500KB")); - } - } - - if (format.compact) { - format.indent.adjustMultilineComment = false; - } - - return format; -} - -function findCommonStringDelimiter(code, tokens) { - var DEFAULT_STRING_DELIMITER = "double"; - if (!code) { - return DEFAULT_STRING_DELIMITER; - } - - var occurences = { - single: 0, - double: 0 - }; - - var checked = 0; - - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token.type.label !== "string") continue; - - var raw = code.slice(token.start, token.end); - if (raw[0] === "'") { - occurences.single++; - } else { - occurences.double++; - } - - checked++; - if (checked >= 3) break; - } - if (occurences.single > occurences.double) { - return "single"; - } else { - return "double"; - } -} - -var CodeGenerator = exports.CodeGenerator = function () { - function CodeGenerator(ast, opts, code) { - (0, _classCallCheck3.default)(this, CodeGenerator); - - this._generator = new Generator(ast, opts, code); - } - - CodeGenerator.prototype.generate = function generate() { - return this._generator.generate(); - }; - - return CodeGenerator; -}(); -},{"./printer":47,"./source-map":48,"babel-messages":53,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/inherits":71,"babel-runtime/helpers/possibleConstructorReturn":73,"detect-indent":235}],44:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -exports.needsWhitespace = needsWhitespace; -exports.needsWhitespaceBefore = needsWhitespaceBefore; -exports.needsWhitespaceAfter = needsWhitespaceAfter; -exports.needsParens = needsParens; - -var _whitespace = require("./whitespace"); - -var _whitespace2 = _interopRequireDefault(_whitespace); - -var _parentheses = require("./parentheses"); - -var parens = _interopRequireWildcard(_parentheses); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function expandAliases(obj) { - var newObj = {}; - - function add(type, func) { - var fn = newObj[type]; - newObj[type] = fn ? function (node, parent, stack) { - var result = fn(node, parent, stack); - - return result == null ? func(node, parent, stack) : result; - } : func; - } - - for (var _iterator = (0, _keys2.default)(obj), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var type = _ref; - - - var aliases = t.FLIPPED_ALIAS_KEYS[type]; - if (aliases) { - for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var alias = _ref2; - - add(alias, obj[type]); - } - } else { - add(type, obj[type]); - } - } - - return newObj; -} - -var expandedParens = expandAliases(parens); -var expandedWhitespaceNodes = expandAliases(_whitespace2.default.nodes); -var expandedWhitespaceList = expandAliases(_whitespace2.default.list); - -function find(obj, node, parent, printStack) { - var fn = obj[node.type]; - return fn ? fn(node, parent, printStack) : null; -} - -function isOrHasCallExpression(node) { - if (t.isCallExpression(node)) { - return true; - } - - if (t.isMemberExpression(node)) { - return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); - } else { - return false; - } -} - -function needsWhitespace(node, parent, type) { - if (!node) return 0; - - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - var linesInfo = find(expandedWhitespaceNodes, node, parent); - - if (!linesInfo) { - var items = find(expandedWhitespaceList, node, parent); - if (items) { - for (var i = 0; i < items.length; i++) { - linesInfo = needsWhitespace(items[i], node, type); - if (linesInfo) break; - } - } - } - - return linesInfo && linesInfo[type] || 0; -} - -function needsWhitespaceBefore(node, parent) { - return needsWhitespace(node, parent, "before"); -} - -function needsWhitespaceAfter(node, parent) { - return needsWhitespace(node, parent, "after"); -} - -function needsParens(node, parent, printStack) { - if (!parent) return false; - - if (t.isNewExpression(parent) && parent.callee === node) { - if (isOrHasCallExpression(node)) return true; - } - - return find(expandedParens, node, parent, printStack); -} -},{"./parentheses":45,"./whitespace":46,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/object/keys":63,"babel-types":112}],45:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.AwaitExpression = exports.FunctionTypeAnnotation = undefined; -exports.NullableTypeAnnotation = NullableTypeAnnotation; -exports.UpdateExpression = UpdateExpression; -exports.ObjectExpression = ObjectExpression; -exports.Binary = Binary; -exports.BinaryExpression = BinaryExpression; -exports.SequenceExpression = SequenceExpression; -exports.YieldExpression = YieldExpression; -exports.ClassExpression = ClassExpression; -exports.UnaryLike = UnaryLike; -exports.FunctionExpression = FunctionExpression; -exports.ArrowFunctionExpression = ArrowFunctionExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.AssignmentExpression = AssignmentExpression; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var PRECEDENCE = { - "||": 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 -}; - -function NullableTypeAnnotation(node, parent) { - return t.isArrayTypeAnnotation(parent); -} - -exports.FunctionTypeAnnotation = NullableTypeAnnotation; -function UpdateExpression(node, parent) { - if (t.isMemberExpression(parent) && parent.object === node) { - return true; - } - - return false; -} - -function ObjectExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerArrow: true }); -} - -function Binary(node, parent) { - if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) { - return true; - } - - if (t.isUnaryLike(parent)) { - return true; - } - - if (t.isMemberExpression(parent) && parent.object === node) { - return true; - } - - if (t.isBinary(parent)) { - var parentOp = parent.operator; - var parentPos = PRECEDENCE[parentOp]; - - var nodeOp = node.operator; - var nodePos = PRECEDENCE[nodeOp]; - - if (parentPos > nodePos) { - return true; - } - - if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent)) { - return true; - } - } - - return false; -} - -function BinaryExpression(node, parent) { - if (node.operator === "in") { - if (t.isVariableDeclarator(parent)) { - return true; - } - - if (t.isFor(parent)) { - return true; - } - } - - return false; -} - -function SequenceExpression(node, parent) { - if (t.isForStatement(parent)) { - return false; - } - - if (t.isExpressionStatement(parent) && parent.expression === node) { - return false; - } - - if (t.isReturnStatement(parent)) { - return false; - } - - if (t.isThrowStatement(parent)) { - return false; - } - - if (t.isSwitchStatement(parent) && parent.discriminant === node) { - return false; - } - - if (t.isWhileStatement(parent) && parent.test === node) { - return false; - } - - if (t.isIfStatement(parent) && parent.test === node) { - return false; - } - - if (t.isForInStatement(parent) && parent.right === node) { - return false; - } - - return true; -} - -function YieldExpression(node, parent) { - return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) && node === parent.test; -} - -exports.AwaitExpression = YieldExpression; -function ClassExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); -} - -function UnaryLike(node, parent) { - if (t.isMemberExpression(parent, { object: node })) { - return true; - } - - if (t.isCallExpression(parent, { callee: node }) || t.isNewExpression(parent, { callee: node })) { - return true; - } - - return false; -} - -function FunctionExpression(node, parent, printStack) { - return isFirstInStatement(printStack, { considerDefaultExports: true }); -} - -function ArrowFunctionExpression(node, parent) { - if (t.isExportDeclaration(parent) || t.isBinaryExpression(parent) || t.isLogicalExpression(parent) || t.isUnaryExpression(parent) || t.isTaggedTemplateExpression(parent)) { - return true; - } - - return UnaryLike(node, parent); -} - -function ConditionalExpression(node, parent) { - if (t.isUnaryLike(parent)) { - return true; - } - - if (t.isBinary(parent)) { - return true; - } - - if (t.isConditionalExpression(parent, { test: node })) { - return true; - } - - if (t.isAwaitExpression(parent)) { - return true; - } - - return UnaryLike(node, parent); -} - -function AssignmentExpression(node) { - if (t.isObjectPattern(node.left)) { - return true; - } else { - return ConditionalExpression.apply(undefined, arguments); - } -} - -function isFirstInStatement(printStack) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$considerArrow = _ref.considerArrow, - considerArrow = _ref$considerArrow === undefined ? false : _ref$considerArrow, - _ref$considerDefaultE = _ref.considerDefaultExports, - considerDefaultExports = _ref$considerDefaultE === undefined ? false : _ref$considerDefaultE; - - var i = printStack.length - 1; - var node = printStack[i]; - i--; - var parent = printStack[i]; - while (i > 0) { - if (t.isExpressionStatement(parent, { expression: node })) { - return true; - } - - if (t.isTaggedTemplateExpression(parent)) { - return true; - } - - if (considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: node })) { - return true; - } - - if (considerArrow && t.isArrowFunctionExpression(parent, { body: node })) { - return true; - } - - if (t.isCallExpression(parent, { callee: node }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { object: node }) || t.isConditional(parent, { test: node }) || t.isBinary(parent, { left: node }) || t.isAssignmentExpression(parent, { left: node })) { - node = parent; - i--; - parent = printStack[i]; - } else { - return false; - } - } - - return false; -} -},{"babel-types":112}],46:[function(require,module,exports){ -"use strict"; - -var _map = require("lodash/map"); - -var _map2 = _interopRequireDefault(_map); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function crawl(node) { - var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - if (t.isMemberExpression(node)) { - crawl(node.object, state); - if (node.computed) crawl(node.property, state); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - crawl(node.left, state); - crawl(node.right, state); - } else if (t.isCallExpression(node)) { - state.hasCall = true; - crawl(node.callee, state); - } else if (t.isFunction(node)) { - state.hasFunction = true; - } else if (t.isIdentifier(node)) { - state.hasHelper = state.hasHelper || isHelper(node.callee); - } - - return state; -} - -function isHelper(node) { - if (t.isMemberExpression(node)) { - return isHelper(node.object) || isHelper(node.property); - } else if (t.isIdentifier(node)) { - return node.name === "require" || node.name[0] === "_"; - } else if (t.isCallExpression(node)) { - return isHelper(node.callee); - } else if (t.isBinary(node) || t.isAssignmentExpression(node)) { - return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); - } else { - return false; - } -} - -function isType(node) { - return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node); -} - -exports.nodes = { - AssignmentExpression: function AssignmentExpression(node) { - var state = crawl(node.right); - if (state.hasCall && state.hasHelper || state.hasFunction) { - return { - before: state.hasFunction, - after: true - }; - } - }, - SwitchCase: function SwitchCase(node, parent) { - return { - before: node.consequent.length || parent.cases[0] === node - }; - }, - LogicalExpression: function LogicalExpression(node) { - if (t.isFunction(node.left) || t.isFunction(node.right)) { - return { - after: true - }; - } - }, - Literal: function Literal(node) { - if (node.value === "use strict") { - return { - after: true - }; - } - }, - CallExpression: function CallExpression(node) { - if (t.isFunction(node.callee) || isHelper(node)) { - return { - before: true, - after: true - }; - } - }, - VariableDeclaration: function VariableDeclaration(node) { - for (var i = 0; i < node.declarations.length; i++) { - var declar = node.declarations[i]; - - var enabled = isHelper(declar.id) && !isType(declar.init); - if (!enabled) { - var state = crawl(declar.init); - enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; - } - - if (enabled) { - return { - before: true, - after: true - }; - } - } - }, - IfStatement: function IfStatement(node) { - if (t.isBlockStatement(node.consequent)) { - return { - before: true, - after: true - }; - } - } -}; - -exports.nodes.ObjectProperty = exports.nodes.ObjectTypeProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) { - if (parent.properties[0] === node) { - return { - before: true - }; - } -}; - -exports.list = { - VariableDeclaration: function VariableDeclaration(node) { - return (0, _map2.default)(node.declarations, "init"); - }, - ArrayExpression: function ArrayExpression(node) { - return node.elements; - }, - ObjectExpression: function ObjectExpression(node) { - return node.properties; - } -}; - -[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function (_ref) { - var type = _ref[0], - amounts = _ref[1]; - - if (typeof amounts === "boolean") { - amounts = { after: amounts, before: amounts }; - } - [type].concat(t.FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { - exports.nodes[type] = function () { - return amounts; - }; - }); -}); -},{"babel-types":112,"lodash/map":449}],47:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _assign = require("babel-runtime/core-js/object/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _weakSet = require("babel-runtime/core-js/weak-set"); - -var _weakSet2 = _interopRequireDefault(_weakSet); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _find = require("lodash/find"); - -var _find2 = _interopRequireDefault(_find); - -var _findLast = require("lodash/findLast"); - -var _findLast2 = _interopRequireDefault(_findLast); - -var _isInteger = require("lodash/isInteger"); - -var _isInteger2 = _interopRequireDefault(_isInteger); - -var _repeat = require("lodash/repeat"); - -var _repeat2 = _interopRequireDefault(_repeat); - -var _buffer = require("./buffer"); - -var _buffer2 = _interopRequireDefault(_buffer); - -var _node = require("./node"); - -var n = _interopRequireWildcard(_node); - -var _whitespace = require("./whitespace"); - -var _whitespace2 = _interopRequireDefault(_whitespace); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SCIENTIFIC_NOTATION = /e/i; -var ZERO_DECIMAL_INTEGER = /\.0+$/; -var NON_DECIMAL_LITERAL = /^0[box]/; - -var Printer = function () { - function Printer(format, map, tokens) { - (0, _classCallCheck3.default)(this, Printer); - this.inForStatementInitCounter = 0; - this._printStack = []; - this._indent = 0; - this._insideAux = false; - this._printedCommentStarts = {}; - this._parenPushNewlineState = null; - this._printAuxAfterOnNextUserNode = false; - this._printedComments = new _weakSet2.default(); - this._endsWithInteger = false; - this._endsWithWord = false; - - this.format = format || {}; - this._buf = new _buffer2.default(map); - this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null; - } - - Printer.prototype.generate = function generate(ast) { - this.print(ast); - this._maybeAddAuxComment(); - - return this._buf.get(); - }; - - Printer.prototype.indent = function indent() { - if (this.format.compact || this.format.concise) return; - - this._indent++; - }; - - Printer.prototype.dedent = function dedent() { - if (this.format.compact || this.format.concise) return; - - this._indent--; - }; - - Printer.prototype.semicolon = function semicolon() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - this._maybeAddAuxComment(); - this._append(";", !force); - }; - - Printer.prototype.rightBrace = function rightBrace() { - if (this.format.minified) { - this._buf.removeLastSemicolon(); - } - this.token("}"); - }; - - Printer.prototype.space = function space() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - - if (this.format.compact) return; - - if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { - this._space(); - } - }; - - Printer.prototype.word = function word(str) { - if (this._endsWithWord) this._space(); - - this._maybeAddAuxComment(); - this._append(str); - - this._endsWithWord = true; - }; - - Printer.prototype.number = function number(str) { - this.word(str); - - this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; - }; - - Printer.prototype.token = function token(str) { - if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { - this._space(); - } - - this._maybeAddAuxComment(); - this._append(str); - }; - - Printer.prototype.newline = function newline(i) { - if (this.format.retainLines || this.format.compact) return; - - if (this.format.concise) { - this.space(); - return; - } - - if (this.endsWith("\n\n")) return; - - if (typeof i !== "number") i = 1; - - i = Math.min(2, i); - if (this.endsWith("{\n") || this.endsWith(":\n")) i--; - if (i <= 0) return; - - for (var j = 0; j < i; j++) { - this._newline(); - } - }; - - Printer.prototype.endsWith = function endsWith(str) { - return this._buf.endsWith(str); - }; - - Printer.prototype.removeTrailingNewline = function removeTrailingNewline() { - this._buf.removeTrailingNewline(); - }; - - Printer.prototype.source = function source(prop, loc) { - this._catchUp(prop, loc); - - this._buf.source(prop, loc); - }; - - Printer.prototype.withSource = function withSource(prop, loc, cb) { - this._catchUp(prop, loc); - - this._buf.withSource(prop, loc, cb); - }; - - Printer.prototype._space = function _space() { - this._append(" ", true); - }; - - Printer.prototype._newline = function _newline() { - this._append("\n", true); - }; - - Printer.prototype._append = function _append(str) { - var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - this._maybeAddParen(str); - this._maybeIndent(str); - - if (queue) this._buf.queue(str);else this._buf.append(str); - - this._endsWithWord = false; - this._endsWithInteger = false; - }; - - Printer.prototype._maybeIndent = function _maybeIndent(str) { - if (this._indent && this.endsWith("\n") && str[0] !== "\n") { - this._buf.queue(this._getIndent()); - } - }; - - Printer.prototype._maybeAddParen = function _maybeAddParen(str) { - var parenPushNewlineState = this._parenPushNewlineState; - if (!parenPushNewlineState) return; - this._parenPushNewlineState = null; - - var i = void 0; - for (i = 0; i < str.length && str[i] === " "; i++) { - continue; - }if (i === str.length) return; - - var cha = str[i]; - if (cha === "\n" || cha === "/") { - this.token("("); - this.indent(); - parenPushNewlineState.printed = true; - } - }; - - Printer.prototype._catchUp = function _catchUp(prop, loc) { - if (!this.format.retainLines) return; - - var pos = loc ? loc[prop] : null; - if (pos && pos.line !== null) { - var count = pos.line - this._buf.getCurrentLine(); - - for (var i = 0; i < count; i++) { - this._newline(); - } - } - }; - - Printer.prototype._getIndent = function _getIndent() { - return (0, _repeat2.default)(this.format.indent.style, this._indent); - }; - - Printer.prototype.startTerminatorless = function startTerminatorless() { - return this._parenPushNewlineState = { - printed: false - }; - }; - - Printer.prototype.endTerminatorless = function endTerminatorless(state) { - if (state.printed) { - this.dedent(); - this.newline(); - this.token(")"); - } - }; - - Printer.prototype.print = function print(node, parent) { - var _this = this; - - if (!node) return; - - var oldConcise = this.format.concise; - if (node._compact) { - this.format.concise = true; - } - - var printMethod = this[node.type]; - if (!printMethod) { - throw new ReferenceError("unknown node of type " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name)); - } - - this._printStack.push(node); - - var oldInAux = this._insideAux; - this._insideAux = !node.loc; - this._maybeAddAuxComment(this._insideAux && !oldInAux); - - var needsParens = n.needsParens(node, parent, this._printStack); - if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { - needsParens = true; - } - if (needsParens) this.token("("); - - this._printLeadingComments(node, parent); - - var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; - this.withSource("start", loc, function () { - _this[node.type](node, parent); - }); - - this._printTrailingComments(node, parent); - - if (needsParens) this.token(")"); - - this._printStack.pop(); - - this.format.concise = oldConcise; - this._insideAux = oldInAux; - }; - - Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) { - if (enteredPositionlessNode) this._printAuxBeforeComment(); - if (!this._insideAux) this._printAuxAfterComment(); - }; - - Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() { - if (this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = true; - - var comment = this.format.auxiliaryCommentBefore; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; - - Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() { - if (!this._printAuxAfterOnNextUserNode) return; - this._printAuxAfterOnNextUserNode = false; - - var comment = this.format.auxiliaryCommentAfter; - if (comment) { - this._printComment({ - type: "CommentBlock", - value: comment - }); - } - }; - - Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { - var extra = node.extra; - if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { - return extra.raw; - } - }; - - Printer.prototype.printJoin = function printJoin(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - if (!nodes || !nodes.length) return; - - if (opts.indent) this.indent(); - - var newlineOpts = { - addNewlines: opts.addNewlines - }; - - for (var i = 0; i < nodes.length; i++) { - var 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 < nodes.length - 1) { - opts.separator.call(this); - } - - if (opts.statement) this._printNewline(false, node, parent, newlineOpts); - } - - if (opts.indent) this.dedent(); - }; - - Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) { - var indent = !!node.leadingComments; - if (indent) this.indent(); - this.print(node, parent); - if (indent) this.dedent(); - }; - - Printer.prototype.printBlock = function printBlock(parent) { - var node = parent.body; - - if (!t.isEmptyStatement(node)) { - this.space(); - } - - this.print(node, parent); - }; - - Printer.prototype._printTrailingComments = function _printTrailingComments(node, parent) { - this._printComments(this._getComments(false, node, parent)); - }; - - Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) { - this._printComments(this._getComments(true, node, parent)); - }; - - Printer.prototype.printInnerComments = function printInnerComments(node) { - var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - if (!node.innerComments) return; - if (indent) this.indent(); - this._printComments(node.innerComments); - if (indent) this.dedent(); - }; - - Printer.prototype.printSequence = function printSequence(nodes, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - opts.statement = true; - return this.printJoin(nodes, parent, opts); - }; - - Printer.prototype.printList = function printList(items, parent) { - var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - if (opts.separator == null) { - opts.separator = commaSeparator; - } - - return this.printJoin(items, parent, opts); - }; - - Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { - var _this2 = this; - - if (this.format.retainLines || this.format.compact) return; - - if (this.format.concise) { - this.space(); - return; - } - - var lines = 0; - - if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) { - if (leading) { - var _comments = node.leadingComments; - var _comment = _comments && (0, _find2.default)(_comments, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); - - lines = this._whitespace.getNewlinesBefore(_comment || node); - } else { - var _comments2 = node.trailingComments; - var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) { - return !!comment.loc && _this2.format.shouldPrintComment(comment.value); - }); - - lines = this._whitespace.getNewlinesAfter(_comment2 || node); - } - } else { - if (!leading) lines++; - if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; - - var needs = n.needsWhitespaceAfter; - if (leading) needs = n.needsWhitespaceBefore; - if (needs(node, parent)) lines++; - - if (!this._buf.hasContent()) lines = 0; - } - - this.newline(lines); - }; - - Printer.prototype._getComments = function _getComments(leading, node) { - return node && (leading ? node.leadingComments : node.trailingComments) || []; - }; - - Printer.prototype._printComment = function _printComment(comment) { - var _this3 = this; - - if (!this.format.shouldPrintComment(comment.value)) return; - - if (comment.ignore) return; - - if (this._printedComments.has(comment)) return; - this._printedComments.add(comment); - - if (comment.start != null) { - if (this._printedCommentStarts[comment.start]) return; - this._printedCommentStarts[comment.start] = true; - } - - this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0); - - if (!this.endsWith("[") && !this.endsWith("{")) this.space(); - - var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/"; - - if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { - var offset = comment.loc && comment.loc.start.column; - if (offset) { - var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); - val = val.replace(newlineRegex, "\n"); - } - - var indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); - val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize)); - } - - this.withSource("start", comment.loc, function () { - _this3._append(val); - }); - - this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0)); - }; - - Printer.prototype._printComments = function _printComments(comments) { - if (!comments || !comments.length) return; - - for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _comment3 = _ref; - - this._printComment(_comment3); - } - }; - - return Printer; -}(); - -exports.default = Printer; - - -function commaSeparator() { - this.token(","); - this.space(); -} - -var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")]; -for (var _i2 = 0; _i2 < _arr.length; _i2++) { - var generator = _arr[_i2]; - (0, _assign2.default)(Printer.prototype, generator); -} -module.exports = exports["default"]; -},{"./buffer":32,"./generators/base":33,"./generators/classes":34,"./generators/expressions":35,"./generators/flow":36,"./generators/jsx":37,"./generators/methods":38,"./generators/modules":39,"./generators/statements":40,"./generators/template-literals":41,"./generators/types":42,"./node":44,"./whitespace":49,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/json/stringify":57,"babel-runtime/core-js/object/assign":60,"babel-runtime/core-js/weak-set":69,"babel-runtime/helpers/classCallCheck":70,"babel-types":112,"lodash/find":423,"lodash/findLast":425,"lodash/isInteger":438,"lodash/repeat":454}],48:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _sourceMap = require("source-map"); - -var _sourceMap2 = _interopRequireDefault(_sourceMap); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var SourceMap = function () { - function SourceMap(opts, code) { - (0, _classCallCheck3.default)(this, SourceMap); - - this._cachedMap = null; - this._code = code; - this._opts = opts; - this._rawMappings = []; - } - - SourceMap.prototype.get = function get() { - var _this = this; - - if (!this._cachedMap) { - (function () { - var map = _this._cachedMap = new _sourceMap2.default.SourceMapGenerator({ - file: _this._opts.sourceMapTarget, - sourceRoot: _this._opts.sourceRoot - }); - - var code = _this._code; - if (typeof code === "string") { - map.setSourceContent(_this._opts.sourceFileName, code); - } else if ((typeof code === "undefined" ? "undefined" : (0, _typeof3.default)(code)) === "object") { - (0, _keys2.default)(code).forEach(function (sourceFileName) { - map.setSourceContent(sourceFileName, code[sourceFileName]); - }); - } - - _this._rawMappings.forEach(map.addMapping, map); - })(); - } - - return this._cachedMap.toJSON(); - }; - - SourceMap.prototype.getRawMappings = function getRawMappings() { - return this._rawMappings.slice(); - }; - - SourceMap.prototype.mark = function mark(generatedLine, generatedColumn, line, column, identifierName, filename) { - if (this._lastGenLine !== generatedLine && line === null) return; - - if (this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { - return; - } - - this._cachedMap = null; - this._lastGenLine = generatedLine; - this._lastSourceLine = line; - this._lastSourceColumn = column; - - this._rawMappings.push({ - name: identifierName || undefined, - generated: { - line: generatedLine, - column: generatedColumn - }, - source: line == null ? undefined : filename || this._opts.sourceFileName, - original: line == null ? undefined : { - line: line, - column: column - } - }); - }; - - return SourceMap; -}(); - -exports.default = SourceMap; -module.exports = exports["default"]; -},{"babel-runtime/core-js/object/keys":63,"babel-runtime/helpers/classCallCheck":70,"babel-runtime/helpers/typeof":74,"source-map":484}],49:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Whitespace = function () { - function Whitespace(tokens) { - (0, _classCallCheck3.default)(this, Whitespace); - - this.tokens = tokens; - this.used = {}; - } - - Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; - - var index = this._findToken(function (token) { - return token.start - node.start; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.start === tokens[index - 1].start) { - --index; - }startToken = tokens[index - 1]; - endToken = tokens[index]; - } - - return this._getNewlinesBetween(startToken, endToken); - }; - - Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) { - var startToken = void 0; - var endToken = void 0; - var tokens = this.tokens; - - var index = this._findToken(function (token) { - return token.end - node.end; - }, 0, tokens.length); - if (index >= 0) { - while (index && node.end === tokens[index - 1].end) { - --index; - }startToken = tokens[index]; - endToken = tokens[index + 1]; - if (endToken.type.label === ",") endToken = tokens[index + 2]; - } - - if (endToken && endToken.type.label === "eof") { - return 1; - } else { - return this._getNewlinesBetween(startToken, endToken); - } - }; - - Whitespace.prototype._getNewlinesBetween = function _getNewlinesBetween(startToken, endToken) { - if (!endToken || !endToken.loc) return 0; - - var start = startToken ? startToken.loc.end.line : 1; - var end = endToken.loc.start.line; - var lines = 0; - - for (var line = start; line < end; line++) { - if (typeof this.used[line] === "undefined") { - this.used[line] = true; - lines++; - } - } - - return lines; - }; - - Whitespace.prototype._findToken = function _findToken(test, start, end) { - if (start >= end) return -1; - var middle = start + end >>> 1; - var match = test(this.tokens[middle]); - if (match < 0) { - return this._findToken(test, middle + 1, end); - } else if (match > 0) { - return this._findToken(test, start, middle); - } else if (match === 0) { - return middle; - } - return -1; - }; - - return Whitespace; -}(); - -exports.default = Whitespace; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":70}],50:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (path, emit) { - var kind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "var"; - - path.traverse(visitor, { kind: kind, emit: emit }); -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var visitor = { - Scope: function Scope(path, state) { - if (state.kind === "let") path.skip(); - }, - Function: function Function(path) { - path.skip(); - }, - VariableDeclaration: function VariableDeclaration(path, state) { - if (state.kind && path.node.kind !== state.kind) return; - - var nodes = []; - - var declarations = path.get("declarations"); - var firstId = void 0; - - for (var _iterator = declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var declar = _ref; - - firstId = declar.node.id; - - if (declar.node.init) { - nodes.push(t.expressionStatement(t.assignmentExpression("=", declar.node.id, declar.node.init))); - } - - for (var name in declar.getBindingIdentifiers()) { - state.emit(t.identifier(name), name); - } - } - - if (path.parentPath.isFor({ left: path.node })) { - path.replaceWith(firstId); - } else { - path.replaceWithMultiple(nodes); - } - } -}; - -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":56,"babel-types":112}],51:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var helpers = {}; -exports.default = helpers; - - -helpers.typeof = (0, _babelTemplate2.default)("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n"); - -helpers.jsx = (0, _babelTemplate2.default)("\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === \"function\" && Symbol.for && Symbol.for(\"react.element\")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n"); - -helpers.asyncIterator = (0, _babelTemplate2.default)("\n (function (iterable) {\n if (typeof Symbol === \"function\") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n })\n"); - -helpers.asyncGenerator = (0, _babelTemplate2.default)("\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume(\"next\", arg); },\n function (arg) { resume(\"throw\", arg); });\n } else {\n settle(result.done ? \"return\" : \"normal\", result.value);\n }\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n"); - -helpers.asyncGeneratorDelegate = (0, _babelTemplate2.default)("\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n return pump(\"return\", value);\n };\n }\n\n return iter;\n })\n"); - -helpers.asyncToGenerator = (0, _babelTemplate2.default)("\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step(\"next\", value);\n }, function (err) {\n step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n"); - -helpers.classCallCheck = (0, _babelTemplate2.default)("\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n });\n"); - -helpers.createClass = (0, _babelTemplate2.default)("\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n"); - -helpers.defineEnumerableProperties = (0, _babelTemplate2.default)("\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n"); - -helpers.defaults = (0, _babelTemplate2.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"); - -helpers.defineProperty = (0, _babelTemplate2.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"); - -helpers.extends = (0, _babelTemplate2.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"); - -helpers.get = (0, _babelTemplate2.default)("\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n"); - -helpers.inherits = (0, _babelTemplate2.default)("\n (function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n"); - -helpers.instanceof = (0, _babelTemplate2.default)("\n (function (left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n"); - -helpers.interopRequireDefault = (0, _babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"); - -helpers.interopRequireWildcard = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"); - -helpers.newArrowCheck = (0, _babelTemplate2.default)("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n"); - -helpers.objectDestructuringEmpty = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n"); - -helpers.objectWithoutProperties = (0, _babelTemplate2.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"); - -helpers.possibleConstructorReturn = (0, _babelTemplate2.default)("\n (function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n });\n"); - -helpers.selfGlobal = (0, _babelTemplate2.default)("\n typeof global === \"undefined\" ? self : global\n"); - -helpers.set = (0, _babelTemplate2.default)("\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if (\"value\" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n"); - -helpers.slicedToArray = (0, _babelTemplate2.default)("\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n })();\n"); - -helpers.slicedToArrayLoose = (0, _babelTemplate2.default)("\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n });\n"); - -helpers.taggedTemplateLiteral = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"); - -helpers.taggedTemplateLiteralLoose = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"); - -helpers.temporalRef = (0, _babelTemplate2.default)("\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n } else {\n return val;\n }\n })\n"); - -helpers.temporalUndefined = (0, _babelTemplate2.default)("\n ({})\n"); - -helpers.toArray = (0, _babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"); - -helpers.toConsumableArray = (0, _babelTemplate2.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"); -module.exports = exports["default"]; -},{"babel-template":75}],52:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.list = undefined; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -exports.get = get; - -var _helpers = require("./helpers"); - -var _helpers2 = _interopRequireDefault(_helpers); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function get(name) { - var fn = _helpers2.default[name]; - if (!fn) throw new ReferenceError("Unknown helper " + name); - - return fn().expression; -} - -var list = exports.list = (0, _keys2.default)(_helpers2.default).map(function (name) { - return name.replace(/^_/, ""); -}).filter(function (name) { - return name !== "__esModule"; -}); - -exports.default = get; -},{"./helpers":51,"babel-runtime/core-js/object/keys":63}],53:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.MESSAGES = undefined; - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -exports.get = get; -exports.parseArgs = parseArgs; - -var _util = require("util"); - -var util = _interopRequireWildcard(_util); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var MESSAGES = exports.MESSAGES = { - tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence", - classesIllegalBareSuper: "Illegal use of bare super", - classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead", - scopeDuplicateDeclaration: "Duplicate declaration $1", - settersNoRest: "Setters aren't allowed to have a rest", - noAssignmentsInForHead: "No assignments allowed in for-in/of head", - expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier", - invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue", - readOnly: "$1 is read-only", - unknownForHead: "Unknown node type $1 in ForStatement", - didYouMean: "Did you mean $1?", - codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.", - missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues", - unsupportedOutputType: "Unsupported output type $1", - illegalMethodName: "Illegal method name $1", - lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated", - - modulesIllegalExportName: "Illegal export $1", - modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes", - - undeclaredVariable: "Reference to undeclared variable $1", - undeclaredVariableType: "Referencing a type alias outside of a type annotation", - undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?", - - traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.", - traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?", - traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2", - traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type", - - pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3", - pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3", - pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4", - pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3" -}; - -function get(key) { - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - var msg = MESSAGES[key]; - if (!msg) throw new ReferenceError("Unknown message " + (0, _stringify2.default)(key)); - - args = parseArgs(args); - - return msg.replace(/\$(\d+)/g, function (str, i) { - return args[i - 1]; - }); -} - -function parseArgs(args) { - return args.map(function (val) { - if (val != null && val.inspect) { - return val.inspect(); - } else { - try { - return (0, _stringify2.default)(val) || val + ""; - } catch (e) { - return util.inspect(val); - } - } - }); -} -},{"babel-runtime/core-js/json/stringify":57,"util":492}],54:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function () { - return { - manipulateOptions: function manipulateOptions(opts, parserOpts) { - parserOpts.plugins.push("dynamicImport"); - } - }; -}; - -module.exports = exports["default"]; -},{}],55:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (_ref) { - var t = _ref.types; - - var IGNORE_REASSIGNMENT_SYMBOL = (0, _symbol2.default)(); - - var reassignmentVisitor = { - "AssignmentExpression|UpdateExpression": function AssignmentExpressionUpdateExpression(path) { - if (path.node[IGNORE_REASSIGNMENT_SYMBOL]) return; - path.node[IGNORE_REASSIGNMENT_SYMBOL] = true; - - var arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); - if (!arg.isIdentifier()) return; - - var name = arg.node.name; - - if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; - - var exportedNames = this.exports[name]; - if (!exportedNames) return; - - var node = path.node; - - var isPostUpdateExpression = path.isUpdateExpression() && !node.prefix; - if (isPostUpdateExpression) { - if (node.operator === "++") node = t.binaryExpression("+", node.argument, t.numericLiteral(1));else if (node.operator === "--") node = t.binaryExpression("-", node.argument, t.numericLiteral(1));else isPostUpdateExpression = false; - } - - for (var _iterator = exportedNames, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref2 = _i.value; - } - - var exportedName = _ref2; - - node = this.buildCall(exportedName, node).expression; - } - - if (isPostUpdateExpression) node = t.sequenceExpression([node, path.node]); - - path.replaceWith(node); - } - }; - - return { - visitor: { - CallExpression: function CallExpression(path, state) { - if (path.node.callee.type === TYPE_IMPORT) { - var contextIdent = state.contextIdent; - path.replaceWith(t.callExpression(t.memberExpression(contextIdent, t.identifier("import")), path.node.arguments)); - } - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.node.name == "__moduleName" && !path.scope.hasBinding("__moduleName")) { - path.replaceWith(t.memberExpression(state.contextIdent, t.identifier("id"))); - } - }, - - - Program: { - enter: function enter(path, state) { - state.contextIdent = path.scope.generateUidIdentifier("context"); - }, - exit: function exit(path, state) { - var exportIdent = path.scope.generateUidIdentifier("export"); - var contextIdent = state.contextIdent; - - var exportNames = (0, _create2.default)(null); - var modules = []; - - var beforeBody = []; - var setters = []; - var sources = []; - var variableIds = []; - var removedPaths = []; - - function addExportName(key, val) { - exportNames[key] = exportNames[key] || []; - exportNames[key].push(val); - } - - function pushModule(source, key, specifiers) { - var module = void 0; - modules.forEach(function (m) { - if (m.key === source) { - module = m; - } - }); - if (!module) { - modules.push(module = { key: source, imports: [], exports: [] }); - } - module[key] = module[key].concat(specifiers); - } - - function buildExportCall(name, val) { - return t.expressionStatement(t.callExpression(exportIdent, [t.stringLiteral(name), val])); - } - - var body = path.get("body"); - - var canHoist = true; - for (var _iterator2 = body, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref3; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref3 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref3 = _i2.value; - } - - var _path = _ref3; - - if (_path.isExportDeclaration()) _path = _path.get("declaration"); - if (_path.isVariableDeclaration() && _path.node.kind !== "var") { - canHoist = false; - break; - } - } - - for (var _iterator3 = body, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref4; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref4 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref4 = _i3.value; - } - - var _path2 = _ref4; - - if (canHoist && _path2.isFunctionDeclaration()) { - beforeBody.push(_path2.node); - removedPaths.push(_path2); - } else if (_path2.isImportDeclaration()) { - var source = _path2.node.source.value; - pushModule(source, "imports", _path2.node.specifiers); - for (var name in _path2.getBindingIdentifiers()) { - _path2.scope.removeBinding(name); - variableIds.push(t.identifier(name)); - } - _path2.remove(); - } else if (_path2.isExportAllDeclaration()) { - pushModule(_path2.node.source.value, "exports", _path2.node); - _path2.remove(); - } else if (_path2.isExportDefaultDeclaration()) { - var declar = _path2.get("declaration"); - if (declar.isClassDeclaration() || declar.isFunctionDeclaration()) { - var id = declar.node.id; - var nodes = []; - - if (id) { - nodes.push(declar.node); - nodes.push(buildExportCall("default", id)); - addExportName(id.name, "default"); - } else { - nodes.push(buildExportCall("default", t.toExpression(declar.node))); - } - - if (!canHoist || declar.isClassDeclaration()) { - _path2.replaceWithMultiple(nodes); - } else { - beforeBody = beforeBody.concat(nodes); - removedPaths.push(_path2); - } - } else { - _path2.replaceWith(buildExportCall("default", declar.node)); - } - } else if (_path2.isExportNamedDeclaration()) { - var _declar = _path2.get("declaration"); - - if (_declar.node) { - _path2.replaceWith(_declar); - - var _nodes = []; - var bindingIdentifiers = void 0; - if (_path2.isFunction()) { - var node = _declar.node; - var _name = node.id.name; - if (canHoist) { - addExportName(_name, _name); - beforeBody.push(node); - beforeBody.push(buildExportCall(_name, node.id)); - removedPaths.push(_path2); - } else { - var _bindingIdentifiers; - - bindingIdentifiers = (_bindingIdentifiers = {}, _bindingIdentifiers[_name] = node.id, _bindingIdentifiers); - } - } else { - bindingIdentifiers = _declar.getBindingIdentifiers(); - } - for (var _name2 in bindingIdentifiers) { - addExportName(_name2, _name2); - _nodes.push(buildExportCall(_name2, t.identifier(_name2))); - } - _path2.insertAfter(_nodes); - } else { - var specifiers = _path2.node.specifiers; - if (specifiers && specifiers.length) { - if (_path2.node.source) { - pushModule(_path2.node.source.value, "exports", specifiers); - _path2.remove(); - } else { - var _nodes2 = []; - - for (var _iterator7 = specifiers, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref8; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref8 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref8 = _i7.value; - } - - var specifier = _ref8; - - _nodes2.push(buildExportCall(specifier.exported.name, specifier.local)); - addExportName(specifier.local.name, specifier.exported.name); - } - - _path2.replaceWithMultiple(_nodes2); - } - } - } - } - } - - modules.forEach(function (specifiers) { - var setterBody = []; - var target = path.scope.generateUidIdentifier(specifiers.key); - - for (var _iterator4 = specifiers.imports, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref5; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref5 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref5 = _i4.value; - } - - var specifier = _ref5; - - if (t.isImportNamespaceSpecifier(specifier)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, target))); - } else if (t.isImportDefaultSpecifier(specifier)) { - specifier = t.importSpecifier(specifier.local, t.identifier("default")); - } - - if (t.isImportSpecifier(specifier)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, t.memberExpression(target, specifier.imported)))); - } - } - - if (specifiers.exports.length) { - var exportObjRef = path.scope.generateUidIdentifier("exportObj"); - - setterBody.push(t.variableDeclaration("var", [t.variableDeclarator(exportObjRef, t.objectExpression([]))])); - - for (var _iterator5 = specifiers.exports, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref6; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref6 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref6 = _i5.value; - } - - var node = _ref6; - - if (t.isExportAllDeclaration(node)) { - setterBody.push(buildExportAll({ - KEY: path.scope.generateUidIdentifier("key"), - EXPORT_OBJ: exportObjRef, - TARGET: target - })); - } else if (t.isExportSpecifier(node)) { - setterBody.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(exportObjRef, node.exported), t.memberExpression(target, node.local)))); - } else {} - } - - setterBody.push(t.expressionStatement(t.callExpression(exportIdent, [exportObjRef]))); - } - - sources.push(t.stringLiteral(specifiers.key)); - setters.push(t.functionExpression(null, [target], t.blockStatement(setterBody))); - }); - - var moduleName = this.getModuleName(); - if (moduleName) moduleName = t.stringLiteral(moduleName); - - if (canHoist) { - (0, _babelHelperHoistVariables2.default)(path, function (id) { - return variableIds.push(id); - }); - } - - if (variableIds.length) { - beforeBody.unshift(t.variableDeclaration("var", variableIds.map(function (id) { - return t.variableDeclarator(id); - }))); - } - - path.traverse(reassignmentVisitor, { - exports: exportNames, - buildCall: buildExportCall, - scope: path.scope - }); - - for (var _iterator6 = removedPaths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref7; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref7 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref7 = _i6.value; - } - - var _path3 = _ref7; - - _path3.remove(); - } - - path.node.body = [buildTemplate({ - SYSTEM_REGISTER: t.memberExpression(t.identifier(state.opts.systemGlobal || "System"), t.identifier("register")), - BEFORE_BODY: beforeBody, - MODULE_NAME: moduleName, - SETTERS: setters, - SOURCES: sources, - BODY: path.node.body, - EXPORT_IDENTIFIER: exportIdent, - CONTEXT_IDENTIFIER: contextIdent - })]; - } - } - } - }; -}; - -var _babelHelperHoistVariables = require("babel-helper-hoist-variables"); - -var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); - -var _babelTemplate = require("babel-template"); - -var _babelTemplate2 = _interopRequireDefault(_babelTemplate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var buildTemplate = (0, _babelTemplate2.default)("\n SYSTEM_REGISTER(MODULE_NAME, [SOURCES], function (EXPORT_IDENTIFIER, CONTEXT_IDENTIFIER) {\n \"use strict\";\n BEFORE_BODY;\n return {\n setters: [SETTERS],\n execute: function () {\n BODY;\n }\n };\n });\n"); - -var buildExportAll = (0, _babelTemplate2.default)("\n for (var KEY in TARGET) {\n if (KEY !== \"default\" && KEY !== \"__esModule\") EXPORT_OBJ[KEY] = TARGET[KEY];\n }\n"); - -var TYPE_IMPORT = "Import"; - -module.exports = exports["default"]; -},{"babel-helper-hoist-variables":50,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/object/create":61,"babel-runtime/core-js/symbol":65,"babel-template":75}],56:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; -},{"core-js/library/fn/get-iterator":125}],57:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true }; -},{"core-js/library/fn/json/stringify":126}],58:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/map"), __esModule: true }; -},{"core-js/library/fn/map":127}],59:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/number/max-safe-integer"), __esModule: true }; -},{"core-js/library/fn/number/max-safe-integer":128}],60:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; -},{"core-js/library/fn/object/assign":129}],61:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; -},{"core-js/library/fn/object/create":130}],62:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/get-own-property-symbols"), __esModule: true }; -},{"core-js/library/fn/object/get-own-property-symbols":131}],63:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; -},{"core-js/library/fn/object/keys":132}],64:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; -},{"core-js/library/fn/object/set-prototype-of":133}],65:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; -},{"core-js/library/fn/symbol":135}],66:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/for"), __esModule: true }; -},{"core-js/library/fn/symbol/for":134}],67:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; -},{"core-js/library/fn/symbol/iterator":136}],68:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-map"), __esModule: true }; -},{"core-js/library/fn/weak-map":137}],69:[function(require,module,exports){ -module.exports = { "default": require("core-js/library/fn/weak-set"), __esModule: true }; -},{"core-js/library/fn/weak-set":138}],70:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; -},{}],71:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _setPrototypeOf = require("../core-js/object/set-prototype-of"); - -var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); - -var _create = require("../core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _typeof2 = require("../helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); - } - - subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; -}; -},{"../core-js/object/create":61,"../core-js/object/set-prototype-of":64,"../helpers/typeof":74}],72:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -exports.default = function (obj, keys) { - var target = {}; - - for (var i in obj) { - if (keys.indexOf(i) >= 0) continue; - if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; - target[i] = obj[i]; - } - - return target; -}; -},{}],73:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("../helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; -}; -},{"../helpers/typeof":74}],74:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _iterator = require("../core-js/symbol/iterator"); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _symbol = require("../core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { - return typeof obj === "undefined" ? "undefined" : _typeof(obj); -} : function (obj) { - return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); -}; -},{"../core-js/symbol":65,"../core-js/symbol/iterator":67}],75:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _symbol = require("babel-runtime/core-js/symbol"); - -var _symbol2 = _interopRequireDefault(_symbol); - -exports.default = function (code, opts) { - var stack = void 0; - try { - throw new Error(); - } catch (error) { - if (error.stack) { - stack = error.stack.split("\n").slice(1).join("\n"); - } - } - - opts = (0, _assign2.default)({ - allowReturnOutsideFunction: true, - allowSuperOutsideMethod: true, - preserveComments: false - }, opts); - - var _getAst = function getAst() { - var ast = void 0; - - try { - ast = babylon.parse(code, opts); - - ast = _babelTraverse2.default.removeProperties(ast, { preserveComments: opts.preserveComments }); - - _babelTraverse2.default.cheap(ast, function (node) { - node[FROM_TEMPLATE] = true; - }); - } catch (err) { - err.stack = err.stack + "from\n" + stack; - throw err; - } - - _getAst = function getAst() { - return ast; - }; - - return ast; - }; - - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return useTemplate(_getAst(), args); - }; -}; - -var _cloneDeep = require("lodash/cloneDeep"); - -var _cloneDeep2 = _interopRequireDefault(_cloneDeep); - -var _assign = require("lodash/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _has = require("lodash/has"); - -var _has2 = _interopRequireDefault(_has); - -var _babelTraverse = require("babel-traverse"); - -var _babelTraverse2 = _interopRequireDefault(_babelTraverse); - -var _babylon = require("babylon"); - -var babylon = _interopRequireWildcard(_babylon); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var FROM_TEMPLATE = "_fromTemplate"; -var TEMPLATE_SKIP = (0, _symbol2.default)(); - -function useTemplate(ast, nodes) { - ast = (0, _cloneDeep2.default)(ast); - var _ast = ast, - program = _ast.program; - - - if (nodes.length) { - (0, _babelTraverse2.default)(ast, templateVisitor, null, nodes); - } - - if (program.body.length > 1) { - return program.body; - } else { - return program.body[0]; - } -} - -var templateVisitor = { - noScope: true, - - enter: function enter(path, args) { - var node = path.node; - - if (node[TEMPLATE_SKIP]) return path.skip(); - - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - var replacement = void 0; - - if (t.isIdentifier(node) && node[FROM_TEMPLATE]) { - if ((0, _has2.default)(args[0], node.name)) { - replacement = args[0][node.name]; - } else if (node.name[0] === "$") { - var i = +node.name.slice(1); - if (args[i]) replacement = args[i]; - } - } - - if (replacement === null) { - path.remove(); - } - - if (replacement) { - replacement[TEMPLATE_SKIP] = true; - path.replaceInline(replacement); - } - }, - exit: function exit(_ref) { - var node = _ref.node; - - if (!node.loc) _babelTraverse2.default.clearNode(node); - } -}; -module.exports = exports["default"]; -},{"babel-runtime/core-js/symbol":65,"babel-traverse":79,"babel-types":112,"babylon":116,"lodash/assign":414,"lodash/cloneDeep":417,"lodash/has":428}],76:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.scope = exports.path = undefined; - -var _weakMap = require("babel-runtime/core-js/weak-map"); - -var _weakMap2 = _interopRequireDefault(_weakMap); - -exports.clear = clear; -exports.clearPath = clearPath; -exports.clearScope = clearScope; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var path = exports.path = new _weakMap2.default(); -var scope = exports.scope = new _weakMap2.default(); - -function clear() { - clearPath(); - clearScope(); -} - -function clearPath() { - exports.path = path = new _weakMap2.default(); -} - -function clearScope() { - exports.scope = scope = new _weakMap2.default(); -} -},{"babel-runtime/core-js/weak-map":68}],77:[function(require,module,exports){ -(function (process){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _path2 = require("./path"); - -var _path3 = _interopRequireDefault(_path2); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var testing = process.env.NODE_ENV === "test"; - -var TraversalContext = function () { - function TraversalContext(scope, opts, state, parentPath) { - (0, _classCallCheck3.default)(this, TraversalContext); - this.queue = null; - - this.parentPath = parentPath; - this.scope = scope; - this.state = state; - this.opts = opts; - } - - TraversalContext.prototype.shouldVisit = function shouldVisit(node) { - var opts = this.opts; - if (opts.enter || opts.exit) return true; - - if (opts[node.type]) return true; - - var keys = t.VISITOR_KEYS[node.type]; - if (!keys || !keys.length) return false; - - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var key = _ref; - - if (node[key]) return true; - } - - return false; - }; - - TraversalContext.prototype.create = function create(node, obj, key, listKey) { - return _path3.default.get({ - parentPath: this.parentPath, - parent: node, - container: obj, - key: key, - listKey: listKey - }); - }; - - TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) { - if (this.trap) { - throw new Error("Infinite cycle detected"); - } - - if (this.queue) { - if (notPriority) { - this.queue.push(path); - } else { - this.priorityQueue.push(path); - } - } - }; - - TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { - if (container.length === 0) return false; - - var queue = []; - - for (var key = 0; key < container.length; key++) { - var node = container[key]; - if (node && this.shouldVisit(node)) { - queue.push(this.create(parent, container, key, listKey)); - } - } - - return this.visitQueue(queue); - }; - - TraversalContext.prototype.visitSingle = function visitSingle(node, key) { - if (this.shouldVisit(node[key])) { - return this.visitQueue([this.create(node, node, key)]); - } else { - return false; - } - }; - - TraversalContext.prototype.visitQueue = function visitQueue(queue) { - this.queue = queue; - this.priorityQueue = []; - - var visited = []; - var stop = false; - - for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var path = _ref2; - - path.resync(); - - if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { - path.pushContext(this); - } - - if (path.key === null) continue; - - if (testing && queue.length >= 10000) { - this.trap = true; - } - - if (visited.indexOf(path.node) >= 0) continue; - visited.push(path.node); - - if (path.visit()) { - stop = true; - break; - } - - if (this.priorityQueue.length) { - stop = this.visitQueue(this.priorityQueue); - this.priorityQueue = []; - this.queue = queue; - if (stop) break; - } - } - - for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var _path = _ref3; - - _path.popContext(); - } - - this.queue = null; - - return stop; - }; - - TraversalContext.prototype.visit = function visit(node, key) { - var nodes = node[key]; - if (!nodes) return false; - - if (Array.isArray(nodes)) { - return this.visitMultiple(nodes, node, key); - } else { - return this.visitSingle(node, key); - } - }; - - return TraversalContext; -}(); - -exports.default = TraversalContext; -module.exports = exports["default"]; -}).call(this,require('_process')) -},{"./path":86,"_process":471,"babel-runtime/core-js/get-iterator":56,"babel-runtime/helpers/classCallCheck":70,"babel-types":112}],78:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Hub = function Hub(file, options) { - (0, _classCallCheck3.default)(this, Hub); - - this.file = file; - this.options = options; -}; - -exports.default = Hub; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":70}],79:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _path = require("./path"); - -Object.defineProperty(exports, "NodePath", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_path).default; - } -}); - -var _scope = require("./scope"); - -Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_scope).default; - } -}); - -var _hub = require("./hub"); - -Object.defineProperty(exports, "Hub", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_hub).default; - } -}); -exports.default = traverse; - -var _context = require("./context"); - -var _context2 = _interopRequireDefault(_context); - -var _visitors = require("./visitors"); - -var visitors = _interopRequireWildcard(_visitors); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("./cache"); - -var cache = _interopRequireWildcard(_cache); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.visitors = visitors; -function traverse(parent, opts, scope, state, parentPath) { - if (!parent) return; - if (!opts) opts = {}; - - if (!opts.noScope && !scope) { - if (parent.type !== "Program" && parent.type !== "File") { - throw new Error(messages.get("traverseNeedsParent", parent.type)); - } - } - - visitors.explode(opts); - - traverse.node(parent, opts, scope, state, parentPath); -} - -traverse.visitors = visitors; -traverse.verify = visitors.verify; -traverse.explode = visitors.explode; - -traverse.NodePath = require("./path"); -traverse.Scope = require("./scope"); -traverse.Hub = require("./hub"); - -traverse.cheap = function (node, enter) { - return t.traverseFast(node, enter); -}; - -traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; - - var context = new _context2.default(scope, opts, state, parentPath); - for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var key = _ref; - - if (skipKeys && skipKeys[key]) continue; - if (context.visit(node, key)) return; - } -}; - -traverse.clearNode = function (node, opts) { - t.removeProperties(node, opts); - - cache.path.delete(node); -}; - -traverse.removeProperties = function (tree, opts) { - t.traverseFast(tree, traverse.clearNode, opts); - return tree; -}; - -function hasBlacklistedType(path, state) { - if (path.node.type === state.type) { - state.has = true; - path.stop(); - } -} - -traverse.hasType = function (tree, scope, type, blacklistTypes) { - if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; - - if (tree.type === type) return true; - - var state = { - has: false, - type: type - }; - - traverse(tree, { - blacklist: blacklistTypes, - enter: hasBlacklistedType - }, scope, state); - - return state.has; -}; - -traverse.clearCache = function () { - cache.clear(); -}; - -traverse.clearCache.clearPath = cache.clearPath; -traverse.clearCache.clearScope = cache.clearScope; - -traverse.copyCache = function (source, destination) { - if (cache.path.has(source)) { - cache.path.set(destination, cache.path.get(source)); - } -}; -},{"./cache":76,"./context":77,"./hub":78,"./path":86,"./scope":98,"./visitors":100,"babel-messages":53,"babel-runtime/core-js/get-iterator":56,"babel-types":112,"lodash/includes":431}],80:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.findParent = findParent; -exports.find = find; -exports.getFunctionParent = getFunctionParent; -exports.getStatementParent = getStatementParent; -exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; -exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; -exports.getAncestry = getAncestry; -exports.isAncestor = isAncestor; -exports.isDescendant = isDescendant; -exports.inType = inType; -exports.inShadow = inShadow; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function findParent(callback) { - var path = this; - while (path = path.parentPath) { - if (callback(path)) return path; - } - return null; -} - -function find(callback) { - var path = this; - do { - if (callback(path)) return path; - } while (path = path.parentPath); - return null; -} - -function getFunctionParent() { - return this.findParent(function (path) { - return path.isFunction() || path.isProgram(); - }); -} - -function getStatementParent() { - var path = this; - do { - if (Array.isArray(path.container)) { - return path; - } - } while (path = path.parentPath); -} - -function getEarliestCommonAncestorFrom(paths) { - return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { - var earliest = void 0; - var keys = t.VISITOR_KEYS[deepest.type]; - - for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var ancestry = _ref; - - var path = ancestry[i + 1]; - - if (!earliest) { - earliest = path; - continue; - } - - if (path.listKey && earliest.listKey === path.listKey) { - if (path.key < earliest.key) { - earliest = path; - continue; - } - } - - var earliestKeyIndex = keys.indexOf(earliest.parentKey); - var currentKeyIndex = keys.indexOf(path.parentKey); - if (earliestKeyIndex > currentKeyIndex) { - earliest = path; - } - } - - return earliest; - }); -} - -function getDeepestCommonAncestorFrom(paths, filter) { - var _this = this; - - if (!paths.length) { - return this; - } - - if (paths.length === 1) { - return paths[0]; - } - - var minDepth = Infinity; - - var lastCommonIndex = void 0, - lastCommon = void 0; - - var ancestries = paths.map(function (path) { - var ancestry = []; - - do { - ancestry.unshift(path); - } while ((path = path.parentPath) && path !== _this); - - if (ancestry.length < minDepth) { - minDepth = ancestry.length; - } - - return ancestry; - }); - - var first = ancestries[0]; - - depthLoop: for (var i = 0; i < minDepth; i++) { - var shouldMatch = first[i]; - - for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var ancestry = _ref2; - - if (ancestry[i] !== shouldMatch) { - break depthLoop; - } - } - - lastCommonIndex = i; - lastCommon = shouldMatch; - } - - if (lastCommon) { - if (filter) { - return filter(lastCommon, lastCommonIndex, ancestries); - } else { - return lastCommon; - } - } else { - throw new Error("Couldn't find intersection"); - } -} - -function getAncestry() { - var path = this; - var paths = []; - do { - paths.push(path); - } while (path = path.parentPath); - return paths; -} - -function isAncestor(maybeDescendant) { - return maybeDescendant.isDescendant(this); -} - -function isDescendant(maybeAncestor) { - return !!this.findParent(function (parent) { - return parent === maybeAncestor; - }); -} - -function inType() { - var path = this; - while (path) { - for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var type = _ref3; - - if (path.node.type === type) return true; - } - path = path.parentPath; - } - - return false; -} - -function inShadow(key) { - var parentFn = this.isFunction() ? this : this.findParent(function (p) { - return p.isFunction(); - }); - if (!parentFn) return; - - if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { - var shadow = parentFn.node.shadow; - - if (shadow && (!key || shadow[key] !== false)) { - return parentFn; - } - } else if (parentFn.isArrowFunctionExpression()) { - return parentFn; - } - - return null; -} -},{"./index":86,"babel-runtime/core-js/get-iterator":56,"babel-types":112}],81:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.shareCommentsWithSiblings = shareCommentsWithSiblings; -exports.addComment = addComment; -exports.addComments = addComments; -function shareCommentsWithSiblings() { - if (typeof this.key === "string") return; - - var node = this.node; - if (!node) return; - - var trailing = node.trailingComments; - var leading = node.leadingComments; - if (!trailing && !leading) return; - - var prev = this.getSibling(this.key - 1); - var next = this.getSibling(this.key + 1); - - if (!prev.node) prev = next; - if (!next.node) next = prev; - - prev.addComments("trailing", leading); - next.addComments("leading", trailing); -} - -function addComment(type, content, line) { - this.addComments(type, [{ - type: line ? "CommentLine" : "CommentBlock", - value: content - }]); -} - -function addComments(type, comments) { - if (!comments) return; - - var node = this.node; - if (!node) return; - - var key = type + "Comments"; - - if (node[key]) { - node[key] = node[key].concat(comments); - } else { - node[key] = comments; - } -} -},{}],82:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.call = call; -exports._call = _call; -exports.isBlacklisted = isBlacklisted; -exports.visit = visit; -exports.skip = skip; -exports.skipKey = skipKey; -exports.stop = stop; -exports.setScope = setScope; -exports.setContext = setContext; -exports.resync = resync; -exports._resyncParent = _resyncParent; -exports._resyncKey = _resyncKey; -exports._resyncList = _resyncList; -exports._resyncRemoved = _resyncRemoved; -exports.popContext = popContext; -exports.pushContext = pushContext; -exports.setup = setup; -exports.setKey = setKey; -exports.requeue = requeue; -exports._getQueueContexts = _getQueueContexts; - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function call(key) { - var opts = this.opts; - - this.debug(function () { - return key; - }); - - if (this.node) { - if (this._call(opts[key])) return true; - } - - if (this.node) { - return this._call(opts[this.node.type] && opts[this.node.type][key]); - } - - return false; -} - -function _call(fns) { - if (!fns) return false; - - for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var fn = _ref; - - if (!fn) continue; - - var node = this.node; - if (!node) return true; - - var ret = fn.call(this.state, this, this.state); - if (ret) throw new Error("Unexpected return value from visitor method " + fn); - - if (this.node !== node) return true; - - if (this.shouldStop || this.shouldSkip || this.removed) return true; - } - - return false; -} - -function isBlacklisted() { - var blacklist = this.opts.blacklist; - return blacklist && blacklist.indexOf(this.node.type) > -1; -} - -function visit() { - if (!this.node) { - return false; - } - - if (this.isBlacklisted()) { - return false; - } - - if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { - return false; - } - - if (this.call("enter") || this.shouldSkip) { - this.debug(function () { - return "Skip..."; - }); - return this.shouldStop; - } - - this.debug(function () { - return "Recursing into..."; - }); - _index2.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys); - - this.call("exit"); - - return this.shouldStop; -} - -function skip() { - this.shouldSkip = true; -} - -function skipKey(key) { - this.skipKeys[key] = true; -} - -function stop() { - this.shouldStop = true; - this.shouldSkip = true; -} - -function setScope() { - if (this.opts && this.opts.noScope) return; - - var target = this.context && this.context.scope; - - if (!target) { - var path = this.parentPath; - while (path && !target) { - if (path.opts && path.opts.noScope) return; - - target = path.scope; - path = path.parentPath; - } - } - - this.scope = this.getScope(target); - if (this.scope) this.scope.init(); -} - -function setContext(context) { - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.skipKeys = {}; - - if (context) { - this.context = context; - this.state = context.state; - this.opts = context.opts; - } - - this.setScope(); - - return this; -} - -function resync() { - if (this.removed) return; - - this._resyncParent(); - this._resyncList(); - this._resyncKey(); -} - -function _resyncParent() { - if (this.parentPath) { - this.parent = this.parentPath.node; - } -} - -function _resyncKey() { - if (!this.container) return; - - if (this.node === this.container[this.key]) return; - - if (Array.isArray(this.container)) { - for (var i = 0; i < this.container.length; i++) { - if (this.container[i] === this.node) { - return this.setKey(i); - } - } - } else { - for (var key in this.container) { - if (this.container[key] === this.node) { - return this.setKey(key); - } - } - } - - this.key = null; -} - -function _resyncList() { - if (!this.parent || !this.inList) return; - - var newContainer = this.parent[this.listKey]; - if (this.container === newContainer) return; - - this.container = newContainer || null; -} - -function _resyncRemoved() { - if (this.key == null || !this.container || this.container[this.key] !== this.node) { - this._markRemoved(); - } -} - -function popContext() { - this.contexts.pop(); - this.setContext(this.contexts[this.contexts.length - 1]); -} - -function pushContext(context) { - this.contexts.push(context); - this.setContext(context); -} - -function setup(parentPath, container, listKey, key) { - this.inList = !!listKey; - this.listKey = listKey; - this.parentKey = listKey || key; - this.container = container; - - this.parentPath = parentPath || this.parentPath; - this.setKey(key); -} - -function setKey(key) { - this.key = key; - this.node = this.container[this.key]; - this.type = this.node && this.node.type; -} - -function requeue() { - var pathToQueue = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this; - - if (pathToQueue.removed) return; - - var contexts = this.contexts; - - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var context = _ref2; - - context.maybeQueue(pathToQueue); - } -} - -function _getQueueContexts() { - var path = this; - var contexts = this.contexts; - while (!contexts.length) { - path = path.parentPath; - contexts = path.contexts; - } - return contexts; -} -},{"../index":79,"babel-runtime/core-js/get-iterator":56}],83:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.toComputedKey = toComputedKey; -exports.ensureBlock = ensureBlock; -exports.arrowFunctionToShadowed = arrowFunctionToShadowed; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function toComputedKey() { - var node = this.node; - - var key = void 0; - if (this.isMemberExpression()) { - key = node.property; - } else if (this.isProperty() || this.isMethod()) { - key = node.key; - } else { - throw new ReferenceError("todo"); - } - - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } - - return key; -} - -function ensureBlock() { - return t.ensureBlock(this.node); -} - -function arrowFunctionToShadowed() { - if (!this.isArrowFunctionExpression()) return; - - this.ensureBlock(); - - var node = this.node; - - node.expression = false; - node.type = "FunctionExpression"; - node.shadow = node.shadow || true; -} -},{"babel-types":112}],84:[function(require,module,exports){ -(function (global){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -exports.evaluateTruthy = evaluateTruthy; -exports.evaluate = evaluate; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var VALID_CALLEES = ["String", "Number", "Math"]; -var INVALID_METHODS = ["random"]; - -function evaluateTruthy() { - var res = this.evaluate(); - if (res.confident) return !!res.value; -} - -function evaluate() { - var confident = true; - var deoptPath = void 0; - var seen = new _map2.default(); - - function deopt(path) { - if (!confident) return; - deoptPath = path; - confident = false; - } - - var value = evaluate(this); - if (!confident) value = undefined; - return { - confident: confident, - deopt: deoptPath, - value: value - }; - - function evaluate(path) { - var node = path.node; - - - if (seen.has(node)) { - var existing = seen.get(node); - if (existing.resolved) { - return existing.value; - } else { - deopt(path); - return; - } - } else { - var item = { resolved: false }; - seen.set(node, item); - - var val = _evaluate(path); - if (confident) { - item.resolved = true; - item.value = val; - } - return val; - } - } - - function _evaluate(path) { - if (!confident) return; - - var node = path.node; - - - if (path.isSequenceExpression()) { - var exprs = path.get("expressions"); - return evaluate(exprs[exprs.length - 1]); - } - - if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { - return node.value; - } - - if (path.isNullLiteral()) { - return null; - } - - if (path.isTemplateLiteral()) { - var str = ""; - - var i = 0; - var _exprs = path.get("expressions"); - - for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var elem = _ref; - - if (!confident) break; - - str += elem.value.cooked; - - var expr = _exprs[i++]; - if (expr) str += String(evaluate(expr)); - } - - if (!confident) return; - return str; - } - - if (path.isConditionalExpression()) { - var testResult = evaluate(path.get("test")); - if (!confident) return; - if (testResult) { - return evaluate(path.get("consequent")); - } else { - return evaluate(path.get("alternate")); - } - } - - if (path.isExpressionWrapper()) { - return evaluate(path.get("expression")); - } - - if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { - var property = path.get("property"); - var object = path.get("object"); - - if (object.isLiteral() && property.isIdentifier()) { - var _value = object.node.value; - var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value); - if (type === "number" || type === "string") { - return _value[property.node.name]; - } - } - } - - if (path.isReferencedIdentifier()) { - var binding = path.scope.getBinding(node.name); - - if (binding && binding.constantViolations.length > 0) { - return deopt(binding.path); - } - - if (binding && path.node.start < binding.path.node.end) { - return deopt(binding.path); - } - - if (binding && binding.hasValue) { - return binding.value; - } else { - if (node.name === "undefined") { - return binding ? deopt(binding.path) : undefined; - } else if (node.name === "Infinity") { - return binding ? deopt(binding.path) : Infinity; - } else if (node.name === "NaN") { - return binding ? deopt(binding.path) : NaN; - } - - var resolved = path.resolve(); - if (resolved === path) { - return deopt(path); - } else { - return evaluate(resolved); - } - } - } - - if (path.isUnaryExpression({ prefix: true })) { - if (node.operator === "void") { - return undefined; - } - - var argument = path.get("argument"); - if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { - return "function"; - } - - var arg = evaluate(argument); - if (!confident) return; - switch (node.operator) { - case "!": - return !arg; - case "+": - return +arg; - case "-": - return -arg; - case "~": - return ~arg; - case "typeof": - return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg); - } - } - - if (path.isArrayExpression()) { - var arr = []; - var elems = path.get("elements"); - for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _elem = _ref2; - - _elem = _elem.evaluate(); - - if (_elem.confident) { - arr.push(_elem.value); - } else { - return deopt(_elem); - } - } - return arr; - } - - if (path.isObjectExpression()) { - var obj = {}; - var props = path.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var prop = _ref3; - - if (prop.isObjectMethod() || prop.isSpreadProperty()) { - return deopt(prop); - } - var keyPath = prop.get("key"); - var key = keyPath; - if (prop.node.computed) { - key = key.evaluate(); - if (!key.confident) { - return deopt(keyPath); - } - key = key.value; - } else if (key.isIdentifier()) { - key = key.node.name; - } else { - key = key.node.value; - } - var valuePath = prop.get("value"); - var _value2 = valuePath.evaluate(); - if (!_value2.confident) { - return deopt(valuePath); - } - _value2 = _value2.value; - obj[key] = _value2; - } - return obj; - } - - if (path.isLogicalExpression()) { - var wasConfident = confident; - var left = evaluate(path.get("left")); - var leftConfident = confident; - confident = wasConfident; - var right = evaluate(path.get("right")); - var rightConfident = confident; - confident = leftConfident && rightConfident; - - switch (node.operator) { - case "||": - if (left && leftConfident) { - confident = true; - return left; - } - - if (!confident) return; - - return left || right; - case "&&": - if (!left && leftConfident || !right && rightConfident) { - confident = true; - } - - if (!confident) return; - - return left && right; - } - } - - if (path.isBinaryExpression()) { - var _left = evaluate(path.get("left")); - if (!confident) return; - var _right = evaluate(path.get("right")); - if (!confident) return; - - switch (node.operator) { - case "-": - return _left - _right; - case "+": - return _left + _right; - case "/": - return _left / _right; - case "*": - return _left * _right; - case "%": - return _left % _right; - case "**": - return Math.pow(_left, _right); - case "<": - return _left < _right; - case ">": - return _left > _right; - case "<=": - return _left <= _right; - case ">=": - return _left >= _right; - case "==": - return _left == _right; - case "!=": - return _left != _right; - case "===": - return _left === _right; - case "!==": - return _left !== _right; - case "|": - return _left | _right; - case "&": - return _left & _right; - case "^": - return _left ^ _right; - case "<<": - return _left << _right; - case ">>": - return _left >> _right; - case ">>>": - return _left >>> _right; - } - } - - if (path.isCallExpression()) { - var callee = path.get("callee"); - var context = void 0; - var func = void 0; - - if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { - func = global[node.callee.name]; - } - - if (callee.isMemberExpression()) { - var _object = callee.get("object"); - var _property = callee.get("property"); - - if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) { - context = global[_object.node.name]; - func = context[_property.node.name]; - } - - if (_object.isLiteral() && _property.isIdentifier()) { - var _type = (0, _typeof3.default)(_object.node.value); - if (_type === "string" || _type === "number") { - context = _object.node.value; - func = context[_property.node.name]; - } - } - } - - if (func) { - var args = path.get("arguments").map(evaluate); - if (!confident) return; - - return func.apply(context, args); - } - } - - deopt(path); - } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/map":58,"babel-runtime/helpers/typeof":74}],85:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.getStatementParent = getStatementParent; -exports.getOpposite = getOpposite; -exports.getCompletionRecords = getCompletionRecords; -exports.getSibling = getSibling; -exports.getPrevSibling = getPrevSibling; -exports.getNextSibling = getNextSibling; -exports.getAllNextSiblings = getAllNextSiblings; -exports.getAllPrevSiblings = getAllPrevSiblings; -exports.get = get; -exports._getKey = _getKey; -exports._getPattern = _getPattern; -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; -exports.getBindingIdentifierPaths = getBindingIdentifierPaths; -exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getStatementParent() { - var path = this; - - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { - break; - } else { - path = path.parentPath; - } - } while (path); - - if (path && (path.isProgram() || path.isFile())) { - throw new Error("File/Program node, we can't possibly find a statement parent to this"); - } - - return path; -} - -function getOpposite() { - if (this.key === "left") { - return this.getSibling("right"); - } else if (this.key === "right") { - return this.getSibling("left"); - } -} - -function getCompletionRecords() { - var paths = []; - - var add = function add(path) { - if (path) paths = paths.concat(path.getCompletionRecords()); - }; - - if (this.isIfStatement()) { - add(this.get("consequent")); - add(this.get("alternate")); - } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { - add(this.get("body")); - } else if (this.isProgram() || this.isBlockStatement()) { - add(this.get("body").pop()); - } else if (this.isFunction()) { - return this.get("body").getCompletionRecords(); - } else if (this.isTryStatement()) { - add(this.get("block")); - add(this.get("handler")); - add(this.get("finalizer")); - } else { - paths.push(this); - } - - return paths; -} - -function getSibling(key) { - return _index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: key - }); -} - -function getPrevSibling() { - return this.getSibling(this.key - 1); -} - -function getNextSibling() { - return this.getSibling(this.key + 1); -} - -function getAllNextSiblings() { - var _key = this.key; - var sibling = this.getSibling(++_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(++_key); - } - return siblings; -} - -function getAllPrevSiblings() { - var _key = this.key; - var sibling = this.getSibling(--_key); - var siblings = []; - while (sibling.node) { - siblings.push(sibling); - sibling = this.getSibling(--_key); - } - return siblings; -} - -function get(key, context) { - if (context === true) context = this.context; - var parts = key.split("."); - if (parts.length === 1) { - return this._getKey(key, context); - } else { - return this._getPattern(parts, context); - } -} - -function _getKey(key, context) { - var _this = this; - - var node = this.node; - var container = node[key]; - - if (Array.isArray(container)) { - return container.map(function (_, i) { - return _index2.default.get({ - listKey: key, - parentPath: _this, - parent: node, - container: container, - key: i - }).setContext(context); - }); - } else { - return _index2.default.get({ - parentPath: this, - parent: node, - container: node, - key: key - }).setContext(context); - } -} - -function _getPattern(parts, context) { - var path = this; - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var part = _ref; - - if (part === ".") { - path = path.parentPath; - } else { - if (Array.isArray(path)) { - path = path[part]; - } else { - path = path.get(part, context); - } - } - } - return path; -} - -function getBindingIdentifiers(duplicates) { - return t.getBindingIdentifiers(this.node, duplicates); -} - -function getOuterBindingIdentifiers(duplicates) { - return t.getOuterBindingIdentifiers(this.node, duplicates); -} - -function getBindingIdentifierPaths() { - var duplicates = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var outerOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - var path = this; - var search = [].concat(path); - var ids = (0, _create2.default)(null); - - while (search.length) { - var id = search.shift(); - if (!id) continue; - if (!id.node) continue; - - var keys = t.getBindingIdentifiers.keys[id.node.type]; - - if (id.isIdentifier()) { - if (duplicates) { - var _ids = ids[id.node.name] = ids[id.node.name] || []; - _ids.push(id); - } else { - ids[id.node.name] = id; - } - continue; - } - - if (id.isExportDeclaration()) { - var declaration = id.get("declaration"); - if (declaration.isDeclaration()) { - search.push(declaration); - } - continue; - } - - if (outerOnly) { - if (id.isFunctionDeclaration()) { - search.push(id.get("id")); - continue; - } - if (id.isFunctionExpression()) { - continue; - } - } - - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var child = id.get(key); - if (Array.isArray(child) || child.node) { - search = search.concat(child); - } - } - } - } - - return ids; -} - -function getOuterBindingIdentifierPaths(duplicates) { - return this.getBindingIdentifierPaths(duplicates, true); -} -},{"./index":86,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/object/create":61,"babel-types":112}],86:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _virtualTypes = require("./lib/virtual-types"); - -var virtualTypes = _interopRequireWildcard(_virtualTypes); - -var _debug2 = require("debug"); - -var _debug3 = _interopRequireDefault(_debug2); - -var _invariant = require("invariant"); - -var _invariant2 = _interopRequireDefault(_invariant); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _assign = require("lodash/assign"); - -var _assign2 = _interopRequireDefault(_assign); - -var _scope = require("../scope"); - -var _scope2 = _interopRequireDefault(_scope); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("../cache"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _debug = (0, _debug3.default)("babel"); - -var NodePath = function () { - function NodePath(hub, parent) { - (0, _classCallCheck3.default)(this, NodePath); - - this.parent = parent; - this.hub = hub; - this.contexts = []; - this.data = {}; - this.shouldSkip = false; - this.shouldStop = false; - this.removed = false; - this.state = null; - this.opts = null; - this.skipKeys = null; - this.parentPath = null; - this.context = null; - this.container = null; - this.listKey = null; - this.inList = false; - this.parentKey = null; - this.key = null; - this.node = null; - this.scope = null; - this.type = null; - this.typeAnnotation = null; - } - - NodePath.get = function get(_ref) { - var hub = _ref.hub, - parentPath = _ref.parentPath, - parent = _ref.parent, - container = _ref.container, - listKey = _ref.listKey, - key = _ref.key; - - if (!hub && parentPath) { - hub = parentPath.hub; - } - - (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); - - var targetNode = container[key]; - - var paths = _cache.path.get(parent) || []; - if (!_cache.path.has(parent)) { - _cache.path.set(parent, paths); - } - - var path = void 0; - - for (var i = 0; i < paths.length; i++) { - var pathCheck = paths[i]; - if (pathCheck.node === targetNode) { - path = pathCheck; - break; - } - } - - if (!path) { - path = new NodePath(hub, parent); - paths.push(path); - } - - path.setup(parentPath, container, listKey, key); - - return path; - }; - - NodePath.prototype.getScope = function getScope(scope) { - var ourScope = scope; - - if (this.isScope()) { - ourScope = new _scope2.default(this, scope); - } - - return ourScope; - }; - - NodePath.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; - - NodePath.prototype.getData = function getData(key, def) { - var val = this.data[key]; - if (!val && def) val = this.data[key] = def; - return val; - }; - - NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { - var Error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SyntaxError; - - return this.hub.file.buildCodeFrameError(this.node, msg, Error); - }; - - NodePath.prototype.traverse = function traverse(visitor, state) { - (0, _index2.default)(this.node, visitor, this.scope, state, this); - }; - - NodePath.prototype.mark = function mark(type, message) { - this.hub.file.metadata.marked.push({ - type: type, - message: message, - loc: this.node.loc - }); - }; - - NodePath.prototype.set = function set(key, node) { - t.validate(this.node, key, node); - this.node[key] = node; - }; - - NodePath.prototype.getPathLocation = function getPathLocation() { - var parts = []; - var path = this; - do { - var key = path.key; - if (path.inList) key = path.listKey + "[" + key + "]"; - parts.unshift(key); - } while (path = path.parentPath); - return parts.join("."); - }; - - NodePath.prototype.debug = function debug(buildMessage) { - if (!_debug.enabled) return; - _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); - }; - - return NodePath; -}(); - -exports.default = NodePath; - - -(0, _assign2.default)(NodePath.prototype, require("./ancestry")); -(0, _assign2.default)(NodePath.prototype, require("./inference")); -(0, _assign2.default)(NodePath.prototype, require("./replacement")); -(0, _assign2.default)(NodePath.prototype, require("./evaluation")); -(0, _assign2.default)(NodePath.prototype, require("./conversion")); -(0, _assign2.default)(NodePath.prototype, require("./introspection")); -(0, _assign2.default)(NodePath.prototype, require("./context")); -(0, _assign2.default)(NodePath.prototype, require("./removal")); -(0, _assign2.default)(NodePath.prototype, require("./modification")); -(0, _assign2.default)(NodePath.prototype, require("./family")); -(0, _assign2.default)(NodePath.prototype, require("./comments")); - -var _loop2 = function _loop2() { - if (_isArray) { - if (_i >= _iterator.length) return "break"; - _ref2 = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) return "break"; - _ref2 = _i.value; - } - - var type = _ref2; - - var typeKey = "is" + type; - NodePath.prototype[typeKey] = function (opts) { - return t[typeKey](this.node, opts); - }; - - NodePath.prototype["assert" + type] = function (opts) { - if (!this[typeKey](opts)) { - throw new TypeError("Expected node path of type " + type); - } - }; -}; - -for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref2; - - var _ret2 = _loop2(); - - if (_ret2 === "break") break; -} - -var _loop = function _loop(type) { - if (type[0] === "_") return "continue"; - if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); - - var virtualType = virtualTypes[type]; - - NodePath.prototype["is" + type] = function (opts) { - return virtualType.checkPath(this, opts); - }; -}; - -for (var type in virtualTypes) { - var _ret = _loop(type); - - if (_ret === "continue") continue; -} -module.exports = exports["default"]; -},{"../cache":76,"../index":79,"../scope":98,"./ancestry":80,"./comments":81,"./context":82,"./conversion":83,"./evaluation":84,"./family":85,"./inference":87,"./introspection":90,"./lib/virtual-types":93,"./modification":94,"./removal":95,"./replacement":96,"babel-runtime/core-js/get-iterator":56,"babel-runtime/helpers/classCallCheck":70,"babel-types":112,"debug":232,"invariant":245,"lodash/assign":414}],87:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.getTypeAnnotation = getTypeAnnotation; -exports._getTypeAnnotation = _getTypeAnnotation; -exports.isBaseType = isBaseType; -exports.couldBeBaseType = couldBeBaseType; -exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; -exports.isGenericType = isGenericType; - -var _inferers = require("./inferers"); - -var inferers = _interopRequireWildcard(_inferers); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getTypeAnnotation() { - if (this.typeAnnotation) return this.typeAnnotation; - - var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); - if (t.isTypeAnnotation(type)) type = type.typeAnnotation; - return this.typeAnnotation = type; -} - -function _getTypeAnnotation() { - var node = this.node; - - if (!node) { - if (this.key === "init" && this.parentPath.isVariableDeclarator()) { - var declar = this.parentPath.parentPath; - var declarParent = declar.parentPath; - - if (declar.key === "left" && declarParent.isForInStatement()) { - return t.stringTypeAnnotation(); - } - - if (declar.key === "left" && declarParent.isForOfStatement()) { - return t.anyTypeAnnotation(); - } - - return t.voidTypeAnnotation(); - } else { - return; - } - } - - if (node.typeAnnotation) { - return node.typeAnnotation; - } - - var inferer = inferers[node.type]; - if (inferer) { - return inferer.call(this, node); - } - - inferer = inferers[this.parentPath.type]; - if (inferer && inferer.validParent) { - return this.parentPath.getTypeAnnotation(); - } -} - -function isBaseType(baseName, soft) { - return _isBaseType(baseName, this.getTypeAnnotation(), soft); -} - -function _isBaseType(baseName, type, soft) { - if (baseName === "string") { - return t.isStringTypeAnnotation(type); - } else if (baseName === "number") { - return t.isNumberTypeAnnotation(type); - } else if (baseName === "boolean") { - return t.isBooleanTypeAnnotation(type); - } else if (baseName === "any") { - return t.isAnyTypeAnnotation(type); - } else if (baseName === "mixed") { - return t.isMixedTypeAnnotation(type); - } else if (baseName === "empty") { - return t.isEmptyTypeAnnotation(type); - } else if (baseName === "void") { - return t.isVoidTypeAnnotation(type); - } else { - if (soft) { - return false; - } else { - throw new Error("Unknown base type " + baseName); - } - } -} - -function couldBeBaseType(name) { - var type = this.getTypeAnnotation(); - if (t.isAnyTypeAnnotation(type)) return true; - - if (t.isUnionTypeAnnotation(type)) { - for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var type2 = _ref; - - if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { - return true; - } - } - return false; - } else { - return _isBaseType(name, type, true); - } -} - -function baseTypeStrictlyMatches(right) { - var left = this.getTypeAnnotation(); - right = right.getTypeAnnotation(); - - if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { - return right.type === left.type; - } -} - -function isGenericType(genericName) { - var type = this.getTypeAnnotation(); - return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); -} -},{"./inferers":89,"babel-runtime/core-js/get-iterator":56,"babel-types":112}],88:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.default = function (node) { - if (!this.isReferenced()) return; - - var binding = this.scope.getBinding(node.name); - if (binding) { - if (binding.identifier.typeAnnotation) { - return binding.identifier.typeAnnotation; - } else { - return getTypeAnnotationBindingConstantViolations(this, node.name); - } - } - - if (node.name === "undefined") { - return t.voidTypeAnnotation(); - } else if (node.name === "NaN" || node.name === "Infinity") { - return t.numberTypeAnnotation(); - } else if (node.name === "arguments") {} -}; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getTypeAnnotationBindingConstantViolations(path, name) { - var binding = path.scope.getBinding(name); - - var types = []; - path.typeAnnotation = t.unionTypeAnnotation(types); - - var functionConstantViolations = []; - var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); - - var testType = getConditionalAnnotation(path, name); - if (testType) { - (function () { - var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); - - constantViolations = constantViolations.filter(function (path) { - return testConstantViolations.indexOf(path) < 0; - }); - - types.push(testType.typeAnnotation); - })(); - } - - if (constantViolations.length) { - constantViolations = constantViolations.concat(functionConstantViolations); - - for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var violation = _ref; - - types.push(violation.getTypeAnnotation()); - } - } - - if (types.length) { - return t.createUnionTypeAnnotation(types); - } -} - -function getConstantViolationsBefore(binding, path, functions) { - var violations = binding.constantViolations.slice(); - violations.unshift(binding.path); - return violations.filter(function (violation) { - violation = violation.resolve(); - var status = violation._guessExecutionStatusRelativeTo(path); - if (functions && status === "function") functions.push(violation); - return status === "before"; - }); -} - -function inferAnnotationFromBinaryExpression(name, path) { - var operator = path.node.operator; - - var right = path.get("right").resolve(); - var left = path.get("left").resolve(); - - var target = void 0; - if (left.isIdentifier({ name: name })) { - target = right; - } else if (right.isIdentifier({ name: name })) { - target = left; - } - if (target) { - if (operator === "===") { - return target.getTypeAnnotation(); - } else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else { - return; - } - } else { - if (operator !== "===") return; - } - - var typeofPath = void 0; - var typePath = void 0; - if (left.isUnaryExpression({ operator: "typeof" })) { - typeofPath = left; - typePath = right; - } else if (right.isUnaryExpression({ operator: "typeof" })) { - typeofPath = right; - typePath = left; - } - if (!typePath && !typeofPath) return; - - typePath = typePath.resolve(); - if (!typePath.isLiteral()) return; - - var typeValue = typePath.node.value; - if (typeof typeValue !== "string") return; - - if (!typeofPath.get("argument").isIdentifier({ name: name })) return; - - return t.createTypeAnnotationBasedOnTypeof(typePath.node.value); -} - -function getParentConditionalPath(path) { - var parentPath = void 0; - while (parentPath = path.parentPath) { - if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { - if (path.key === "test") { - return; - } else { - return parentPath; - } - } else { - path = parentPath; - } - } -} - -function getConditionalAnnotation(path, name) { - var ifStatement = getParentConditionalPath(path); - if (!ifStatement) return; - - var test = ifStatement.get("test"); - var paths = [test]; - var types = []; - - do { - var _path = paths.shift().resolve(); - - if (_path.isLogicalExpression()) { - paths.push(_path.get("left")); - paths.push(_path.get("right")); - } - - if (_path.isBinaryExpression()) { - var type = inferAnnotationFromBinaryExpression(name, _path); - if (type) types.push(type); - } - } while (paths.length); - - if (types.length) { - return { - typeAnnotation: t.createUnionTypeAnnotation(types), - ifStatement: ifStatement - }; - } else { - return getConditionalAnnotation(ifStatement, name); - } -} -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":56,"babel-types":112}],89:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = exports.Identifier = undefined; - -var _infererReference = require("./inferer-reference"); - -Object.defineProperty(exports, "Identifier", { - enumerable: true, - get: function get() { - return _interopRequireDefault(_infererReference).default; - } -}); -exports.VariableDeclarator = VariableDeclarator; -exports.TypeCastExpression = TypeCastExpression; -exports.NewExpression = NewExpression; -exports.TemplateLiteral = TemplateLiteral; -exports.UnaryExpression = UnaryExpression; -exports.BinaryExpression = BinaryExpression; -exports.LogicalExpression = LogicalExpression; -exports.ConditionalExpression = ConditionalExpression; -exports.SequenceExpression = SequenceExpression; -exports.AssignmentExpression = AssignmentExpression; -exports.UpdateExpression = UpdateExpression; -exports.StringLiteral = StringLiteral; -exports.NumericLiteral = NumericLiteral; -exports.BooleanLiteral = BooleanLiteral; -exports.NullLiteral = NullLiteral; -exports.RegExpLiteral = RegExpLiteral; -exports.ObjectExpression = ObjectExpression; -exports.ArrayExpression = ArrayExpression; -exports.RestElement = RestElement; -exports.CallExpression = CallExpression; -exports.TaggedTemplateExpression = TaggedTemplateExpression; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function VariableDeclarator() { - var id = this.get("id"); - - if (id.isIdentifier()) { - return this.get("init").getTypeAnnotation(); - } else { - return; - } -} - -function TypeCastExpression(node) { - return node.typeAnnotation; -} - -TypeCastExpression.validParent = true; - -function NewExpression(node) { - if (this.get("callee").isIdentifier()) { - return t.genericTypeAnnotation(node.callee); - } -} - -function TemplateLiteral() { - return t.stringTypeAnnotation(); -} - -function UnaryExpression(node) { - var operator = node.operator; - - if (operator === "void") { - return t.voidTypeAnnotation(); - } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.stringTypeAnnotation(); - } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } -} - -function BinaryExpression(node) { - var operator = node.operator; - - if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.numberTypeAnnotation(); - } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { - return t.booleanTypeAnnotation(); - } else if (operator === "+") { - var right = this.get("right"); - var left = this.get("left"); - - if (left.isBaseType("number") && right.isBaseType("number")) { - return t.numberTypeAnnotation(); - } else if (left.isBaseType("string") || right.isBaseType("string")) { - return t.stringTypeAnnotation(); - } - - return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]); - } -} - -function LogicalExpression() { - return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); -} - -function ConditionalExpression() { - return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); -} - -function SequenceExpression() { - return this.get("expressions").pop().getTypeAnnotation(); -} - -function AssignmentExpression() { - return this.get("right").getTypeAnnotation(); -} - -function UpdateExpression(node) { - var operator = node.operator; - if (operator === "++" || operator === "--") { - return t.numberTypeAnnotation(); - } -} - -function StringLiteral() { - return t.stringTypeAnnotation(); -} - -function NumericLiteral() { - return t.numberTypeAnnotation(); -} - -function BooleanLiteral() { - return t.booleanTypeAnnotation(); -} - -function NullLiteral() { - return t.nullLiteralTypeAnnotation(); -} - -function RegExpLiteral() { - return t.genericTypeAnnotation(t.identifier("RegExp")); -} - -function ObjectExpression() { - return t.genericTypeAnnotation(t.identifier("Object")); -} - -function ArrayExpression() { - return t.genericTypeAnnotation(t.identifier("Array")); -} - -function RestElement() { - return ArrayExpression(); -} - -RestElement.validParent = true; - -function Func() { - return t.genericTypeAnnotation(t.identifier("Function")); -} - -exports.FunctionExpression = Func; -exports.ArrowFunctionExpression = Func; -exports.FunctionDeclaration = Func; -exports.ClassExpression = Func; -exports.ClassDeclaration = Func; -function CallExpression() { - return resolveCall(this.get("callee")); -} - -function TaggedTemplateExpression() { - return resolveCall(this.get("tag")); -} - -function resolveCall(callee) { - callee = callee.resolve(); - - if (callee.isFunction()) { - if (callee.is("async")) { - if (callee.is("generator")) { - return t.genericTypeAnnotation(t.identifier("AsyncIterator")); - } else { - return t.genericTypeAnnotation(t.identifier("Promise")); - } - } else { - if (callee.node.returnType) { - return callee.node.returnType; - } else {} - } - } -} -},{"./inferer-reference":88,"babel-types":112}],90:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.is = undefined; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.matchesPattern = matchesPattern; -exports.has = has; -exports.isStatic = isStatic; -exports.isnt = isnt; -exports.equals = equals; -exports.isNodeType = isNodeType; -exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; -exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; -exports.isCompletionRecord = isCompletionRecord; -exports.isStatementOrBlock = isStatementOrBlock; -exports.referencesImport = referencesImport; -exports.getSource = getSource; -exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; -exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; -exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; -exports.resolve = resolve; -exports._resolve = _resolve; - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function matchesPattern(pattern, allowPartial) { - if (!this.isMemberExpression()) return false; - - var parts = pattern.split("."); - var search = [this.node]; - var i = 0; - - function matches(name) { - var part = parts[i]; - return part === "*" || name === part; - } - - while (search.length) { - var node = search.shift(); - - if (allowPartial && i === parts.length) { - return true; - } - - if (t.isIdentifier(node)) { - if (!matches(node.name)) return false; - } else if (t.isLiteral(node)) { - if (!matches(node.value)) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isLiteral(node.property)) { - return false; - } else { - search.unshift(node.property); - search.unshift(node.object); - continue; - } - } else if (t.isThisExpression(node)) { - if (!matches("this")) return false; - } else { - return false; - } - - if (++i > parts.length) { - return false; - } - } - - return i === parts.length; -} - -function has(key) { - var val = this.node && this.node[key]; - if (val && Array.isArray(val)) { - return !!val.length; - } else { - return !!val; - } -} - -function isStatic() { - return this.scope.isStatic(this.node); -} - -var is = exports.is = has; - -function isnt(key) { - return !this.has(key); -} - -function equals(key, value) { - return this.node[key] === value; -} - -function isNodeType(type) { - return t.isType(this.type, type); -} - -function canHaveVariableDeclarationOrExpression() { - return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); -} - -function canSwapBetweenExpressionAndStatement(replacement) { - if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { - return false; - } - - if (this.isExpression()) { - return t.isBlockStatement(replacement); - } else if (this.isBlockStatement()) { - return t.isExpression(replacement); - } - - return false; -} - -function isCompletionRecord(allowInsideFunction) { - var path = this; - var first = true; - - do { - var container = path.container; - - if (path.isFunction() && !first) { - return !!allowInsideFunction; - } - - first = false; - - if (Array.isArray(container) && path.key !== container.length - 1) { - return false; - } - } while ((path = path.parentPath) && !path.isProgram()); - - return true; -} - -function isStatementOrBlock() { - if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { - return false; - } else { - return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key); - } -} - -function referencesImport(moduleSource, importName) { - if (!this.isReferencedIdentifier()) return false; - - var binding = this.scope.getBinding(this.node.name); - if (!binding || binding.kind !== "module") return false; - - var path = binding.path; - var parent = path.parentPath; - if (!parent.isImportDeclaration()) return false; - - if (parent.node.source.value === moduleSource) { - if (!importName) return true; - } else { - return false; - } - - if (path.isImportDefaultSpecifier() && importName === "default") { - return true; - } - - if (path.isImportNamespaceSpecifier() && importName === "*") { - return true; - } - - if (path.isImportSpecifier() && path.node.imported.name === importName) { - return true; - } - - return false; -} - -function getSource() { - var node = this.node; - if (node.end) { - return this.hub.file.code.slice(node.start, node.end); - } else { - return ""; - } -} - -function willIMaybeExecuteBefore(target) { - return this._guessExecutionStatusRelativeTo(target) !== "after"; -} - -function _guessExecutionStatusRelativeTo(target) { - var targetFuncParent = target.scope.getFunctionParent(); - var selfFuncParent = this.scope.getFunctionParent(); - - if (targetFuncParent.node !== selfFuncParent.node) { - var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); - if (status) { - return status; - } else { - target = targetFuncParent.path; - } - } - - var targetPaths = target.getAncestry(); - if (targetPaths.indexOf(this) >= 0) return "after"; - - var selfPaths = this.getAncestry(); - - var commonPath = void 0; - var targetIndex = void 0; - var selfIndex = void 0; - for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { - var selfPath = selfPaths[selfIndex]; - targetIndex = targetPaths.indexOf(selfPath); - if (targetIndex >= 0) { - commonPath = selfPath; - break; - } - } - if (!commonPath) { - return "before"; - } - - var targetRelationship = targetPaths[targetIndex - 1]; - var selfRelationship = selfPaths[selfIndex - 1]; - if (!targetRelationship || !selfRelationship) { - return "before"; - } - - if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { - return targetRelationship.key > selfRelationship.key ? "before" : "after"; - } - - var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); - var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); - return targetKeyPosition > selfKeyPosition ? "before" : "after"; -} - -function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { - var targetFuncPath = targetFuncParent.path; - if (!targetFuncPath.isFunctionDeclaration()) return; - - var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); - - if (!binding.references) return "before"; - - var referencePaths = binding.referencePaths; - - for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var path = _ref; - - if (path.key !== "callee" || !path.parentPath.isCallExpression()) { - return; - } - } - - var allStatus = void 0; - - for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _path = _ref2; - - var childOfFunction = !!_path.find(function (path) { - return path.node === targetFuncPath.node; - }); - if (childOfFunction) continue; - - var status = this._guessExecutionStatusRelativeTo(_path); - - if (allStatus) { - if (allStatus !== status) return; - } else { - allStatus = status; - } - } - - return allStatus; -} - -function resolve(dangerous, resolved) { - return this._resolve(dangerous, resolved) || this; -} - -function _resolve(dangerous, resolved) { - var _this = this; - - if (resolved && resolved.indexOf(this) >= 0) return; - - resolved = resolved || []; - resolved.push(this); - - if (this.isVariableDeclarator()) { - if (this.get("id").isIdentifier()) { - return this.get("init").resolve(dangerous, resolved); - } else {} - } else if (this.isReferencedIdentifier()) { - var binding = this.scope.getBinding(this.node.name); - if (!binding) return; - - if (!binding.constant) return; - - if (binding.kind === "module") return; - - if (binding.path !== this) { - var _ret = function () { - var ret = binding.path.resolve(dangerous, resolved); - - if (_this.find(function (parent) { - return parent.node === ret.node; - })) return { - v: void 0 - }; - return { - v: ret - }; - }(); - - if ((typeof _ret === "undefined" ? "undefined" : (0, _typeof3.default)(_ret)) === "object") return _ret.v; - } - } else if (this.isTypeCastExpression()) { - return this.get("expression").resolve(dangerous, resolved); - } else if (dangerous && this.isMemberExpression()) { - - var targetKey = this.toComputedKey(); - if (!t.isLiteral(targetKey)) return; - - var targetName = targetKey.value; - - var target = this.get("object").resolve(dangerous, resolved); - - if (target.isObjectExpression()) { - var props = target.get("properties"); - for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var prop = _ref3; - - if (!prop.isProperty()) continue; - - var key = prop.get("key"); - - var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); - - match = match || key.isLiteral({ value: targetName }); - - if (match) return prop.get("value").resolve(dangerous, resolved); - } - } else if (target.isArrayExpression() && !isNaN(+targetName)) { - var elems = target.get("elements"); - var elem = elems[targetName]; - if (elem) return elem.resolve(dangerous, resolved); - } - } -} -},{"babel-runtime/core-js/get-iterator":56,"babel-runtime/helpers/typeof":74,"babel-types":112,"lodash/includes":431}],91:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var referenceVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) { - return; - } - - if (path.node.name === "this") { - var scope = path.scope; - do { - if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break; - } while (scope = scope.parent); - if (scope) state.breakOnScopePaths.push(scope.path); - } - - var binding = path.scope.getBinding(path.node.name); - if (!binding) return; - - if (binding !== state.scope.getBinding(path.node.name)) return; - - state.bindings[path.node.name] = binding; - } -}; - -var PathHoister = function () { - function PathHoister(path, scope) { - (0, _classCallCheck3.default)(this, PathHoister); - - this.breakOnScopePaths = []; - - this.bindings = {}; - - this.scopes = []; - - this.scope = scope; - this.path = path; - - this.attachAfter = false; - } - - PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { - for (var key in this.bindings) { - var binding = this.bindings[key]; - if (!scope.bindingIdentifierEquals(key, binding.identifier)) { - return false; - } - } - - return true; - }; - - PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { - var scope = this.path.scope; - do { - if (this.isCompatibleScope(scope)) { - this.scopes.push(scope); - } else { - break; - } - - if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { - break; - } - } while (scope = scope.parent); - }; - - PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { - var path = this._getAttachmentPath(); - if (!path) return; - - var targetScope = path.scope; - - if (targetScope.path === path) { - targetScope = path.scope.parent; - } - - if (targetScope.path.isProgram() || targetScope.path.isFunction()) { - for (var name in this.bindings) { - if (!targetScope.hasOwnBinding(name)) continue; - - var binding = this.bindings[name]; - - if (binding.kind === "param") continue; - - if (this.getAttachmentParentForPath(binding.path).key > path.key) { - this.attachAfter = true; - path = binding.path; - - for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var violationPath = _ref; - - if (this.getAttachmentParentForPath(violationPath).key > path.key) { - path = violationPath; - } - } - } - } - } - - return path; - }; - - PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { - var scopes = this.scopes; - - var scope = scopes.pop(); - - if (!scope) return; - - if (scope.path.isFunction()) { - if (this.hasOwnParamBindings(scope)) { - if (this.scope === scope) return; - - return scope.path.get("body").get("body")[0]; - } else { - return this.getNextScopeAttachmentParent(); - } - } else if (scope.path.isProgram()) { - return this.getNextScopeAttachmentParent(); - } - }; - - PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() { - var scope = this.scopes.pop(); - if (scope) return this.getAttachmentParentForPath(scope.path); - }; - - PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) { - do { - if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path; - } while (path = path.parentPath); - }; - - PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { - for (var name in this.bindings) { - if (!scope.hasOwnBinding(name)) continue; - - var binding = this.bindings[name]; - - if (binding.kind === "param" && binding.constant) return true; - } - return false; - }; - - PathHoister.prototype.run = function run() { - var node = this.path.node; - if (node._hoisted) return; - node._hoisted = true; - - this.path.traverse(referenceVisitor, this); - - this.getCompatibleScopes(); - - var attachTo = this.getAttachmentPath(); - if (!attachTo) return; - - if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; - - var uid = attachTo.scope.generateUidIdentifier("ref"); - var declarator = t.variableDeclarator(uid, this.path.node); - - var insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; - attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]); - - var parent = this.path.parentPath; - if (parent.isJSXElement() && this.path.container === parent.node.children) { - uid = t.JSXExpressionContainer(uid); - } - - this.path.replaceWith(uid); - }; - - return PathHoister; -}(); - -exports.default = PathHoister; -module.exports = exports["default"]; -},{"babel-runtime/core-js/get-iterator":56,"babel-runtime/helpers/classCallCheck":70,"babel-types":112}],92:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -var hooks = exports.hooks = [function (self, parent) { - var removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement(); - - if (removeParent) { - parent.remove(); - return true; - } -}, function (self, parent) { - if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { - parent.replaceWith(parent.node.expressions[0]); - return true; - } -}, function (self, parent) { - if (parent.isBinary()) { - if (self.key === "left") { - parent.replaceWith(parent.node.right); - } else { - parent.replaceWith(parent.node.left); - } - return true; - } -}, function (self, parent) { - if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) { - self.replaceWith({ - type: "BlockStatement", - body: [] - }); - return true; - } -}]; -},{}],93:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var ReferencedIdentifier = exports.ReferencedIdentifier = { - types: ["Identifier", "JSXIdentifier"], - checkPath: function checkPath(_ref, opts) { - var node = _ref.node, - parent = _ref.parent; - - if (!t.isIdentifier(node, opts) && !t.isJSXMemberExpression(parent, opts)) { - if (t.isJSXIdentifier(node, opts)) { - if (_babelTypes.react.isCompatTag(node.name)) return false; - } else { - return false; - } - } - - return t.isReferenced(node, parent); - } -}; - -var ReferencedMemberExpression = exports.ReferencedMemberExpression = { - types: ["MemberExpression"], - checkPath: function checkPath(_ref2) { - var node = _ref2.node, - parent = _ref2.parent; - - return t.isMemberExpression(node) && t.isReferenced(node, parent); - } -}; - -var BindingIdentifier = exports.BindingIdentifier = { - types: ["Identifier"], - checkPath: function checkPath(_ref3) { - var node = _ref3.node, - parent = _ref3.parent; - - return t.isIdentifier(node) && t.isBinding(node, parent); - } -}; - -var Statement = exports.Statement = { - types: ["Statement"], - checkPath: function checkPath(_ref4) { - var node = _ref4.node, - parent = _ref4.parent; - - if (t.isStatement(node)) { - if (t.isVariableDeclaration(node)) { - if (t.isForXStatement(parent, { left: node })) return false; - if (t.isForStatement(parent, { init: node })) return false; - } - - return true; - } else { - return false; - } - } -}; - -var Expression = exports.Expression = { - types: ["Expression"], - checkPath: function checkPath(path) { - if (path.isIdentifier()) { - return path.isReferencedIdentifier(); - } else { - return t.isExpression(path.node); - } - } -}; - -var Scope = exports.Scope = { - types: ["Scopable"], - checkPath: function checkPath(path) { - return t.isScope(path.node, path.parent); - } -}; - -var Referenced = exports.Referenced = { - checkPath: function checkPath(path) { - return t.isReferenced(path.node, path.parent); - } -}; - -var BlockScoped = exports.BlockScoped = { - checkPath: function checkPath(path) { - return t.isBlockScoped(path.node); - } -}; - -var Var = exports.Var = { - types: ["VariableDeclaration"], - checkPath: function checkPath(path) { - return t.isVar(path.node); - } -}; - -var User = exports.User = { - checkPath: function checkPath(path) { - return path.node && !!path.node.loc; - } -}; - -var Generated = exports.Generated = { - checkPath: function checkPath(path) { - return !path.isUser(); - } -}; - -var Pure = exports.Pure = { - checkPath: function checkPath(path, opts) { - return path.scope.isPure(path.node, opts); - } -}; - -var Flow = exports.Flow = { - types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], - checkPath: function checkPath(_ref5) { - var node = _ref5.node; - - if (t.isFlow(node)) { - return true; - } else if (t.isImportDeclaration(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else if (t.isExportDeclaration(node)) { - return node.exportKind === "type"; - } else if (t.isImportSpecifier(node)) { - return node.importKind === "type" || node.importKind === "typeof"; - } else { - return false; - } - } -}; -},{"babel-types":112}],94:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.insertBefore = insertBefore; -exports._containerInsert = _containerInsert; -exports._containerInsertBefore = _containerInsertBefore; -exports._containerInsertAfter = _containerInsertAfter; -exports._maybePopFromStatements = _maybePopFromStatements; -exports.insertAfter = insertAfter; -exports.updateSiblingKeys = updateSiblingKeys; -exports._verifyNodeList = _verifyNodeList; -exports.unshiftContainer = unshiftContainer; -exports.pushContainer = pushContainer; -exports.hoist = hoist; - -var _cache = require("../cache"); - -var _hoister = require("./lib/hoister"); - -var _hoister2 = _interopRequireDefault(_hoister); - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function insertBefore(nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertBefore(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) nodes.push(this.node); - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertBefore(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.push(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); - } - } - - return [this]; -} - -function _containerInsert(from, nodes) { - this.updateSiblingKeys(from, nodes.length); - - var paths = []; - - for (var i = 0; i < nodes.length; i++) { - var to = from + i; - var node = nodes[i]; - this.container.splice(to, 0, node); - - if (this.context) { - var path = this.context.create(this.parent, this.container, to, this.listKey); - - if (this.context.queue) path.pushContext(this.context); - paths.push(path); - } else { - paths.push(_index2.default.get({ - parentPath: this.parentPath, - parent: this.parent, - container: this.container, - listKey: this.listKey, - key: to - })); - } - } - - var contexts = this._getQueueContexts(); - - for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var _path = _ref; - - _path.setScope(); - _path.debug(function () { - return "Inserted."; - }); - - for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var context = _ref2; - - context.maybeQueue(_path, true); - } - } - - return paths; -} - -function _containerInsertBefore(nodes) { - return this._containerInsert(this.key, nodes); -} - -function _containerInsertAfter(nodes) { - return this._containerInsert(this.key + 1, nodes); -} - -function _maybePopFromStatements(nodes) { - var last = nodes[nodes.length - 1]; - var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression); - - if (isIdentifier && !this.isCompletionRecord()) { - nodes.pop(); - } -} - -function insertAfter(nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { - return this.parentPath.insertAfter(nodes); - } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { - if (this.node) { - var temp = this.scope.generateDeclaredUidIdentifier(); - nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); - nodes.push(t.expressionStatement(temp)); - } - this.replaceExpressionWithStatements(nodes); - } else { - this._maybePopFromStatements(nodes); - if (Array.isArray(this.container)) { - return this._containerInsertAfter(nodes); - } else if (this.isStatementOrBlock()) { - if (this.node) nodes.unshift(this.node); - this._replaceWith(t.blockStatement(nodes)); - } else { - throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); - } - } - - return [this]; -} - -function updateSiblingKeys(fromIndex, incrementBy) { - if (!this.parent) return; - - var paths = _cache.path.get(this.parent); - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (path.key >= fromIndex) { - path.key += incrementBy; - } - } -} - -function _verifyNodeList(nodes) { - if (!nodes) { - return []; - } - - if (nodes.constructor !== Array) { - nodes = [nodes]; - } - - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - var msg = void 0; - - if (!node) { - msg = "has falsy node"; - } else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") { - msg = "contains a non-object node"; - } else if (!node.type) { - msg = "without a type"; - } else if (node instanceof _index2.default) { - msg = "has a NodePath when it expected a raw object"; - } - - if (msg) { - var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node); - throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type); - } - } - - return nodes; -} - -function unshiftContainer(listKey, nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: this.node[listKey], - listKey: listKey, - key: 0 - }); - - return path.insertBefore(nodes); -} - -function pushContainer(listKey, nodes) { - this._assertUnremoved(); - - nodes = this._verifyNodeList(nodes); - - var container = this.node[listKey]; - var path = _index2.default.get({ - parentPath: this, - parent: this.node, - container: container, - listKey: listKey, - key: container.length - }); - - return path.replaceWithMultiple(nodes); -} - -function hoist() { - var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scope; - - var hoister = new _hoister2.default(this, scope); - return hoister.run(); -} -},{"../cache":76,"./index":86,"./lib/hoister":91,"babel-runtime/core-js/get-iterator":56,"babel-runtime/helpers/typeof":74,"babel-types":112}],95:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.remove = remove; -exports._callRemovalHooks = _callRemovalHooks; -exports._remove = _remove; -exports._markRemoved = _markRemoved; -exports._assertUnremoved = _assertUnremoved; - -var _removalHooks = require("./lib/removal-hooks"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function remove() { - this._assertUnremoved(); - - this.resync(); - - if (this._callRemovalHooks()) { - this._markRemoved(); - return; - } - - this.shareCommentsWithSiblings(); - this._remove(); - this._markRemoved(); -} - -function _callRemovalHooks() { - for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var fn = _ref; - - if (fn(this, this.parentPath)) return true; - } -} - -function _remove() { - if (Array.isArray(this.container)) { - this.container.splice(this.key, 1); - this.updateSiblingKeys(this.key, -1); - } else { - this._replaceWith(null); - } -} - -function _markRemoved() { - this.shouldSkip = true; - this.removed = true; - this.node = null; -} - -function _assertUnremoved() { - if (this.removed) { - throw this.buildCodeFrameError("NodePath has been removed so is read-only."); - } -} -},{"./lib/removal-hooks":92,"babel-runtime/core-js/get-iterator":56}],96:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.replaceWithMultiple = replaceWithMultiple; -exports.replaceWithSourceString = replaceWithSourceString; -exports.replaceWith = replaceWith; -exports._replaceWith = _replaceWith; -exports.replaceExpressionWithStatements = replaceExpressionWithStatements; -exports.replaceInline = replaceInline; - -var _babelCodeFrame = require("babel-code-frame"); - -var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _index3 = require("./index"); - -var _index4 = _interopRequireDefault(_index3); - -var _babylon = require("babylon"); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hoistVariablesVisitor = { - Function: function Function(path) { - path.skip(); - }, - VariableDeclaration: function VariableDeclaration(path) { - if (path.node.kind !== "var") return; - - var bindings = path.getBindingIdentifiers(); - for (var key in bindings) { - path.scope.push({ id: bindings[key] }); - } - - var exprs = []; - - for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var declar = _ref; - - if (declar.init) { - exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init))); - } - } - - path.replaceWithMultiple(exprs); - } -}; - -function replaceWithMultiple(nodes) { - this.resync(); - - nodes = this._verifyNodeList(nodes); - t.inheritLeadingComments(nodes[0], this.node); - t.inheritTrailingComments(nodes[nodes.length - 1], this.node); - this.node = this.container[this.key] = null; - this.insertAfter(nodes); - - if (this.node) { - this.requeue(); - } else { - this.remove(); - } -} - -function replaceWithSourceString(replacement) { - this.resync(); - - try { - replacement = "(" + replacement + ")"; - replacement = (0, _babylon.parse)(replacement); - } catch (err) { - var loc = err.loc; - if (loc) { - err.message += " - make sure this is an expression."; - err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1); - } - throw err; - } - - replacement = replacement.program.body[0].expression; - _index2.default.removeProperties(replacement); - return this.replaceWith(replacement); -} - -function replaceWith(replacement) { - this.resync(); - - if (this.removed) { - throw new Error("You can't replace this node, we've already removed it"); - } - - if (replacement instanceof _index4.default) { - replacement = replacement.node; - } - - if (!replacement) { - throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); - } - - if (this.node === replacement) { - return; - } - - if (this.isProgram() && !t.isProgram(replacement)) { - throw new Error("You can only replace a Program root node with another Program node"); - } - - if (Array.isArray(replacement)) { - throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); - } - - if (typeof replacement === "string") { - throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); - } - - if (this.isNodeType("Statement") && t.isExpression(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { - replacement = t.expressionStatement(replacement); - } - } - - if (this.isNodeType("Expression") && t.isStatement(replacement)) { - if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { - return this.replaceExpressionWithStatements([replacement]); - } - } - - var oldNode = this.node; - if (oldNode) { - t.inheritsComments(replacement, oldNode); - t.removeComments(oldNode); - } - - this._replaceWith(replacement); - this.type = replacement.type; - - this.setScope(); - - this.requeue(); -} - -function _replaceWith(node) { - if (!this.container) { - throw new ReferenceError("Container is falsy"); - } - - if (this.inList) { - t.validate(this.parent, this.key, [node]); - } else { - t.validate(this.parent, this.key, node); - } - - this.debug(function () { - return "Replace with " + (node && node.type); - }); - - this.node = this.container[this.key] = node; -} - -function replaceExpressionWithStatements(nodes) { - this.resync(); - - var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); - - if (t.isSequenceExpression(toSequenceExpression)) { - var exprs = toSequenceExpression.expressions; - - if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { - this._maybePopFromStatements(exprs); - } - - if (exprs.length === 1) { - this.replaceWith(exprs[0]); - } else { - this.replaceWith(toSequenceExpression); - } - } else if (toSequenceExpression) { - this.replaceWith(toSequenceExpression); - } else { - var container = t.functionExpression(null, [], t.blockStatement(nodes)); - container.shadow = true; - - this.replaceWith(t.callExpression(container, [])); - this.traverse(hoistVariablesVisitor); - - var completionRecords = this.get("callee").getCompletionRecords(); - for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var path = _ref2; - - if (!path.isExpressionStatement()) continue; - - var loop = path.findParent(function (path) { - return path.isLoop(); - }); - if (loop) { - var uid = loop.getData("expressionReplacementReturnUid"); - - if (!uid) { - var callee = this.get("callee"); - uid = callee.scope.generateDeclaredUidIdentifier("ret"); - callee.get("body").pushContainer("body", t.returnStatement(uid)); - loop.setData("expressionReplacementReturnUid", uid); - } else { - uid = t.identifier(uid.name); - } - - path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression)); - } else { - path.replaceWith(t.returnStatement(path.node.expression)); - } - } - - return this.node; - } -} - -function replaceInline(nodes) { - this.resync(); - - if (Array.isArray(nodes)) { - if (Array.isArray(this.container)) { - nodes = this._verifyNodeList(nodes); - this._containerInsertAfter(nodes); - return this.remove(); - } else { - return this.replaceWithMultiple(nodes); - } - } else { - return this.replaceWith(nodes); - } -} -},{"../index":79,"./index":86,"babel-code-frame":3,"babel-runtime/core-js/get-iterator":56,"babel-types":112,"babylon":116}],97:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Binding = function () { - function Binding(_ref) { - var existing = _ref.existing, - identifier = _ref.identifier, - scope = _ref.scope, - path = _ref.path, - kind = _ref.kind; - (0, _classCallCheck3.default)(this, Binding); - - this.identifier = identifier; - this.scope = scope; - this.path = path; - this.kind = kind; - - this.constantViolations = []; - this.constant = true; - - this.referencePaths = []; - this.referenced = false; - this.references = 0; - - this.clearValue(); - - if (existing) { - this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations); - } - } - - Binding.prototype.deoptValue = function deoptValue() { - this.clearValue(); - this.hasDeoptedValue = true; - }; - - Binding.prototype.setValue = function setValue(value) { - if (this.hasDeoptedValue) return; - this.hasValue = true; - this.value = value; - }; - - Binding.prototype.clearValue = function clearValue() { - this.hasDeoptedValue = false; - this.hasValue = false; - this.value = null; - }; - - Binding.prototype.reassign = function reassign(path) { - this.constant = false; - if (this.constantViolations.indexOf(path) !== -1) { - return; - } - this.constantViolations.push(path); - }; - - Binding.prototype.reference = function reference(path) { - if (this.referencePaths.indexOf(path) !== -1) { - return; - } - this.referenced = true; - this.references++; - this.referencePaths.push(path); - }; - - Binding.prototype.dereference = function dereference() { - this.references--; - this.referenced = !!this.references; - }; - - return Binding; -}(); - -exports.default = Binding; -module.exports = exports["default"]; -},{"babel-runtime/helpers/classCallCheck":70}],98:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -var _map = require("babel-runtime/core-js/map"); - -var _map2 = _interopRequireDefault(_map); - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _includes = require("lodash/includes"); - -var _includes2 = _interopRequireDefault(_includes); - -var _repeat = require("lodash/repeat"); - -var _repeat2 = _interopRequireDefault(_repeat); - -var _renamer = require("./lib/renamer"); - -var _renamer2 = _interopRequireDefault(_renamer); - -var _index = require("../index"); - -var _index2 = _interopRequireDefault(_index); - -var _defaults = require("lodash/defaults"); - -var _defaults2 = _interopRequireDefault(_defaults); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _binding2 = require("./binding"); - -var _binding3 = _interopRequireDefault(_binding2); - -var _globals = require("globals"); - -var _globals2 = _interopRequireDefault(_globals); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _cache = require("../cache"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _crawlCallsCount = 0; - -function getCache(path, parentScope, self) { - var scopes = _cache.scope.get(path.node) || []; - - for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var scope = _ref; - - if (scope.parent === parentScope && scope.path === path) return scope; - } - - scopes.push(self); - - if (!_cache.scope.has(path.node)) { - _cache.scope.set(path.node, scopes); - } -} - -function gatherNodeParts(node, parts) { - if (t.isModuleDeclaration(node)) { - if (node.source) { - gatherNodeParts(node.source, parts); - } else if (node.specifiers && node.specifiers.length) { - for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var specifier = _ref2; - - gatherNodeParts(specifier, parts); - } - } else if (node.declaration) { - gatherNodeParts(node.declaration, parts); - } - } else if (t.isModuleSpecifier(node)) { - gatherNodeParts(node.local, parts); - } else if (t.isMemberExpression(node)) { - gatherNodeParts(node.object, parts); - gatherNodeParts(node.property, parts); - } else if (t.isIdentifier(node)) { - parts.push(node.name); - } else if (t.isLiteral(node)) { - parts.push(node.value); - } else if (t.isCallExpression(node)) { - gatherNodeParts(node.callee, parts); - } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { - for (var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var prop = _ref3; - - gatherNodeParts(prop.key || prop.argument, parts); - } - } -} - -var collectorVisitor = { - For: function For(path) { - for (var _iterator4 = t.FOR_INIT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var key = _ref4; - - var declar = path.get(key); - if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); - } - }, - Declaration: function Declaration(path) { - if (path.isBlockScoped()) return; - - if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return; - - path.scope.getFunctionParent().registerDeclaration(path); - }, - ReferencedIdentifier: function ReferencedIdentifier(path, state) { - state.references.push(path); - }, - ForXStatement: function ForXStatement(path, state) { - var left = path.get("left"); - if (left.isPattern() || left.isIdentifier()) { - state.constantViolations.push(left); - } - }, - - - ExportDeclaration: { - exit: function exit(path) { - var node = path.node, - scope = path.scope; - - var declar = node.declaration; - if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { - var _id = declar.id; - if (!_id) return; - - var binding = scope.getBinding(_id.name); - if (binding) binding.reference(path); - } else if (t.isVariableDeclaration(declar)) { - for (var _iterator5 = declar.declarations, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var decl = _ref5; - - var ids = t.getBindingIdentifiers(decl); - for (var name in ids) { - var _binding = scope.getBinding(name); - if (_binding) _binding.reference(path); - } - } - } - } - }, - - LabeledStatement: function LabeledStatement(path) { - path.scope.getProgramParent().addGlobal(path.node); - path.scope.getBlockParent().registerDeclaration(path); - }, - AssignmentExpression: function AssignmentExpression(path, state) { - state.assignments.push(path); - }, - UpdateExpression: function UpdateExpression(path, state) { - state.constantViolations.push(path.get("argument")); - }, - UnaryExpression: function UnaryExpression(path, state) { - if (path.node.operator === "delete") { - state.constantViolations.push(path.get("argument")); - } - }, - BlockScoped: function BlockScoped(path) { - var scope = path.scope; - if (scope.path === path) scope = scope.parent; - scope.getBlockParent().registerDeclaration(path); - }, - ClassDeclaration: function ClassDeclaration(path) { - var id = path.node.id; - if (!id) return; - - var name = id.name; - path.scope.bindings[name] = path.scope.getBinding(name); - }, - Block: function Block(path) { - var paths = path.get("body"); - for (var _iterator6 = paths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } - - var bodyPath = _ref6; - - if (bodyPath.isFunctionDeclaration()) { - path.scope.getBlockParent().registerDeclaration(bodyPath); - } - } - } -}; - -var uid = 0; - -var Scope = function () { - function Scope(path, parentScope) { - (0, _classCallCheck3.default)(this, Scope); - - if (parentScope && parentScope.block === path.node) { - return parentScope; - } - - var cached = getCache(path, parentScope, this); - if (cached) return cached; - - this.uid = uid++; - this.parent = parentScope; - this.hub = path.hub; - - this.parentBlock = path.parent; - this.block = path.node; - this.path = path; - - this.labels = new _map2.default(); - } - - Scope.prototype.traverse = function traverse(node, opts, state) { - (0, _index2.default)(node, opts, this, state, this.path); - }; - - Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - var id = this.generateUidIdentifier(name); - this.push({ id: id }); - return id; - }; - - Scope.prototype.generateUidIdentifier = function generateUidIdentifier() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - return t.identifier(this.generateUid(name)); - }; - - Scope.prototype.generateUid = function generateUid() { - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; - - name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); - - var uid = void 0; - var i = 0; - do { - uid = this._generateUid(name, i); - i++; - } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); - - var program = this.getProgramParent(); - program.references[uid] = true; - program.uids[uid] = true; - - return uid; - }; - - Scope.prototype._generateUid = function _generateUid(name, i) { - var id = name; - if (i > 1) id += i; - return "_" + id; - }; - - Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) { - var node = parent; - - if (t.isAssignmentExpression(parent)) { - node = parent.left; - } else if (t.isVariableDeclarator(parent)) { - node = parent.id; - } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) { - node = node.key; - } - - var parts = []; - gatherNodeParts(node, parts); - - var id = parts.join("$"); - id = id.replace(/^_/, "") || defaultName || "ref"; - - return this.generateUidIdentifier(id.slice(0, 20)); - }; - - Scope.prototype.isStatic = function isStatic(node) { - if (t.isThisExpression(node) || t.isSuper(node)) { - return true; - } - - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding) { - return binding.constant; - } else { - return this.hasBinding(node.name); - } - } - - return false; - }; - - Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) { - if (this.isStatic(node)) { - return null; - } else { - var _id2 = this.generateUidIdentifierBasedOnNode(node); - if (!dontPush) this.push({ id: _id2 }); - return _id2; - } - }; - - Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) { - if (kind === "param") return; - - if (kind === "hoisted" && local.kind === "let") return; - - var duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); - - if (duplicate) { - throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError); - } - }; - - Scope.prototype.rename = function rename(oldName, newName, block) { - var binding = this.getBinding(oldName); - if (binding) { - newName = newName || this.generateUidIdentifier(oldName).name; - return new _renamer2.default(binding, oldName, newName).rename(block); - } - }; - - Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) { - if (map[oldName]) { - map[newName] = value; - map[oldName] = null; - } - }; - - Scope.prototype.dump = function dump() { - var sep = (0, _repeat2.default)("-", 60); - console.log(sep); - var scope = this; - do { - console.log("#", scope.block.type); - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - console.log(" -", name, { - constant: binding.constant, - references: binding.references, - violations: binding.constantViolations.length, - kind: binding.kind - }); - } - } while (scope = scope.parent); - console.log(sep); - }; - - Scope.prototype.toArray = function toArray(node, i) { - var file = this.hub.file; - - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (binding && binding.constant && binding.path.isGenericType("Array")) return node; - } - - if (t.isArrayExpression(node)) { - return node; - } - - if (t.isIdentifier(node, { name: "arguments" })) { - return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); - } - - var helperName = "toArray"; - var args = [node]; - if (i === true) { - helperName = "toConsumableArray"; - } else if (i) { - args.push(t.numericLiteral(i)); - helperName = "slicedToArray"; - } - return t.callExpression(file.addHelper(helperName), args); - }; - - Scope.prototype.hasLabel = function hasLabel(name) { - return !!this.getLabel(name); - }; - - Scope.prototype.getLabel = function getLabel(name) { - return this.labels.get(name); - }; - - Scope.prototype.registerLabel = function registerLabel(path) { - this.labels.set(path.node.label.name, path); - }; - - Scope.prototype.registerDeclaration = function registerDeclaration(path) { - if (path.isLabeledStatement()) { - this.registerLabel(path); - } else if (path.isFunctionDeclaration()) { - this.registerBinding("hoisted", path.get("id"), path); - } else if (path.isVariableDeclaration()) { - var declarations = path.get("declarations"); - for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } - - var declar = _ref7; - - this.registerBinding(path.node.kind, declar); - } - } else if (path.isClassDeclaration()) { - this.registerBinding("let", path); - } else if (path.isImportDeclaration()) { - var specifiers = path.get("specifiers"); - for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; - - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } - - var specifier = _ref8; - - this.registerBinding("module", specifier); - } - } else if (path.isExportDeclaration()) { - var _declar = path.get("declaration"); - if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) { - this.registerDeclaration(_declar); - } - } else { - this.registerBinding("unknown", path); - } - }; - - Scope.prototype.buildUndefinedNode = function buildUndefinedNode() { - if (this.hasBinding("undefined")) { - return t.unaryExpression("void", t.numericLiteral(0), true); - } else { - return t.identifier("undefined"); - } - }; - - Scope.prototype.registerConstantViolation = function registerConstantViolation(path) { - var ids = path.getBindingIdentifiers(); - for (var name in ids) { - var binding = this.getBinding(name); - if (binding) binding.reassign(path); - } - }; - - Scope.prototype.registerBinding = function registerBinding(kind, path) { - var bindingPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : path; - - if (!kind) throw new ReferenceError("no `kind`"); - - if (path.isVariableDeclaration()) { - var declarators = path.get("declarations"); - for (var _iterator9 = declarators, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; - - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } - - var declar = _ref9; - - this.registerBinding(kind, declar); - } - return; - } - - var parent = this.getProgramParent(); - var ids = path.getBindingIdentifiers(true); - - for (var name in ids) { - for (var _iterator10 = ids[name], _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; - } - - var _id3 = _ref10; - - var local = this.getOwnBinding(name); - if (local) { - if (local.identifier === _id3) continue; - - this.checkBlockScopedCollisions(local, kind, name, _id3); - } - - if (local && local.path.isFlow()) local = null; - - parent.references[name] = true; - - this.bindings[name] = new _binding3.default({ - identifier: _id3, - existing: local, - scope: this, - path: bindingPath, - kind: kind - }); - } - } - }; - - Scope.prototype.addGlobal = function addGlobal(node) { - this.globals[node.name] = node; - }; - - Scope.prototype.hasUid = function hasUid(name) { - var scope = this; - - do { - if (scope.uids[name]) return true; - } while (scope = scope.parent); - - return false; - }; - - Scope.prototype.hasGlobal = function hasGlobal(name) { - var scope = this; - - do { - if (scope.globals[name]) return true; - } while (scope = scope.parent); - - return false; - }; - - Scope.prototype.hasReference = function hasReference(name) { - var scope = this; - - do { - if (scope.references[name]) return true; - } while (scope = scope.parent); - - return false; - }; - - Scope.prototype.isPure = function isPure(node, constantsOnly) { - if (t.isIdentifier(node)) { - var binding = this.getBinding(node.name); - if (!binding) return false; - if (constantsOnly) return binding.constant; - return true; - } else if (t.isClass(node)) { - if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false; - return this.isPure(node.body, constantsOnly); - } else if (t.isClassBody(node)) { - for (var _iterator11 = node.body, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : (0, _getIterator3.default)(_iterator11);;) { - var _ref11; - - if (_isArray11) { - if (_i11 >= _iterator11.length) break; - _ref11 = _iterator11[_i11++]; - } else { - _i11 = _iterator11.next(); - if (_i11.done) break; - _ref11 = _i11.value; - } - - var method = _ref11; - - if (!this.isPure(method, constantsOnly)) return false; - } - return true; - } else if (t.isBinary(node)) { - return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); - } else if (t.isArrayExpression(node)) { - for (var _iterator12 = node.elements, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : (0, _getIterator3.default)(_iterator12);;) { - var _ref12; - - if (_isArray12) { - if (_i12 >= _iterator12.length) break; - _ref12 = _iterator12[_i12++]; - } else { - _i12 = _iterator12.next(); - if (_i12.done) break; - _ref12 = _i12.value; - } - - var elem = _ref12; - - if (!this.isPure(elem, constantsOnly)) return false; - } - return true; - } else if (t.isObjectExpression(node)) { - for (var _iterator13 = node.properties, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : (0, _getIterator3.default)(_iterator13);;) { - var _ref13; - - if (_isArray13) { - if (_i13 >= _iterator13.length) break; - _ref13 = _iterator13[_i13++]; - } else { - _i13 = _iterator13.next(); - if (_i13.done) break; - _ref13 = _i13.value; - } - - var prop = _ref13; - - if (!this.isPure(prop, constantsOnly)) return false; - } - return true; - } else if (t.isClassMethod(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - if (node.kind === "get" || node.kind === "set") return false; - return true; - } else if (t.isClassProperty(node) || t.isObjectProperty(node)) { - if (node.computed && !this.isPure(node.key, constantsOnly)) return false; - return this.isPure(node.value, constantsOnly); - } else if (t.isUnaryExpression(node)) { - return this.isPure(node.argument, constantsOnly); - } else { - return t.isPureish(node); - } - }; - - Scope.prototype.setData = function setData(key, val) { - return this.data[key] = val; - }; - - Scope.prototype.getData = function getData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) return data; - } while (scope = scope.parent); - }; - - Scope.prototype.removeData = function removeData(key) { - var scope = this; - do { - var data = scope.data[key]; - if (data != null) scope.data[key] = null; - } while (scope = scope.parent); - }; - - Scope.prototype.init = function init() { - if (!this.references) this.crawl(); - }; - - Scope.prototype.crawl = function crawl() { - _crawlCallsCount++; - this._crawl(); - _crawlCallsCount--; - }; - - Scope.prototype._crawl = function _crawl() { - var path = this.path; - - this.references = (0, _create2.default)(null); - this.bindings = (0, _create2.default)(null); - this.globals = (0, _create2.default)(null); - this.uids = (0, _create2.default)(null); - this.data = (0, _create2.default)(null); - - if (path.isLoop()) { - for (var _iterator14 = t.FOR_INIT_KEYS, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : (0, _getIterator3.default)(_iterator14);;) { - var _ref14; - - if (_isArray14) { - if (_i14 >= _iterator14.length) break; - _ref14 = _iterator14[_i14++]; - } else { - _i14 = _iterator14.next(); - if (_i14.done) break; - _ref14 = _i14.value; - } - - var key = _ref14; - - var node = path.get(key); - if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); - } - } - - if (path.isFunctionExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path.get("id"), path); - } - } - - if (path.isClassExpression() && path.has("id")) { - if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { - this.registerBinding("local", path); - } - } - - if (path.isFunction()) { - var params = path.get("params"); - for (var _iterator15 = params, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : (0, _getIterator3.default)(_iterator15);;) { - var _ref15; - - if (_isArray15) { - if (_i15 >= _iterator15.length) break; - _ref15 = _iterator15[_i15++]; - } else { - _i15 = _iterator15.next(); - if (_i15.done) break; - _ref15 = _i15.value; - } - - var param = _ref15; - - this.registerBinding("param", param); - } - } - - if (path.isCatchClause()) { - this.registerBinding("let", path); - } - - var parent = this.getProgramParent(); - if (parent.crawling) return; - - var state = { - references: [], - constantViolations: [], - assignments: [] - }; - - this.crawling = true; - path.traverse(collectorVisitor, state); - this.crawling = false; - - for (var _iterator16 = state.assignments, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : (0, _getIterator3.default)(_iterator16);;) { - var _ref16; - - if (_isArray16) { - if (_i16 >= _iterator16.length) break; - _ref16 = _iterator16[_i16++]; - } else { - _i16 = _iterator16.next(); - if (_i16.done) break; - _ref16 = _i16.value; - } - - var _path = _ref16; - - var ids = _path.getBindingIdentifiers(); - var programParent = void 0; - for (var name in ids) { - if (_path.scope.getBinding(name)) continue; - - programParent = programParent || _path.scope.getProgramParent(); - programParent.addGlobal(ids[name]); - } - - _path.scope.registerConstantViolation(_path); - } - - for (var _iterator17 = state.references, _isArray17 = Array.isArray(_iterator17), _i17 = 0, _iterator17 = _isArray17 ? _iterator17 : (0, _getIterator3.default)(_iterator17);;) { - var _ref17; - - if (_isArray17) { - if (_i17 >= _iterator17.length) break; - _ref17 = _iterator17[_i17++]; - } else { - _i17 = _iterator17.next(); - if (_i17.done) break; - _ref17 = _i17.value; - } - - var ref = _ref17; - - var binding = ref.scope.getBinding(ref.node.name); - if (binding) { - binding.reference(ref); - } else { - ref.scope.getProgramParent().addGlobal(ref.node); - } - } - - for (var _iterator18 = state.constantViolations, _isArray18 = Array.isArray(_iterator18), _i18 = 0, _iterator18 = _isArray18 ? _iterator18 : (0, _getIterator3.default)(_iterator18);;) { - var _ref18; - - if (_isArray18) { - if (_i18 >= _iterator18.length) break; - _ref18 = _iterator18[_i18++]; - } else { - _i18 = _iterator18.next(); - if (_i18.done) break; - _ref18 = _i18.value; - } - - var _path2 = _ref18; - - _path2.scope.registerConstantViolation(_path2); - } - }; - - Scope.prototype.push = function push(opts) { - var path = this.path; - - if (!path.isBlockStatement() && !path.isProgram()) { - path = this.getBlockParent().path; - } - - if (path.isSwitchStatement()) { - path = this.getFunctionParent().path; - } - - if (path.isLoop() || path.isCatchClause() || path.isFunction()) { - t.ensureBlock(path.node); - path = path.get("body"); - } - - var unique = opts.unique; - var kind = opts.kind || "var"; - var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; - - var dataKey = "declaration:" + kind + ":" + blockHoist; - var declarPath = !unique && path.getData(dataKey); - - if (!declarPath) { - var declar = t.variableDeclaration(kind, []); - declar._generated = true; - declar._blockHoist = blockHoist; - - var _path$unshiftContaine = path.unshiftContainer("body", [declar]); - - declarPath = _path$unshiftContaine[0]; - - if (!unique) path.setData(dataKey, declarPath); - } - - var declarator = t.variableDeclarator(opts.id, opts.init); - declarPath.node.declarations.push(declarator); - this.registerBinding(kind, declarPath.get("declarations").pop()); - }; - - Scope.prototype.getProgramParent = function getProgramParent() { - var scope = this; - do { - if (scope.path.isProgram()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; - - Scope.prototype.getFunctionParent = function getFunctionParent() { - var scope = this; - do { - if (scope.path.isFunctionParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a Function or Program..."); - }; - - Scope.prototype.getBlockParent = function getBlockParent() { - var scope = this; - do { - if (scope.path.isBlockParent()) { - return scope; - } - } while (scope = scope.parent); - throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); - }; - - Scope.prototype.getAllBindings = function getAllBindings() { - var ids = (0, _create2.default)(null); - - var scope = this; - do { - (0, _defaults2.default)(ids, scope.bindings); - scope = scope.parent; - } while (scope); - - return ids; - }; - - Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind() { - var ids = (0, _create2.default)(null); - - for (var _iterator19 = arguments, _isArray19 = Array.isArray(_iterator19), _i19 = 0, _iterator19 = _isArray19 ? _iterator19 : (0, _getIterator3.default)(_iterator19);;) { - var _ref19; - - if (_isArray19) { - if (_i19 >= _iterator19.length) break; - _ref19 = _iterator19[_i19++]; - } else { - _i19 = _iterator19.next(); - if (_i19.done) break; - _ref19 = _i19.value; - } - - var kind = _ref19; - - var scope = this; - do { - for (var name in scope.bindings) { - var binding = scope.bindings[name]; - if (binding.kind === kind) ids[name] = binding; - } - scope = scope.parent; - } while (scope); - } - - return ids; - }; - - Scope.prototype.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) { - return this.getBindingIdentifier(name) === node; - }; - - Scope.prototype.warnOnFlowBinding = function warnOnFlowBinding(binding) { - if (_crawlCallsCount === 0 && binding && binding.path.isFlow()) { - console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 6.8. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "); - } - return binding; - }; - - Scope.prototype.getBinding = function getBinding(name) { - var scope = this; - - do { - var binding = scope.getOwnBinding(name); - if (binding) return this.warnOnFlowBinding(binding); - } while (scope = scope.parent); - }; - - Scope.prototype.getOwnBinding = function getOwnBinding(name) { - return this.warnOnFlowBinding(this.bindings[name]); - }; - - Scope.prototype.getBindingIdentifier = function getBindingIdentifier(name) { - var info = this.getBinding(name); - return info && info.identifier; - }; - - Scope.prototype.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) { - var binding = this.bindings[name]; - return binding && binding.identifier; - }; - - Scope.prototype.hasOwnBinding = function hasOwnBinding(name) { - return !!this.getOwnBinding(name); - }; - - Scope.prototype.hasBinding = function hasBinding(name, noGlobals) { - if (!name) return false; - if (this.hasOwnBinding(name)) return true; - if (this.parentHasBinding(name, noGlobals)) return true; - if (this.hasUid(name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.globals, name)) return true; - if (!noGlobals && (0, _includes2.default)(Scope.contextVariables, name)) return true; - return false; - }; - - Scope.prototype.parentHasBinding = function parentHasBinding(name, noGlobals) { - return this.parent && this.parent.hasBinding(name, noGlobals); - }; - - Scope.prototype.moveBindingTo = function moveBindingTo(name, scope) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - info.scope = scope; - scope.bindings[name] = info; - } - }; - - Scope.prototype.removeOwnBinding = function removeOwnBinding(name) { - delete this.bindings[name]; - }; - - Scope.prototype.removeBinding = function removeBinding(name) { - var info = this.getBinding(name); - if (info) { - info.scope.removeOwnBinding(name); - } - - var scope = this; - do { - if (scope.uids[name]) { - scope.uids[name] = false; - } - } while (scope = scope.parent); - }; - - return Scope; -}(); - -Scope.globals = (0, _keys2.default)(_globals2.default.builtin); -Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; -exports.default = Scope; -module.exports = exports["default"]; -},{"../cache":76,"../index":79,"./binding":97,"./lib/renamer":99,"babel-messages":53,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/map":58,"babel-runtime/core-js/object/create":61,"babel-runtime/core-js/object/keys":63,"babel-runtime/helpers/classCallCheck":70,"babel-types":112,"globals":242,"lodash/defaults":420,"lodash/includes":431,"lodash/repeat":454}],99:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); - -var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - -var _binding = require("../binding"); - -var _binding2 = _interopRequireDefault(_binding); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var renameVisitor = { - ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { - var node = _ref.node; - - if (node.name === state.oldName) { - node.name = state.newName; - } - }, - Scope: function Scope(path, state) { - if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { - path.skip(); - } - }, - "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { - var ids = path.getOuterBindingIdentifiers(); - - for (var name in ids) { - if (name === state.oldName) ids[name].name = state.newName; - } - } -}; - -var Renamer = function () { - function Renamer(binding, oldName, newName) { - (0, _classCallCheck3.default)(this, Renamer); - - this.newName = newName; - this.oldName = oldName; - this.binding = binding; - } - - Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { - var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; - if (!exportDeclar) return; - - var isDefault = exportDeclar.isExportDefaultDeclaration(); - - if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { - parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); - } - - var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); - var specifiers = []; - - for (var name in bindingIdentifiers) { - var localName = name === this.oldName ? this.newName : name; - var exportedName = isDefault ? "default" : name; - specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); - } - - if (specifiers.length) { - var aliasDeclar = t.exportNamedDeclaration(null, specifiers); - - if (parentDeclar.isFunctionDeclaration()) { - aliasDeclar._blockHoist = 3; - } - - exportDeclar.insertAfter(aliasDeclar); - exportDeclar.replaceWith(parentDeclar.node); - } - }; - - Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) { - return; - - if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return; - if (this.binding.kind !== "hoisted") return; - - path.node.id = t.identifier(this.oldName); - path.node._blockHoist = 3; - - path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))])); - }; - - Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) { - return; - - if (!path.isFunctionExpression() && !path.isClassExpression()) return; - if (this.binding.kind !== "local") return; - - path.node.id = t.identifier(this.oldName); - - this.binding.scope.parent.push({ - id: t.identifier(this.newName) - }); - - path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node)); - }; - - Renamer.prototype.rename = function rename(block) { - var binding = this.binding, - oldName = this.oldName, - newName = this.newName; - var scope = binding.scope, - path = binding.path; - - - var parentDeclar = path.find(function (path) { - return path.isDeclaration() || path.isFunctionExpression(); - }); - if (parentDeclar) { - this.maybeConvertFromExportDeclaration(parentDeclar); - } - - scope.traverse(block || scope.block, renameVisitor, this); - - if (!block) { - scope.removeOwnBinding(oldName); - scope.bindings[newName] = binding; - this.binding.identifier.name = newName; - } - - if (binding.type === "hoisted") {} - - if (parentDeclar) { - this.maybeConvertFromClassFunctionDeclaration(parentDeclar); - this.maybeConvertFromClassFunctionExpression(parentDeclar); - } - }; - - return Renamer; -}(); - -exports.default = Renamer; -module.exports = exports["default"]; -},{"../binding":97,"babel-runtime/helpers/classCallCheck":70,"babel-types":112}],100:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.explode = explode; -exports.verify = verify; -exports.merge = merge; - -var _virtualTypes = require("./path/lib/virtual-types"); - -var virtualTypes = _interopRequireWildcard(_virtualTypes); - -var _babelMessages = require("babel-messages"); - -var messages = _interopRequireWildcard(_babelMessages); - -var _babelTypes = require("babel-types"); - -var t = _interopRequireWildcard(_babelTypes); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function explode(visitor) { - if (visitor._exploded) return visitor; - visitor._exploded = true; - - for (var nodeType in visitor) { - if (shouldIgnoreKey(nodeType)) continue; - - var parts = nodeType.split("|"); - if (parts.length === 1) continue; - - var fns = visitor[nodeType]; - delete visitor[nodeType]; - - for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var part = _ref; - - visitor[part] = fns; - } - } - - verify(visitor); - - delete visitor.__esModule; - - ensureEntranceObjects(visitor); - - ensureCallbackArrays(visitor); - - for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _nodeType3 = _ref2; - - if (shouldIgnoreKey(_nodeType3)) continue; - - var wrapper = virtualTypes[_nodeType3]; - if (!wrapper) continue; - - var _fns2 = visitor[_nodeType3]; - for (var type in _fns2) { - _fns2[type] = wrapCheck(wrapper, _fns2[type]); - } - - delete visitor[_nodeType3]; - - if (wrapper.types) { - for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var _type = _ref4; - - if (visitor[_type]) { - mergePair(visitor[_type], _fns2); - } else { - visitor[_type] = _fns2; - } - } - } else { - mergePair(visitor, _fns2); - } - } - - for (var _nodeType in visitor) { - if (shouldIgnoreKey(_nodeType)) continue; - - var _fns = visitor[_nodeType]; - - var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; - - var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; - if (deprecratedKey) { - console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); - aliases = [deprecratedKey]; - } - - if (!aliases) continue; - - delete visitor[_nodeType]; - - for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var alias = _ref3; - - var existing = visitor[alias]; - if (existing) { - mergePair(existing, _fns); - } else { - visitor[alias] = (0, _clone2.default)(_fns); - } - } - } - - for (var _nodeType2 in visitor) { - if (shouldIgnoreKey(_nodeType2)) continue; - - ensureCallbackArrays(visitor[_nodeType2]); - } - - return visitor; -} - -function verify(visitor) { - if (visitor._verified) return; - - if (typeof visitor === "function") { - throw new Error(messages.get("traverseVerifyRootFunction")); - } - - for (var nodeType in visitor) { - if (nodeType === "enter" || nodeType === "exit") { - validateVisitorMethods(nodeType, visitor[nodeType]); - } - - if (shouldIgnoreKey(nodeType)) continue; - - if (t.TYPES.indexOf(nodeType) < 0) { - throw new Error(messages.get("traverseVerifyNodeType", nodeType)); - } - - var visitors = visitor[nodeType]; - if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { - for (var visitorKey in visitors) { - if (visitorKey === "enter" || visitorKey === "exit") { - validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); - } else { - throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); - } - } - } - } - - visitor._verified = true; -} - -function validateVisitorMethods(path, val) { - var fns = [].concat(val); - for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var fn = _ref5; - - if (typeof fn !== "function") { - throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); - } - } -} - -function merge(visitors) { - var states = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var wrapper = arguments[2]; - - var rootVisitor = {}; - - for (var i = 0; i < visitors.length; i++) { - var visitor = visitors[i]; - var state = states[i]; - - explode(visitor); - - for (var type in visitor) { - var visitorType = visitor[type]; - - if (state || wrapper) { - visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); - } - - var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; - mergePair(nodeVisitor, visitorType); - } - } - - return rootVisitor; -} - -function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { - var newVisitor = {}; - - var _loop = function _loop(key) { - var fns = oldVisitor[key]; - - if (!Array.isArray(fns)) return "continue"; - - fns = fns.map(function (fn) { - var newFn = fn; - - if (state) { - newFn = function newFn(path) { - return fn.call(state, path, state); - }; - } - - if (wrapper) { - newFn = wrapper(state.key, key, newFn); - } - - return newFn; - }); - - newVisitor[key] = fns; - }; - - for (var key in oldVisitor) { - var _ret = _loop(key); - - if (_ret === "continue") continue; - } - - return newVisitor; -} - -function ensureEntranceObjects(obj) { - for (var key in obj) { - if (shouldIgnoreKey(key)) continue; - - var fns = obj[key]; - if (typeof fns === "function") { - obj[key] = { enter: fns }; - } - } -} - -function ensureCallbackArrays(obj) { - if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; - if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; -} - -function wrapCheck(wrapper, fn) { - var newFn = function newFn(path) { - if (wrapper.checkPath(path)) { - return fn.apply(this, arguments); - } - }; - newFn.toString = function () { - return fn.toString(); - }; - return newFn; -} - -function shouldIgnoreKey(key) { - if (key[0] === "_") return true; - - if (key === "enter" || key === "exit" || key === "shouldSkip") return true; - - if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; - - return false; -} - -function mergePair(dest, src) { - for (var key in src) { - dest[key] = [].concat(dest[key] || [], src[key]); - } -} -},{"./path/lib/virtual-types":93,"babel-messages":53,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/object/keys":63,"babel-runtime/helpers/typeof":74,"babel-types":112,"lodash/clone":416}],101:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; - -var _for = require("babel-runtime/core-js/symbol/for"); - -var _for2 = _interopRequireDefault(_for); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var STATEMENT_OR_BLOCK_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; -var FLATTENABLE_KEYS = exports.FLATTENABLE_KEYS = ["body", "expressions"]; -var FOR_INIT_KEYS = exports.FOR_INIT_KEYS = ["left", "init"]; -var COMMENT_KEYS = exports.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; - -var LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = ["||", "&&"]; -var UPDATE_OPERATORS = exports.UPDATE_OPERATORS = ["++", "--"]; - -var BOOLEAN_NUMBER_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; -var EQUALITY_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; -var COMPARISON_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = [].concat(EQUALITY_BINARY_OPERATORS, ["in", "instanceof"]); -var BOOLEAN_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); -var NUMBER_BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; -var BINARY_OPERATORS = exports.BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS); - -var BOOLEAN_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; -var NUMBER_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; -var STRING_UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = ["typeof"]; -var UNARY_OPERATORS = exports.UNARY_OPERATORS = ["void"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS); - -var INHERIT_KEYS = exports.INHERIT_KEYS = { - optional: ["typeAnnotation", "typeParameters", "returnType"], - force: ["start", "loc", "end"] -}; - -var BLOCK_SCOPED_SYMBOL = exports.BLOCK_SCOPED_SYMBOL = (0, _for2.default)("var used to be block scoped"); -var NOT_LOCAL_BINDING = exports.NOT_LOCAL_BINDING = (0, _for2.default)("should not be considered a local binding"); -},{"babel-runtime/core-js/symbol/for":66}],102:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _maxSafeInteger = require("babel-runtime/core-js/number/max-safe-integer"); - -var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.toComputedKey = toComputedKey; -exports.toSequenceExpression = toSequenceExpression; -exports.toKeyAlias = toKeyAlias; -exports.toIdentifier = toIdentifier; -exports.toBindingIdentifierName = toBindingIdentifierName; -exports.toStatement = toStatement; -exports.toExpression = toExpression; -exports.toBlock = toBlock; -exports.valueToNode = valueToNode; - -var _isPlainObject = require("lodash/isPlainObject"); - -var _isPlainObject2 = _interopRequireDefault(_isPlainObject); - -var _isRegExp = require("lodash/isRegExp"); - -var _isRegExp2 = _interopRequireDefault(_isRegExp); - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toComputedKey(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key || node.property; - - if (!node.computed) { - if (t.isIdentifier(key)) key = t.stringLiteral(key.name); - } - return key; -} - -function toSequenceExpression(nodes, scope) { - if (!nodes || !nodes.length) return; - - var declars = []; - var bailed = false; - - var result = convert(nodes); - if (bailed) return; - - for (var i = 0; i < declars.length; i++) { - scope.push(declars[i]); - } - - return result; - - function convert(nodes) { - var ensureLastUndefined = false; - var exprs = []; - - for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var node = _ref; - - if (t.isExpression(node)) { - exprs.push(node); - } else if (t.isExpressionStatement(node)) { - exprs.push(node.expression); - } else if (t.isVariableDeclaration(node)) { - if (node.kind !== "var") return bailed = true; - - for (var _iterator2 = node.declarations, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var declar = _ref2; - - var bindings = t.getBindingIdentifiers(declar); - for (var key in bindings) { - declars.push({ - kind: node.kind, - id: bindings[key] - }); - } - - if (declar.init) { - exprs.push(t.assignmentExpression("=", declar.id, declar.init)); - } - } - - ensureLastUndefined = true; - continue; - } else if (t.isIfStatement(node)) { - var consequent = node.consequent ? convert([node.consequent]) : scope.buildUndefinedNode(); - var alternate = node.alternate ? convert([node.alternate]) : scope.buildUndefinedNode(); - if (!consequent || !alternate) return bailed = true; - - exprs.push(t.conditionalExpression(node.test, consequent, alternate)); - } else if (t.isBlockStatement(node)) { - exprs.push(convert(node.body)); - } else if (t.isEmptyStatement(node)) { - ensureLastUndefined = true; - continue; - } else { - return bailed = true; - } - - ensureLastUndefined = false; - } - - if (ensureLastUndefined || exprs.length === 0) { - exprs.push(scope.buildUndefinedNode()); - } - - if (exprs.length === 1) { - return exprs[0]; - } else { - return t.sequenceExpression(exprs); - } - } -} - -function toKeyAlias(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.key; - - var alias = void 0; - - if (node.kind === "method") { - return toKeyAlias.increment() + ""; - } else if (t.isIdentifier(key)) { - alias = key.name; - } else if (t.isStringLiteral(key)) { - alias = (0, _stringify2.default)(key.value); - } else { - alias = (0, _stringify2.default)(t.removePropertiesDeep(t.cloneDeep(key))); - } - - if (node.computed) { - alias = "[" + alias + "]"; - } - - if (node.static) { - alias = "static:" + alias; - } - - return alias; -} - -toKeyAlias.uid = 0; - -toKeyAlias.increment = function () { - if (toKeyAlias.uid >= _maxSafeInteger2.default) { - return toKeyAlias.uid = 0; - } else { - return toKeyAlias.uid++; - } -}; - -function toIdentifier(name) { - name = name + ""; - - name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); - - name = name.replace(/^[-0-9]+/, ""); - - name = name.replace(/[-\s]+(.)?/g, function (match, c) { - return c ? c.toUpperCase() : ""; - }); - - if (!t.isValidIdentifier(name)) { - name = "_" + name; - } - - return name || "_"; -} - -function toBindingIdentifierName(name) { - name = toIdentifier(name); - if (name === "eval" || name === "arguments") name = "_" + name; - return name; -} - -function toStatement(node, ignore) { - if (t.isStatement(node)) { - return node; - } - - var mustHaveId = false; - var newType = void 0; - - if (t.isClass(node)) { - mustHaveId = true; - newType = "ClassDeclaration"; - } else if (t.isFunction(node)) { - mustHaveId = true; - newType = "FunctionDeclaration"; - } else if (t.isAssignmentExpression(node)) { - return t.expressionStatement(node); - } - - if (mustHaveId && !node.id) { - newType = false; - } - - if (!newType) { - if (ignore) { - return false; - } else { - throw new Error("cannot turn " + node.type + " to a statement"); - } - } - - node.type = newType; - - return node; -} - -function toExpression(node) { - if (t.isExpressionStatement(node)) { - node = node.expression; - } - - if (t.isExpression(node)) { - return node; - } - - if (t.isClass(node)) { - node.type = "ClassExpression"; - } else if (t.isFunction(node)) { - node.type = "FunctionExpression"; - } - - if (!t.isExpression(node)) { - throw new Error("cannot turn " + node.type + " to an expression"); - } - - return node; -} - -function toBlock(node, parent) { - if (t.isBlockStatement(node)) { - return node; - } - - if (t.isEmptyStatement(node)) { - node = []; - } - - if (!Array.isArray(node)) { - if (!t.isStatement(node)) { - if (t.isFunction(parent)) { - node = t.returnStatement(node); - } else { - node = t.expressionStatement(node); - } - } - - node = [node]; - } - - return t.blockStatement(node); -} - -function valueToNode(value) { - if (value === undefined) { - return t.identifier("undefined"); - } - - if (value === true || value === false) { - return t.booleanLiteral(value); - } - - if (value === null) { - return t.nullLiteral(); - } - - if (typeof value === "string") { - return t.stringLiteral(value); - } - - if (typeof value === "number") { - return t.numericLiteral(value); - } - - if ((0, _isRegExp2.default)(value)) { - var pattern = value.source; - var flags = value.toString().match(/\/([a-z]+|)$/)[1]; - return t.regExpLiteral(pattern, flags); - } - - if (Array.isArray(value)) { - return t.arrayExpression(value.map(t.valueToNode)); - } - - if ((0, _isPlainObject2.default)(value)) { - var props = []; - for (var key in value) { - var nodeKey = void 0; - if (t.isValidIdentifier(key)) { - nodeKey = t.identifier(key); - } else { - nodeKey = t.stringLiteral(key); - } - props.push(t.objectProperty(nodeKey, t.valueToNode(value[key]))); - } - return t.objectExpression(props); - } - - throw new Error("don't know how to turn this value into a node"); -} -},{"./index":112,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/json/stringify":57,"babel-runtime/core-js/number/max-safe-integer":59,"lodash/isPlainObject":442,"lodash/isRegExp":443}],103:[function(require,module,exports){ -"use strict"; - -var _index = require("../index"); - -var t = _interopRequireWildcard(_index); - -var _constants = require("../constants"); - -var _index2 = require("./index"); - -var _index3 = _interopRequireDefault(_index2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -(0, _index3.default)("ArrayExpression", { - fields: { - elements: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), - default: [] - } - }, - visitor: ["elements"], - aliases: ["Expression"] -}); - -(0, _index3.default)("AssignmentExpression", { - fields: { - operator: { - validate: (0, _index2.assertValueType)("string") - }, - left: { - validate: (0, _index2.assertNodeType)("LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Expression"] -}); - -(0, _index3.default)("BinaryExpression", { - builder: ["operator", "left", "right"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.BINARY_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - visitor: ["left", "right"], - aliases: ["Binary", "Expression"] -}); - -(0, _index3.default)("Directive", { - visitor: ["value"], - fields: { - value: { - validate: (0, _index2.assertNodeType)("DirectiveLiteral") - } - } -}); - -(0, _index3.default)("DirectiveLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } - } -}); - -(0, _index3.default)("BlockStatement", { - builder: ["body", "directives"], - visitor: ["directives", "body"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "Statement"] -}); - -(0, _index3.default)("BreakStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); - -(0, _index3.default)("CallExpression", { - visitor: ["callee", "arguments"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) - } - }, - aliases: ["Expression"] -}); - -(0, _index3.default)("CatchClause", { - visitor: ["param", "body"], - fields: { - param: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - } - }, - aliases: ["Scopable"] -}); - -(0, _index3.default)("ConditionalExpression", { - visitor: ["test", "consequent", "alternate"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Expression") - }, - alternate: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Expression", "Conditional"] -}); - -(0, _index3.default)("ContinueStatement", { - visitor: ["label"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - } - }, - aliases: ["Statement", "Terminatorless", "CompletionStatement"] -}); - -(0, _index3.default)("DebuggerStatement", { - aliases: ["Statement"] -}); - -(0, _index3.default)("DoWhileStatement", { - visitor: ["test", "body"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - }, - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] -}); - -(0, _index3.default)("EmptyStatement", { - aliases: ["Statement"] -}); - -(0, _index3.default)("ExpressionStatement", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index2.assertNodeType)("Expression") - } - }, - aliases: ["Statement", "ExpressionWrapper"] -}); - -(0, _index3.default)("File", { - builder: ["program", "comments", "tokens"], - visitor: ["program"], - fields: { - program: { - validate: (0, _index2.assertNodeType)("Program") - } - } -}); - -(0, _index3.default)("ForInStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("ForStatement", { - visitor: ["init", "test", "update", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], - fields: { - init: { - validate: (0, _index2.assertNodeType)("VariableDeclaration", "Expression"), - optional: true - }, - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - update: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("FunctionDeclaration", { - builder: ["id", "params", "body", "generator", "async"], - visitor: ["id", "params", "body", "returnType", "typeParameters"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] -}); - -(0, _index3.default)("FunctionExpression", { - inherits: "FunctionDeclaration", - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("Identifier"), - optional: true - }, - params: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - } -}); - -(0, _index3.default)("Identifier", { - builder: ["name"], - visitor: ["typeAnnotation"], - aliases: ["Expression", "LVal"], - fields: { - name: { - validate: function validate(node, key, val) { - if (!t.isValidIdentifier(val)) {} - } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index3.default)("IfStatement", { - visitor: ["test", "consequent", "alternate"], - aliases: ["Statement", "Conditional"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - consequent: { - validate: (0, _index2.assertNodeType)("Statement") - }, - alternate: { - optional: true, - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("LabeledStatement", { - visitor: ["label", "body"], - aliases: ["Statement"], - fields: { - label: { - validate: (0, _index2.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index2.assertNodeType)("Statement") - } - } -}); - -(0, _index3.default)("StringLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("string") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("NumericLiteral", { - builder: ["value"], - deprecatedAlias: "NumberLiteral", - fields: { - value: { - validate: (0, _index2.assertValueType)("number") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("NullLiteral", { - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("BooleanLiteral", { - builder: ["value"], - fields: { - value: { - validate: (0, _index2.assertValueType)("boolean") - } - }, - aliases: ["Expression", "Pureish", "Literal", "Immutable"] -}); - -(0, _index3.default)("RegExpLiteral", { - builder: ["pattern", "flags"], - deprecatedAlias: "RegexLiteral", - aliases: ["Expression", "Literal"], - fields: { - pattern: { - validate: (0, _index2.assertValueType)("string") - }, - flags: { - validate: (0, _index2.assertValueType)("string"), - default: "" - } - } -}); - -(0, _index3.default)("LogicalExpression", { - builder: ["operator", "left", "right"], - visitor: ["left", "right"], - aliases: ["Binary", "Expression"], - fields: { - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.LOGICAL_OPERATORS) - }, - left: { - validate: (0, _index2.assertNodeType)("Expression") - }, - right: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); - -(0, _index3.default)("MemberExpression", { - builder: ["object", "property", "computed"], - visitor: ["object", "property"], - aliases: ["Expression", "LVal"], - fields: { - object: { - validate: (0, _index2.assertNodeType)("Expression") - }, - property: { - validate: function validate(node, key, val) { - var expectedType = node.computed ? "Expression" : "Identifier"; - (0, _index2.assertNodeType)(expectedType)(node, key, val); - } - }, - computed: { - default: false - } - } -}); - -(0, _index3.default)("NewExpression", { - visitor: ["callee", "arguments"], - aliases: ["Expression"], - fields: { - callee: { - validate: (0, _index2.assertNodeType)("Expression") - }, - arguments: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) - } - } -}); - -(0, _index3.default)("Program", { - visitor: ["directives", "body"], - builder: ["body", "directives"], - fields: { - directives: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), - default: [] - }, - body: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - }, - aliases: ["Scopable", "BlockParent", "Block", "FunctionParent"] -}); - -(0, _index3.default)("ObjectExpression", { - visitor: ["properties"], - aliases: ["Expression"], - fields: { - properties: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadProperty"))) - } - } -}); - -(0, _index3.default)("ObjectMethod", { - builder: ["kind", "key", "params", "body", "computed"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("method", "get", "set")), - default: "method" - }, - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index2.assertValueType)("boolean") - } - }, - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] -}); - -(0, _index3.default)("ObjectProperty", { - builder: ["key", "value", "computed", "shorthand", "decorators"], - fields: { - computed: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - value: { - validate: (0, _index2.assertNodeType)("Expression") - }, - shorthand: { - validate: (0, _index2.assertValueType)("boolean"), - default: false - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))), - optional: true - } - }, - visitor: ["key", "value", "decorators"], - aliases: ["UserWhitespacable", "Property", "ObjectMember"] -}); - -(0, _index3.default)("RestElement", { - visitor: ["argument", "typeAnnotation"], - aliases: ["LVal"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("LVal") - }, - decorators: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index3.default)("ReturnStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - } - } -}); - -(0, _index3.default)("SequenceExpression", { - visitor: ["expressions"], - fields: { - expressions: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression"))) - } - }, - aliases: ["Expression"] -}); - -(0, _index3.default)("SwitchCase", { - visitor: ["test", "consequent"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression"), - optional: true - }, - consequent: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) - } - } -}); - -(0, _index3.default)("SwitchStatement", { - visitor: ["discriminant", "cases"], - aliases: ["Statement", "BlockParent", "Scopable"], - fields: { - discriminant: { - validate: (0, _index2.assertNodeType)("Expression") - }, - cases: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("SwitchCase"))) - } - } -}); - -(0, _index3.default)("ThisExpression", { - aliases: ["Expression"] -}); - -(0, _index3.default)("ThrowStatement", { - visitor: ["argument"], - aliases: ["Statement", "Terminatorless", "CompletionStatement"], - fields: { - argument: { - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); - -(0, _index3.default)("TryStatement", { - visitor: ["block", "handler", "finalizer"], - aliases: ["Statement"], - fields: { - body: { - validate: (0, _index2.assertNodeType)("BlockStatement") - }, - handler: { - optional: true, - handler: (0, _index2.assertNodeType)("BlockStatement") - }, - finalizer: { - optional: true, - validate: (0, _index2.assertNodeType)("BlockStatement") - } - } -}); - -(0, _index3.default)("UnaryExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: true - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UNARY_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["UnaryLike", "Expression"] -}); - -(0, _index3.default)("UpdateExpression", { - builder: ["operator", "argument", "prefix"], - fields: { - prefix: { - default: false - }, - argument: { - validate: (0, _index2.assertNodeType)("Expression") - }, - operator: { - validate: _index2.assertOneOf.apply(undefined, _constants.UPDATE_OPERATORS) - } - }, - visitor: ["argument"], - aliases: ["Expression"] -}); - -(0, _index3.default)("VariableDeclaration", { - builder: ["kind", "declarations"], - visitor: ["declarations"], - aliases: ["Statement", "Declaration"], - fields: { - kind: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("var", "let", "const")) - }, - declarations: { - validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("VariableDeclarator"))) - } - } -}); - -(0, _index3.default)("VariableDeclarator", { - visitor: ["id", "init"], - fields: { - id: { - validate: (0, _index2.assertNodeType)("LVal") - }, - init: { - optional: true, - validate: (0, _index2.assertNodeType)("Expression") - } - } -}); - -(0, _index3.default)("WhileStatement", { - visitor: ["test", "body"], - aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], - fields: { - test: { - validate: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } - } -}); - -(0, _index3.default)("WithStatement", { - visitor: ["object", "body"], - aliases: ["Statement"], - fields: { - object: { - object: (0, _index2.assertNodeType)("Expression") - }, - body: { - validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") - } - } -}); -},{"../constants":101,"../index":112,"./index":107}],104:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("AssignmentPattern", { - visitor: ["left", "right"], - aliases: ["Pattern", "LVal"], - fields: { - left: { - validate: (0, _index.assertNodeType)("Identifier") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ArrayPattern", { - visitor: ["elements", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - elements: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ArrowFunctionExpression", { - builder: ["params", "body", "async"], - visitor: ["params", "body", "returnType", "typeParameters"], - aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], - fields: { - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement", "Expression") - }, - async: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); - -(0, _index2.default)("ClassBody", { - visitor: ["body"], - fields: { - body: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ClassMethod", "ClassProperty"))) - } - } -}); - -(0, _index2.default)("ClassDeclaration", { - builder: ["id", "superClass", "body", "decorators"], - visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], - aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], - fields: { - id: { - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ClassExpression", { - inherits: "ClassDeclaration", - aliases: ["Scopable", "Class", "Expression", "Pureish"], - fields: { - id: { - optional: true, - validate: (0, _index.assertNodeType)("Identifier") - }, - body: { - validate: (0, _index.assertNodeType)("ClassBody") - }, - superClass: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("ExportAllDeclaration", { - visitor: ["source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); - -(0, _index2.default)("ExportDefaultDeclaration", { - visitor: ["declaration"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("FunctionDeclaration", "ClassDeclaration", "Expression") - } - } -}); - -(0, _index2.default)("ExportNamedDeclaration", { - visitor: ["declaration", "specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], - fields: { - declaration: { - validate: (0, _index.assertNodeType)("Declaration"), - optional: true - }, - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ExportSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral"), - optional: true - } - } -}); - -(0, _index2.default)("ExportSpecifier", { - visitor: ["local", "exported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ForOfStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); - -(0, _index2.default)("ImportDeclaration", { - visitor: ["specifiers", "source"], - aliases: ["Statement", "Declaration", "ModuleDeclaration"], - fields: { - specifiers: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) - }, - source: { - validate: (0, _index.assertNodeType)("StringLiteral") - } - } -}); - -(0, _index2.default)("ImportDefaultSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ImportNamespaceSpecifier", { - visitor: ["local"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ImportSpecifier", { - visitor: ["local", "imported"], - aliases: ["ModuleSpecifier"], - fields: { - local: { - validate: (0, _index.assertNodeType)("Identifier") - }, - imported: { - validate: (0, _index.assertNodeType)("Identifier") - }, - importKind: { - validate: (0, _index.assertOneOf)(null, "type", "typeof") - } - } -}); - -(0, _index2.default)("MetaProperty", { - visitor: ["meta", "property"], - aliases: ["Expression"], - fields: { - meta: { - validate: (0, _index.assertValueType)("string") - }, - property: { - validate: (0, _index.assertValueType)("string") - } - } -}); - -(0, _index2.default)("ClassMethod", { - aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], - builder: ["kind", "key", "params", "body", "computed", "static"], - visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], - fields: { - kind: { - validate: (0, _index.chain)((0, _index.assertValueType)("string"), (0, _index.assertOneOf)("get", "set", "method", "constructor")), - default: "method" - }, - computed: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - static: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - key: { - validate: function validate(node, key, val) { - var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; - _index.assertNodeType.apply(undefined, expectedTypes)(node, key, val); - } - }, - params: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) - }, - body: { - validate: (0, _index.assertNodeType)("BlockStatement") - }, - generator: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - async: { - default: false, - validate: (0, _index.assertValueType)("boolean") - } - } -}); - -(0, _index2.default)("ObjectPattern", { - visitor: ["properties", "typeAnnotation"], - aliases: ["Pattern", "LVal"], - fields: { - properties: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("RestProperty", "Property"))) - }, - decorators: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) - } - } -}); - -(0, _index2.default)("SpreadElement", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("Super", { - aliases: ["Expression"] -}); - -(0, _index2.default)("TaggedTemplateExpression", { - visitor: ["tag", "quasi"], - aliases: ["Expression"], - fields: { - tag: { - validate: (0, _index.assertNodeType)("Expression") - }, - quasi: { - validate: (0, _index.assertNodeType)("TemplateLiteral") - } - } -}); - -(0, _index2.default)("TemplateElement", { - builder: ["value", "tail"], - fields: { - value: {}, - tail: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); - -(0, _index2.default)("TemplateLiteral", { - visitor: ["quasis", "expressions"], - aliases: ["Expression", "Literal"], - fields: { - quasis: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("TemplateElement"))) - }, - expressions: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) - } - } -}); - -(0, _index2.default)("YieldExpression", { - builder: ["argument", "delegate"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - delegate: { - validate: (0, _index.assertValueType)("boolean"), - default: false - }, - argument: { - optional: true, - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":107}],105:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("AwaitExpression", { - builder: ["argument"], - visitor: ["argument"], - aliases: ["Expression", "Terminatorless"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("ForAwaitStatement", { - visitor: ["left", "right", "body"], - aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], - fields: { - left: { - validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") - }, - right: { - validate: (0, _index.assertNodeType)("Expression") - }, - body: { - validate: (0, _index.assertNodeType)("Statement") - } - } -}); - -(0, _index2.default)("BindExpression", { - visitor: ["object", "callee"], - aliases: ["Expression"], - fields: {} -}); - -(0, _index2.default)("Import", { - aliases: ["Expression"] -}); - -(0, _index2.default)("Decorator", { - visitor: ["expression"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("DoExpression", { - visitor: ["body"], - aliases: ["Expression"], - fields: { - body: { - validate: (0, _index.assertNodeType)("BlockStatement") - } - } -}); - -(0, _index2.default)("ExportDefaultSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("ExportNamespaceSpecifier", { - visitor: ["exported"], - aliases: ["ModuleSpecifier"], - fields: { - exported: { - validate: (0, _index.assertNodeType)("Identifier") - } - } -}); - -(0, _index2.default)("RestProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("LVal") - } - } -}); - -(0, _index2.default)("SpreadProperty", { - visitor: ["argument"], - aliases: ["UnaryLike"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":107}],106:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("AnyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("ArrayTypeAnnotation", { - visitor: ["elementType"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("BooleanTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("BooleanLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("NullLiteralTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("ClassImplements", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("ClassProperty", { - visitor: ["key", "value", "typeAnnotation", "decorators"], - builder: ["key", "value", "typeAnnotation", "decorators", "computed"], - aliases: ["Property"], - fields: { - computed: { - validate: (0, _index.assertValueType)("boolean"), - default: false - } - } -}); - -(0, _index2.default)("DeclareClass", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareFunction", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareInterface", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareModule", { - visitor: ["id", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareModuleExports", { - visitor: ["typeAnnotation"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareTypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("DeclareVariable", { - visitor: ["id"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("ExistentialTypeParam", { - aliases: ["Flow"] -}); - -(0, _index2.default)("FunctionTypeAnnotation", { - visitor: ["typeParameters", "params", "rest", "returnType"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("FunctionTypeParam", { - visitor: ["name", "typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("GenericTypeAnnotation", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("InterfaceExtends", { - visitor: ["id", "typeParameters"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("InterfaceDeclaration", { - visitor: ["id", "typeParameters", "extends", "body"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("IntersectionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("MixedTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); - -(0, _index2.default)("EmptyTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"] -}); - -(0, _index2.default)("NullableTypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("NumericLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("NumberTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("StringLiteralTypeAnnotation", { - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("StringTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("ThisTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); - -(0, _index2.default)("TupleTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeofTypeAnnotation", { - visitor: ["argument"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeAlias", { - visitor: ["id", "typeParameters", "right"], - aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], - fields: {} -}); - -(0, _index2.default)("TypeAnnotation", { - visitor: ["typeAnnotation"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeCastExpression", { - visitor: ["expression", "typeAnnotation"], - aliases: ["Flow", "ExpressionWrapper", "Expression"], - fields: {} -}); - -(0, _index2.default)("TypeParameter", { - visitor: ["bound"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeParameterDeclaration", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("TypeParameterInstantiation", { - visitor: ["params"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeAnnotation", { - visitor: ["properties", "indexers", "callProperties"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeCallProperty", { - visitor: ["value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeIndexer", { - visitor: ["id", "key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("ObjectTypeProperty", { - visitor: ["key", "value"], - aliases: ["Flow", "UserWhitespacable"], - fields: {} -}); - -(0, _index2.default)("QualifiedTypeIdentifier", { - visitor: ["id", "qualification"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("UnionTypeAnnotation", { - visitor: ["types"], - aliases: ["Flow"], - fields: {} -}); - -(0, _index2.default)("VoidTypeAnnotation", { - aliases: ["Flow", "FlowBaseAnnotation"], - fields: {} -}); -},{"./index":107}],107:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = undefined; - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -exports.assertEach = assertEach; -exports.assertOneOf = assertOneOf; -exports.assertNodeType = assertNodeType; -exports.assertNodeOrValueType = assertNodeOrValueType; -exports.assertValueType = assertValueType; -exports.chain = chain; -exports.default = defineType; - -var _index = require("../index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var VISITOR_KEYS = exports.VISITOR_KEYS = {}; -var ALIAS_KEYS = exports.ALIAS_KEYS = {}; -var NODE_FIELDS = exports.NODE_FIELDS = {}; -var BUILDER_KEYS = exports.BUILDER_KEYS = {}; -var DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {}; - -function getType(val) { - if (Array.isArray(val)) { - return "array"; - } else if (val === null) { - return "null"; - } else if (val === undefined) { - return "undefined"; - } else { - return typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val); - } -} - -function assertEach(callback) { - function validator(node, key, val) { - if (!Array.isArray(val)) return; - - for (var i = 0; i < val.length; i++) { - callback(node, key + "[" + i + "]", val[i]); - } - } - validator.each = callback; - return validator; -} - -function assertOneOf() { - for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) { - vals[_key] = arguments[_key]; - } - - function validate(node, key, val) { - if (vals.indexOf(val) < 0) { - throw new TypeError("Property " + key + " expected value to be one of " + (0, _stringify2.default)(vals) + " but got " + (0, _stringify2.default)(val)); - } - } - - validate.oneOf = vals; - - return validate; -} - -function assertNodeType() { - for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - types[_key2] = arguments[_key2]; - } - - function validate(node, key, val) { - var valid = false; - - for (var _iterator = types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var type = _ref; - - if (t.is(type, val)) { - valid = true; - break; - } - } - - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); - } - } - - validate.oneOfNodeTypes = types; - - return validate; -} - -function assertNodeOrValueType() { - for (var _len3 = arguments.length, types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - types[_key3] = arguments[_key3]; - } - - function validate(node, key, val) { - var valid = false; - - for (var _iterator2 = types, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var type = _ref2; - - if (getType(val) === type || t.is(type, val)) { - valid = true; - break; - } - } - - if (!valid) { - throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); - } - } - - validate.oneOfNodeOrValueTypes = types; - - return validate; -} - -function assertValueType(type) { - function validate(node, key, val) { - var valid = getType(val) === type; - - if (!valid) { - throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); - } - } - - validate.type = type; - - return validate; -} - -function chain() { - for (var _len4 = arguments.length, fns = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - fns[_key4] = arguments[_key4]; - } - - function validate() { - for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var fn = _ref3; - - fn.apply(undefined, arguments); - } - } - validate.chainOf = fns; - return validate; -} - -function defineType(type) { - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var inherits = opts.inherits && store[opts.inherits] || {}; - - opts.fields = opts.fields || inherits.fields || {}; - opts.visitor = opts.visitor || inherits.visitor || []; - opts.aliases = opts.aliases || inherits.aliases || []; - opts.builder = opts.builder || inherits.builder || opts.visitor || []; - - if (opts.deprecatedAlias) { - DEPRECATED_KEYS[opts.deprecatedAlias] = type; - } - - for (var _iterator4 = opts.visitor.concat(opts.builder), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var _key5 = _ref4; - - opts.fields[_key5] = opts.fields[_key5] || {}; - } - - for (var key in opts.fields) { - var field = opts.fields[key]; - - if (opts.builder.indexOf(key) === -1) { - field.optional = true; - } - if (field.default === undefined) { - field.default = null; - } else if (!field.validate) { - field.validate = assertValueType(getType(field.default)); - } - } - - VISITOR_KEYS[type] = opts.visitor; - BUILDER_KEYS[type] = opts.builder; - NODE_FIELDS[type] = opts.fields; - ALIAS_KEYS[type] = opts.aliases; - - store[type] = opts; -} - -var store = {}; -},{"../index":112,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/json/stringify":57,"babel-runtime/helpers/typeof":74}],108:[function(require,module,exports){ -"use strict"; - -require("./index"); - -require("./core"); - -require("./es2015"); - -require("./flow"); - -require("./jsx"); - -require("./misc"); - -require("./experimental"); -},{"./core":103,"./es2015":104,"./experimental":105,"./flow":106,"./index":107,"./jsx":109,"./misc":110}],109:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("JSXAttribute", { - visitor: ["name", "value"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXNamespacedName") - }, - value: { - optional: true, - validate: (0, _index.assertNodeType)("JSXElement", "StringLiteral", "JSXExpressionContainer") - } - } -}); - -(0, _index2.default)("JSXClosingElement", { - visitor: ["name"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - } - } -}); - -(0, _index2.default)("JSXElement", { - builder: ["openingElement", "closingElement", "children", "selfClosing"], - visitor: ["openingElement", "children", "closingElement"], - aliases: ["JSX", "Immutable", "Expression"], - fields: { - openingElement: { - validate: (0, _index.assertNodeType)("JSXOpeningElement") - }, - closingElement: { - optional: true, - validate: (0, _index.assertNodeType)("JSXClosingElement") - }, - children: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement"))) - } - } -}); - -(0, _index2.default)("JSXEmptyExpression", { - aliases: ["JSX", "Expression"] -}); - -(0, _index2.default)("JSXExpressionContainer", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("JSXSpreadChild", { - visitor: ["expression"], - aliases: ["JSX", "Immutable"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("JSXIdentifier", { - builder: ["name"], - aliases: ["JSX", "Expression"], - fields: { - name: { - validate: (0, _index.assertValueType)("string") - } - } -}); - -(0, _index2.default)("JSXMemberExpression", { - visitor: ["object", "property"], - aliases: ["JSX", "Expression"], - fields: { - object: { - validate: (0, _index.assertNodeType)("JSXMemberExpression", "JSXIdentifier") - }, - property: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } - } -}); - -(0, _index2.default)("JSXNamespacedName", { - visitor: ["namespace", "name"], - aliases: ["JSX"], - fields: { - namespace: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - }, - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier") - } - } -}); - -(0, _index2.default)("JSXOpeningElement", { - builder: ["name", "attributes", "selfClosing"], - visitor: ["name", "attributes"], - aliases: ["JSX", "Immutable"], - fields: { - name: { - validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") - }, - selfClosing: { - default: false, - validate: (0, _index.assertValueType)("boolean") - }, - attributes: { - validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) - } - } -}); - -(0, _index2.default)("JSXSpreadAttribute", { - visitor: ["argument"], - aliases: ["JSX"], - fields: { - argument: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); - -(0, _index2.default)("JSXText", { - aliases: ["JSX", "Immutable"], - builder: ["value"], - fields: { - value: { - validate: (0, _index.assertValueType)("string") - } - } -}); -},{"./index":107}],110:[function(require,module,exports){ -"use strict"; - -var _index = require("./index"); - -var _index2 = _interopRequireDefault(_index); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -(0, _index2.default)("Noop", { - visitor: [] -}); - -(0, _index2.default)("ParenthesizedExpression", { - visitor: ["expression"], - aliases: ["Expression", "ExpressionWrapper"], - fields: { - expression: { - validate: (0, _index.assertNodeType)("Expression") - } - } -}); -},{"./index":107}],111:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.createUnionTypeAnnotation = createUnionTypeAnnotation; -exports.removeTypeDuplicates = removeTypeDuplicates; -exports.createTypeAnnotationBasedOnTypeof = createTypeAnnotationBasedOnTypeof; - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function createUnionTypeAnnotation(types) { - var flattened = removeTypeDuplicates(types); - - if (flattened.length === 1) { - return flattened[0]; - } else { - return t.unionTypeAnnotation(flattened); - } -} - -function removeTypeDuplicates(nodes) { - var generics = {}; - var bases = {}; - - var typeGroups = []; - - var types = []; - - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (!node) continue; - - if (types.indexOf(node) >= 0) { - continue; - } - - if (t.isAnyTypeAnnotation(node)) { - return [node]; - } - - if (t.isFlowBaseAnnotation(node)) { - bases[node.type] = node; - continue; - } - - if (t.isUnionTypeAnnotation(node)) { - if (typeGroups.indexOf(node.types) < 0) { - nodes = nodes.concat(node.types); - typeGroups.push(node.types); - } - continue; - } - - if (t.isGenericTypeAnnotation(node)) { - var name = node.id.name; - - if (generics[name]) { - var existing = generics[name]; - if (existing.typeParameters) { - if (node.typeParameters) { - existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); - } - } else { - existing = node.typeParameters; - } - } else { - generics[name] = node; - } - - continue; - } - - types.push(node); - } - - for (var type in bases) { - types.push(bases[type]); - } - - for (var _name in generics) { - types.push(generics[_name]); - } - - return types; -} - -function createTypeAnnotationBasedOnTypeof(type) { - if (type === "string") { - return t.stringTypeAnnotation(); - } else if (type === "number") { - return t.numberTypeAnnotation(); - } else if (type === "undefined") { - return t.voidTypeAnnotation(); - } else if (type === "boolean") { - return t.booleanTypeAnnotation(); - } else if (type === "function") { - return t.genericTypeAnnotation(t.identifier("Function")); - } else if (type === "object") { - return t.genericTypeAnnotation(t.identifier("Object")); - } else if (type === "symbol") { - return t.genericTypeAnnotation(t.identifier("Symbol")); - } else { - throw new Error("Invalid typeof value"); - } -} -},{"./index":112}],112:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.createTypeAnnotationBasedOnTypeof = exports.removeTypeDuplicates = exports.createUnionTypeAnnotation = exports.valueToNode = exports.toBlock = exports.toExpression = exports.toStatement = exports.toBindingIdentifierName = exports.toIdentifier = exports.toKeyAlias = exports.toSequenceExpression = exports.toComputedKey = exports.isNodesEquivalent = exports.isImmutable = exports.isScope = exports.isSpecifierDefault = exports.isVar = exports.isBlockScoped = exports.isLet = exports.isValidIdentifier = exports.isReferenced = exports.isBinding = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.TYPES = exports.react = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; - -var _getOwnPropertySymbols = require("babel-runtime/core-js/object/get-own-property-symbols"); - -var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _stringify = require("babel-runtime/core-js/json/stringify"); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _constants = require("./constants"); - -Object.defineProperty(exports, "STATEMENT_OR_BLOCK_KEYS", { - enumerable: true, - get: function get() { - return _constants.STATEMENT_OR_BLOCK_KEYS; - } -}); -Object.defineProperty(exports, "FLATTENABLE_KEYS", { - enumerable: true, - get: function get() { - return _constants.FLATTENABLE_KEYS; - } -}); -Object.defineProperty(exports, "FOR_INIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.FOR_INIT_KEYS; - } -}); -Object.defineProperty(exports, "COMMENT_KEYS", { - enumerable: true, - get: function get() { - return _constants.COMMENT_KEYS; - } -}); -Object.defineProperty(exports, "LOGICAL_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.LOGICAL_OPERATORS; - } -}); -Object.defineProperty(exports, "UPDATE_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UPDATE_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "EQUALITY_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.EQUALITY_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "COMPARISON_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.COMPARISON_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BINARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BINARY_OPERATORS; - } -}); -Object.defineProperty(exports, "BOOLEAN_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.BOOLEAN_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "NUMBER_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.NUMBER_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "STRING_UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.STRING_UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "UNARY_OPERATORS", { - enumerable: true, - get: function get() { - return _constants.UNARY_OPERATORS; - } -}); -Object.defineProperty(exports, "INHERIT_KEYS", { - enumerable: true, - get: function get() { - return _constants.INHERIT_KEYS; - } -}); -Object.defineProperty(exports, "BLOCK_SCOPED_SYMBOL", { - enumerable: true, - get: function get() { - return _constants.BLOCK_SCOPED_SYMBOL; - } -}); -Object.defineProperty(exports, "NOT_LOCAL_BINDING", { - enumerable: true, - get: function get() { - return _constants.NOT_LOCAL_BINDING; - } -}); -exports.is = is; -exports.isType = isType; -exports.validate = validate; -exports.shallowEqual = shallowEqual; -exports.appendToMemberExpression = appendToMemberExpression; -exports.prependToMemberExpression = prependToMemberExpression; -exports.ensureBlock = ensureBlock; -exports.clone = clone; -exports.cloneWithoutLoc = cloneWithoutLoc; -exports.cloneDeep = cloneDeep; -exports.buildMatchMemberExpression = buildMatchMemberExpression; -exports.removeComments = removeComments; -exports.inheritsComments = inheritsComments; -exports.inheritTrailingComments = inheritTrailingComments; -exports.inheritLeadingComments = inheritLeadingComments; -exports.inheritInnerComments = inheritInnerComments; -exports.inherits = inherits; -exports.assertNode = assertNode; -exports.isNode = isNode; -exports.traverseFast = traverseFast; -exports.removeProperties = removeProperties; -exports.removePropertiesDeep = removePropertiesDeep; - -var _retrievers = require("./retrievers"); - -Object.defineProperty(exports, "getBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getBindingIdentifiers; - } -}); -Object.defineProperty(exports, "getOuterBindingIdentifiers", { - enumerable: true, - get: function get() { - return _retrievers.getOuterBindingIdentifiers; - } -}); - -var _validators = require("./validators"); - -Object.defineProperty(exports, "isBinding", { - enumerable: true, - get: function get() { - return _validators.isBinding; - } -}); -Object.defineProperty(exports, "isReferenced", { - enumerable: true, - get: function get() { - return _validators.isReferenced; - } -}); -Object.defineProperty(exports, "isValidIdentifier", { - enumerable: true, - get: function get() { - return _validators.isValidIdentifier; - } -}); -Object.defineProperty(exports, "isLet", { - enumerable: true, - get: function get() { - return _validators.isLet; - } -}); -Object.defineProperty(exports, "isBlockScoped", { - enumerable: true, - get: function get() { - return _validators.isBlockScoped; - } -}); -Object.defineProperty(exports, "isVar", { - enumerable: true, - get: function get() { - return _validators.isVar; - } -}); -Object.defineProperty(exports, "isSpecifierDefault", { - enumerable: true, - get: function get() { - return _validators.isSpecifierDefault; - } -}); -Object.defineProperty(exports, "isScope", { - enumerable: true, - get: function get() { - return _validators.isScope; - } -}); -Object.defineProperty(exports, "isImmutable", { - enumerable: true, - get: function get() { - return _validators.isImmutable; - } -}); -Object.defineProperty(exports, "isNodesEquivalent", { - enumerable: true, - get: function get() { - return _validators.isNodesEquivalent; - } -}); - -var _converters = require("./converters"); - -Object.defineProperty(exports, "toComputedKey", { - enumerable: true, - get: function get() { - return _converters.toComputedKey; - } -}); -Object.defineProperty(exports, "toSequenceExpression", { - enumerable: true, - get: function get() { - return _converters.toSequenceExpression; - } -}); -Object.defineProperty(exports, "toKeyAlias", { - enumerable: true, - get: function get() { - return _converters.toKeyAlias; - } -}); -Object.defineProperty(exports, "toIdentifier", { - enumerable: true, - get: function get() { - return _converters.toIdentifier; - } -}); -Object.defineProperty(exports, "toBindingIdentifierName", { - enumerable: true, - get: function get() { - return _converters.toBindingIdentifierName; - } -}); -Object.defineProperty(exports, "toStatement", { - enumerable: true, - get: function get() { - return _converters.toStatement; - } -}); -Object.defineProperty(exports, "toExpression", { - enumerable: true, - get: function get() { - return _converters.toExpression; - } -}); -Object.defineProperty(exports, "toBlock", { - enumerable: true, - get: function get() { - return _converters.toBlock; - } -}); -Object.defineProperty(exports, "valueToNode", { - enumerable: true, - get: function get() { - return _converters.valueToNode; - } -}); - -var _flow = require("./flow"); - -Object.defineProperty(exports, "createUnionTypeAnnotation", { - enumerable: true, - get: function get() { - return _flow.createUnionTypeAnnotation; - } -}); -Object.defineProperty(exports, "removeTypeDuplicates", { - enumerable: true, - get: function get() { - return _flow.removeTypeDuplicates; - } -}); -Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { - enumerable: true, - get: function get() { - return _flow.createTypeAnnotationBasedOnTypeof; - } -}); - -var _toFastProperties = require("to-fast-properties"); - -var _toFastProperties2 = _interopRequireDefault(_toFastProperties); - -var _clone = require("lodash/clone"); - -var _clone2 = _interopRequireDefault(_clone); - -var _uniq = require("lodash/uniq"); - -var _uniq2 = _interopRequireDefault(_uniq); - -require("./definitions/init"); - -var _definitions = require("./definitions"); - -var _react2 = require("./react"); - -var _react = _interopRequireWildcard(_react2); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var t = exports; - -function registerType(type) { - var is = t["is" + type]; - if (!is) { - is = t["is" + type] = function (node, opts) { - return t.is(type, node, opts); - }; - } - - t["assert" + type] = function (node, opts) { - opts = opts || {}; - if (!is(node, opts)) { - throw new Error("Expected type " + (0, _stringify2.default)(type) + " with option " + (0, _stringify2.default)(opts)); - } - }; -} - -exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; -exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; -exports.NODE_FIELDS = _definitions.NODE_FIELDS; -exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; -exports.DEPRECATED_KEYS = _definitions.DEPRECATED_KEYS; -exports.react = _react; - - -for (var type in t.VISITOR_KEYS) { - registerType(type); -} - -t.FLIPPED_ALIAS_KEYS = {}; - -(0, _keys2.default)(t.ALIAS_KEYS).forEach(function (type) { - t.ALIAS_KEYS[type].forEach(function (alias) { - var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; - types.push(type); - }); -}); - -(0, _keys2.default)(t.FLIPPED_ALIAS_KEYS).forEach(function (type) { - t[type.toUpperCase() + "_TYPES"] = t.FLIPPED_ALIAS_KEYS[type]; - registerType(type); -}); - -var TYPES = exports.TYPES = (0, _keys2.default)(t.VISITOR_KEYS).concat((0, _keys2.default)(t.FLIPPED_ALIAS_KEYS)).concat((0, _keys2.default)(t.DEPRECATED_KEYS)); - -function is(type, node, opts) { - if (!node) return false; - - var matches = isType(node.type, type); - if (!matches) return false; - - if (typeof opts === "undefined") { - return true; - } else { - return t.shallowEqual(node, opts); - } -} - -function isType(nodeType, targetType) { - if (nodeType === targetType) return true; - - if (t.ALIAS_KEYS[targetType]) return false; - - var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; - if (aliases) { - if (aliases[0] === nodeType) return true; - - for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var alias = _ref; - - if (nodeType === alias) return true; - } - } - - return false; -} - -(0, _keys2.default)(t.BUILDER_KEYS).forEach(function (type) { - var keys = t.BUILDER_KEYS[type]; - - function builder() { - if (arguments.length > keys.length) { - throw new Error("t." + type + ": Too many arguments passed. Received " + arguments.length + " but can receive " + ("no more than " + keys.length)); - } - - var node = {}; - node.type = type; - - var i = 0; - - for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var _key = _ref2; - - var field = t.NODE_FIELDS[type][_key]; - - var arg = arguments[i++]; - if (arg === undefined) arg = (0, _clone2.default)(field.default); - - node[_key] = arg; - } - - for (var key in node) { - validate(node, key, node[key]); - } - - return node; - } - - t[type] = builder; - t[type[0].toLowerCase() + type.slice(1)] = builder; -}); - -var _loop = function _loop(_type) { - var newType = t.DEPRECATED_KEYS[_type]; - - function proxy(fn) { - return function () { - console.trace("The node type " + _type + " has been renamed to " + newType); - return fn.apply(this, arguments); - }; - } - - t[_type] = t[_type[0].toLowerCase() + _type.slice(1)] = proxy(t[newType]); - t["is" + _type] = proxy(t["is" + newType]); - t["assert" + _type] = proxy(t["assert" + newType]); -}; - -for (var _type in t.DEPRECATED_KEYS) { - _loop(_type); -} - -function validate(node, key, val) { - if (!node) return; - - var fields = t.NODE_FIELDS[node.type]; - if (!fields) return; - - var field = fields[key]; - if (!field || !field.validate) return; - if (field.optional && val == null) return; - - field.validate(node, key, val); -} - -function shallowEqual(actual, expected) { - var keys = (0, _keys2.default)(expected); - - for (var _iterator3 = keys, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { - var _ref3; - - if (_isArray3) { - if (_i3 >= _iterator3.length) break; - _ref3 = _iterator3[_i3++]; - } else { - _i3 = _iterator3.next(); - if (_i3.done) break; - _ref3 = _i3.value; - } - - var key = _ref3; - - if (actual[key] !== expected[key]) { - return false; - } - } - - return true; -} - -function appendToMemberExpression(member, append, computed) { - member.object = t.memberExpression(member.object, member.property, member.computed); - member.property = append; - member.computed = !!computed; - return member; -} - -function prependToMemberExpression(member, prepend) { - member.object = t.memberExpression(prepend, member.object); - return member; -} - -function ensureBlock(node) { - var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "body"; - - return node[key] = t.toBlock(node[key], node); -} - -function clone(node) { - if (!node) return node; - var newNode = {}; - for (var key in node) { - if (key[0] === "_") continue; - newNode[key] = node[key]; - } - return newNode; -} - -function cloneWithoutLoc(node) { - var newNode = clone(node); - delete newNode.loc; - return newNode; -} - -function cloneDeep(node) { - if (!node) return node; - var newNode = {}; - - for (var key in node) { - if (key[0] === "_") continue; - - var val = node[key]; - - if (val) { - if (val.type) { - val = t.cloneDeep(val); - } else if (Array.isArray(val)) { - val = val.map(t.cloneDeep); - } - } - - newNode[key] = val; - } - - return newNode; -} - -function buildMatchMemberExpression(match, allowPartial) { - var parts = match.split("."); - - return function (member) { - if (!t.isMemberExpression(member)) return false; - - var search = [member]; - var i = 0; - - while (search.length) { - var node = search.shift(); - - if (allowPartial && i === parts.length) { - return true; - } - - if (t.isIdentifier(node)) { - if (parts[i] !== node.name) return false; - } else if (t.isStringLiteral(node)) { - if (parts[i] !== node.value) return false; - } else if (t.isMemberExpression(node)) { - if (node.computed && !t.isStringLiteral(node.property)) { - return false; - } else { - search.push(node.object); - search.push(node.property); - continue; - } - } else { - return false; - } - - if (++i > parts.length) { - return false; - } - } - - return true; - }; -} - -function removeComments(node) { - for (var _iterator4 = t.COMMENT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { - var _ref4; - - if (_isArray4) { - if (_i4 >= _iterator4.length) break; - _ref4 = _iterator4[_i4++]; - } else { - _i4 = _iterator4.next(); - if (_i4.done) break; - _ref4 = _i4.value; - } - - var key = _ref4; - - delete node[key]; - } - return node; -} - -function inheritsComments(child, parent) { - inheritTrailingComments(child, parent); - inheritLeadingComments(child, parent); - inheritInnerComments(child, parent); - return child; -} - -function inheritTrailingComments(child, parent) { - _inheritComments("trailingComments", child, parent); -} - -function inheritLeadingComments(child, parent) { - _inheritComments("leadingComments", child, parent); -} - -function inheritInnerComments(child, parent) { - _inheritComments("innerComments", child, parent); -} - -function _inheritComments(key, child, parent) { - if (child && parent) { - child[key] = (0, _uniq2.default)([].concat(child[key], parent[key]).filter(Boolean)); - } -} - -function inherits(child, parent) { - if (!child || !parent) return child; - - for (var _iterator5 = t.INHERIT_KEYS.optional, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { - var _ref5; - - if (_isArray5) { - if (_i5 >= _iterator5.length) break; - _ref5 = _iterator5[_i5++]; - } else { - _i5 = _iterator5.next(); - if (_i5.done) break; - _ref5 = _i5.value; - } - - var _key2 = _ref5; - - if (child[_key2] == null) { - child[_key2] = parent[_key2]; - } - } - - for (var key in parent) { - if (key[0] === "_") child[key] = parent[key]; - } - - for (var _iterator6 = t.INHERIT_KEYS.force, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { - var _ref6; - - if (_isArray6) { - if (_i6 >= _iterator6.length) break; - _ref6 = _iterator6[_i6++]; - } else { - _i6 = _iterator6.next(); - if (_i6.done) break; - _ref6 = _i6.value; - } - - var _key3 = _ref6; - - child[_key3] = parent[_key3]; - } - - t.inheritsComments(child, parent); - - return child; -} - -function assertNode(node) { - if (!isNode(node)) { - throw new TypeError("Not a valid node " + (node && node.type)); - } -} - -function isNode(node) { - return !!(node && _definitions.VISITOR_KEYS[node.type]); -} - -(0, _toFastProperties2.default)(t); -(0, _toFastProperties2.default)(t.VISITOR_KEYS); - -function traverseFast(node, enter, opts) { - if (!node) return; - - var keys = t.VISITOR_KEYS[node.type]; - if (!keys) return; - - opts = opts || {}; - enter(node, opts); - - for (var _iterator7 = keys, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { - var _ref7; - - if (_isArray7) { - if (_i7 >= _iterator7.length) break; - _ref7 = _iterator7[_i7++]; - } else { - _i7 = _iterator7.next(); - if (_i7.done) break; - _ref7 = _i7.value; - } - - var key = _ref7; - - var subNode = node[key]; - - if (Array.isArray(subNode)) { - for (var _iterator8 = subNode, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { - var _ref8; - - if (_isArray8) { - if (_i8 >= _iterator8.length) break; - _ref8 = _iterator8[_i8++]; - } else { - _i8 = _iterator8.next(); - if (_i8.done) break; - _ref8 = _i8.value; - } - - var _node = _ref8; - - traverseFast(_node, enter, opts); - } - } else { - traverseFast(subNode, enter, opts); - } - } -} - -var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; - -var CLEAR_KEYS_PLUS_COMMENTS = t.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); - -function removeProperties(node, opts) { - opts = opts || {}; - var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; - for (var _iterator9 = map, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { - var _ref9; - - if (_isArray9) { - if (_i9 >= _iterator9.length) break; - _ref9 = _iterator9[_i9++]; - } else { - _i9 = _iterator9.next(); - if (_i9.done) break; - _ref9 = _i9.value; - } - - var _key4 = _ref9; - - if (node[_key4] != null) node[_key4] = undefined; - } - - for (var key in node) { - if (key[0] === "_" && node[key] != null) node[key] = undefined; - } - - var syms = (0, _getOwnPropertySymbols2.default)(node); - for (var _iterator10 = syms, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { - var _ref10; - - if (_isArray10) { - if (_i10 >= _iterator10.length) break; - _ref10 = _iterator10[_i10++]; - } else { - _i10 = _iterator10.next(); - if (_i10.done) break; - _ref10 = _i10.value; - } - - var sym = _ref10; - - node[sym] = null; - } -} - -function removePropertiesDeep(tree, opts) { - traverseFast(tree, removeProperties, opts); - return tree; -} -},{"./constants":101,"./converters":102,"./definitions":107,"./definitions/init":108,"./flow":111,"./react":113,"./retrievers":114,"./validators":115,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/json/stringify":57,"babel-runtime/core-js/object/get-own-property-symbols":62,"babel-runtime/core-js/object/keys":63,"lodash/clone":416,"lodash/uniq":464,"to-fast-properties":487}],113:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; -exports.isReactComponent = undefined; -exports.isCompatTag = isCompatTag; -exports.buildChildren = buildChildren; - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -var isReactComponent = exports.isReactComponent = t.buildMatchMemberExpression("React.Component"); - -function isCompatTag(tagName) { - return !!tagName && /^[a-z]|\-/.test(tagName); -} - -function cleanJSXElementLiteralChild(child, args) { - var lines = child.value.split(/\r\n|\n|\r/); - - var lastNonEmptyLine = 0; - - for (var i = 0; i < lines.length; i++) { - if (lines[i].match(/[^ \t]/)) { - lastNonEmptyLine = i; - } - } - - var str = ""; - - for (var _i = 0; _i < lines.length; _i++) { - var line = lines[_i]; - - var isFirstLine = _i === 0; - var isLastLine = _i === lines.length - 1; - var isLastNonEmptyLine = _i === lastNonEmptyLine; - - var trimmedLine = line.replace(/\t/g, " "); - - if (!isFirstLine) { - trimmedLine = trimmedLine.replace(/^[ ]+/, ""); - } - - if (!isLastLine) { - trimmedLine = trimmedLine.replace(/[ ]+$/, ""); - } - - if (trimmedLine) { - if (!isLastNonEmptyLine) { - trimmedLine += " "; - } - - str += trimmedLine; - } - } - - if (str) args.push(t.stringLiteral(str)); -} - -function buildChildren(node) { - var elems = []; - - for (var i = 0; i < node.children.length; i++) { - var child = node.children[i]; - - if (t.isJSXText(child)) { - cleanJSXElementLiteralChild(child, elems); - continue; - } - - if (t.isJSXExpressionContainer(child)) child = child.expression; - if (t.isJSXEmptyExpression(child)) continue; - - elems.push(child); - } - - return elems; -} -},{"./index":112}],114:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _create = require("babel-runtime/core-js/object/create"); - -var _create2 = _interopRequireDefault(_create); - -exports.getBindingIdentifiers = getBindingIdentifiers; -exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function getBindingIdentifiers(node, duplicates, outerOnly) { - var search = [].concat(node); - var ids = (0, _create2.default)(null); - - while (search.length) { - var id = search.shift(); - if (!id) continue; - - var keys = t.getBindingIdentifiers.keys[id.type]; - - if (t.isIdentifier(id)) { - if (duplicates) { - var _ids = ids[id.name] = ids[id.name] || []; - _ids.push(id); - } else { - ids[id.name] = id; - } - continue; - } - - if (t.isExportDeclaration(id)) { - if (t.isDeclaration(id.declaration)) { - search.push(id.declaration); - } - continue; - } - - if (outerOnly) { - if (t.isFunctionDeclaration(id)) { - search.push(id.id); - continue; - } - - if (t.isFunctionExpression(id)) { - continue; - } - } - - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (id[key]) { - search = search.concat(id[key]); - } - } - } - } - - return ids; -} - -getBindingIdentifiers.keys = { - DeclareClass: ["id"], - DeclareFunction: ["id"], - DeclareModule: ["id"], - DeclareVariable: ["id"], - InterfaceDeclaration: ["id"], - TypeAlias: ["id"], - - CatchClause: ["param"], - LabeledStatement: ["label"], - UnaryExpression: ["argument"], - AssignmentExpression: ["left"], - - ImportSpecifier: ["local"], - ImportNamespaceSpecifier: ["local"], - ImportDefaultSpecifier: ["local"], - ImportDeclaration: ["specifiers"], - - ExportSpecifier: ["exported"], - ExportNamespaceSpecifier: ["exported"], - ExportDefaultSpecifier: ["exported"], - - FunctionDeclaration: ["id", "params"], - FunctionExpression: ["id", "params"], - - ClassDeclaration: ["id"], - ClassExpression: ["id"], - - RestElement: ["argument"], - UpdateExpression: ["argument"], - - RestProperty: ["argument"], - ObjectProperty: ["value"], - - AssignmentPattern: ["left"], - ArrayPattern: ["elements"], - ObjectPattern: ["properties"], - - VariableDeclaration: ["declarations"], - VariableDeclarator: ["id"] -}; - -function getOuterBindingIdentifiers(node, duplicates) { - return getBindingIdentifiers(node, duplicates, true); -} -},{"./index":112,"babel-runtime/core-js/object/create":61}],115:[function(require,module,exports){ -"use strict"; - -exports.__esModule = true; - -var _keys = require("babel-runtime/core-js/object/keys"); - -var _keys2 = _interopRequireDefault(_keys); - -var _typeof2 = require("babel-runtime/helpers/typeof"); - -var _typeof3 = _interopRequireDefault(_typeof2); - -var _getIterator2 = require("babel-runtime/core-js/get-iterator"); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -exports.isBinding = isBinding; -exports.isReferenced = isReferenced; -exports.isValidIdentifier = isValidIdentifier; -exports.isLet = isLet; -exports.isBlockScoped = isBlockScoped; -exports.isVar = isVar; -exports.isSpecifierDefault = isSpecifierDefault; -exports.isScope = isScope; -exports.isImmutable = isImmutable; -exports.isNodesEquivalent = isNodesEquivalent; - -var _retrievers = require("./retrievers"); - -var _esutils = require("esutils"); - -var _esutils2 = _interopRequireDefault(_esutils); - -var _index = require("./index"); - -var t = _interopRequireWildcard(_index); - -var _constants = require("./constants"); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isBinding(node, parent) { - var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; - if (keys) { - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var val = parent[key]; - if (Array.isArray(val)) { - if (val.indexOf(node) >= 0) return true; - } else { - if (val === node) return true; - } - } - } - - return false; -} - -function isReferenced(node, parent) { - switch (parent.type) { - case "BindExpression": - return parent.object === node || parent.callee === node; - - case "MemberExpression": - case "JSXMemberExpression": - if (parent.property === node && parent.computed) { - return true; - } else if (parent.object === node) { - return true; - } else { - return false; - } - - case "MetaProperty": - return false; - - case "ObjectProperty": - if (parent.key === node) { - return parent.computed; - } - - case "VariableDeclarator": - return parent.id !== node; - - case "ArrowFunctionExpression": - case "FunctionDeclaration": - case "FunctionExpression": - for (var _iterator = parent.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var param = _ref; - - if (param === node) return false; - } - - return parent.id !== node; - - case "ExportSpecifier": - if (parent.source) { - return false; - } else { - return parent.local === node; - } - - case "ExportNamespaceSpecifier": - case "ExportDefaultSpecifier": - return false; - - case "JSXAttribute": - return parent.name !== node; - - case "ClassProperty": - if (parent.key === node) { - return parent.computed; - } else { - return parent.value === node; - } - - case "ImportDefaultSpecifier": - case "ImportNamespaceSpecifier": - case "ImportSpecifier": - return false; - - case "ClassDeclaration": - case "ClassExpression": - return parent.id !== node; - - case "ClassMethod": - case "ObjectMethod": - return parent.key === node && parent.computed; - - case "LabeledStatement": - return false; - - case "CatchClause": - return parent.param !== node; - - case "RestElement": - return false; - - case "AssignmentExpression": - return parent.right === node; - - case "AssignmentPattern": - return parent.right === node; - - case "ObjectPattern": - case "ArrayPattern": - return false; - } - - return true; -} - -function isValidIdentifier(name) { - if (typeof name !== "string" || _esutils2.default.keyword.isReservedWordES6(name, true)) { - return false; - } else { - return _esutils2.default.keyword.isIdentifierNameES6(name); - } -} - -function isLet(node) { - return t.isVariableDeclaration(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); -} - -function isBlockScoped(node) { - return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node); -} - -function isVar(node) { - return t.isVariableDeclaration(node, { kind: "var" }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; -} - -function isSpecifierDefault(specifier) { - return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); -} - -function isScope(node, parent) { - if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { - return false; - } - - return t.isScopable(node); -} - -function isImmutable(node) { - if (t.isType(node.type, "Immutable")) return true; - - if (t.isIdentifier(node)) { - if (node.name === "undefined") { - return true; - } else { - return false; - } - } - - return false; -} - -function isNodesEquivalent(a, b) { - if ((typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || (typeof a === "undefined" ? "undefined" : (0, _typeof3.default)(a)) !== "object" || a == null || b == null) { - return a === b; - } - - if (a.type !== b.type) { - return false; - } - - var fields = (0, _keys2.default)(t.NODE_FIELDS[a.type] || a.type); - - for (var _iterator2 = fields, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { - var _ref2; - - if (_isArray2) { - if (_i2 >= _iterator2.length) break; - _ref2 = _iterator2[_i2++]; - } else { - _i2 = _iterator2.next(); - if (_i2.done) break; - _ref2 = _i2.value; - } - - var field = _ref2; - - if ((0, _typeof3.default)(a[field]) !== (0, _typeof3.default)(b[field])) { - return false; - } - - if (Array.isArray(a[field])) { - if (!Array.isArray(b[field])) { - return false; - } - if (a[field].length !== b[field].length) { - return false; - } - - for (var i = 0; i < a[field].length; i++) { - if (!isNodesEquivalent(a[field][i], b[field][i])) { - return false; - } - } - continue; - } - - if (!isNodesEquivalent(a[field], b[field])) { - return false; - } - } - - return true; -} -},{"./constants":101,"./index":112,"./retrievers":114,"babel-runtime/core-js/get-iterator":56,"babel-runtime/core-js/object/keys":63,"babel-runtime/helpers/typeof":74,"esutils":240}],116:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -/* eslint max-len: 0 */ - -// This is a trick taken from Esprima. It turns out that, on -// non-Chrome browsers, to check whether a string is in a set, a -// predicate containing a big ugly `switch` statement is faster than -// a regular expression, and on Chrome the two are about on par. -// This function uses `eval` (non-lexical) to produce such a -// predicate from a space-separated string of words. -// -// It starts by sorting the words by length. - -function makePredicate(words) { - words = words.split(" "); - return function (str) { - return words.indexOf(str) >= 0; - }; -} - -// Reserved word lists for various dialects of the language - -var reservedWords = { - 6: makePredicate("enum await"), - strict: makePredicate("implements interface let package private protected public static yield"), - strictBind: makePredicate("eval arguments") -}; - -// And the keywords - -var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super"); - -// ## Character categories - -// Big ugly regular expressions that match characters in the -// whitespace, identifier, and identifier-start categories. These -// are only applied when a character is found to actually have a -// code point above 128. -// Generated by `bin/generate-identifier-regex.js`. - -var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; -var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA900-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F"; - -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - -// These are a run-length and offset encoded representation of the -// >0xffff code points that are a valid part of identifiers. The -// offset starts at 0x10000, and each pair of numbers represents an -// offset to the next range, and then a size of the range. They were -// generated by `bin/generate-identifier-regex.js`. -// eslint-disable-next-line comma-spacing -var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 785, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 54, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 86, 25, 391, 63, 32, 0, 449, 56, 264, 8, 2, 36, 18, 0, 50, 29, 881, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 65, 0, 32, 6124, 20, 754, 9486, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 60, 67, 1213, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 10591, 541]; -// eslint-disable-next-line comma-spacing -var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 10, 2, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 87, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 423, 9, 838, 7, 2, 7, 17, 9, 57, 21, 2, 13, 19882, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 2214, 6, 110, 6, 6, 9, 792487, 239]; - -// This has a complexity linear to the value of the code. The -// assumption is that looking up astral identifier characters is -// rare. -function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) return false; - - pos += set[i + 1]; - if (pos >= code) return true; - } -} - -// Test whether a given character code starts an identifier. - -function isIdentifierStart(code) { - if (code < 65) return code === 36; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes); -} - -// Test whether a given character is part of an identifier. - -function isIdentifierChar(code) { - if (code < 48) return code === 36; - if (code < 58) return true; - if (code < 65) return false; - if (code < 91) return true; - if (code < 97) return code === 95; - if (code < 123) return true; - if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); -} - -// A second optional argument can be given to further configure -var defaultOptions = { - // Source type ("script" or "module") for different semantics - sourceType: "script", - // Source filename. - sourceFilename: undefined, - // Line from which to start counting source. Useful for - // integration with other tools. - startLine: 1, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program. - allowImportExportEverywhere: false, - // TODO - allowSuperOutsideMethod: false, - // An array of plugins to enable - plugins: [], - // TODO - strictMode: null -}; - -// Interpret and default an options object - -function getOptions(opts) { - var options = {}; - for (var key in defaultOptions) { - options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; - } - return options; -} - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; -} : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; - - - - - - - - - - - -var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; - - - - - - - - - - - -var inherits = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; -}; - - - - - - - - - - - -var possibleConstructorReturn = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return call && (typeof call === "object" || typeof call === "function") ? call : self; -}; - -// ## Token types - -// The assignment of fine-grained, information-carrying type objects -// allows the tokenizer to store the information it has about a -// token in a way that is very cheap for the parser to look up. - -// All token type variables start with an underscore, to make them -// easy to recognize. - -// The `beforeExpr` property is used to disambiguate between regular -// expressions and divisions. It is set on all token types that can -// be followed by an expression (thus, a slash after them would be a -// regular expression). -// -// `isLoop` marks a keyword as starting a loop, which is important -// to know when parsing a label, in order to allow or disallow -// continue jumps to that label. - -var beforeExpr = true; -var startsExpr = true; -var isLoop = true; -var isAssign = true; -var prefix = true; -var postfix = true; - -var TokenType = function TokenType(label) { - var conf = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, TokenType); - - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.rightAssociative = !!conf.rightAssociative; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; -}; - -var KeywordTokenType = function (_TokenType) { - inherits(KeywordTokenType, _TokenType); - - function KeywordTokenType(name) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - classCallCheck(this, KeywordTokenType); - - options.keyword = name; - - return possibleConstructorReturn(this, _TokenType.call(this, name, options)); - } - - return KeywordTokenType; -}(TokenType); - -var BinopTokenType = function (_TokenType2) { - inherits(BinopTokenType, _TokenType2); - - function BinopTokenType(name, prec) { - classCallCheck(this, BinopTokenType); - return possibleConstructorReturn(this, _TokenType2.call(this, name, { beforeExpr: beforeExpr, binop: prec })); - } - - return BinopTokenType; -}(TokenType); - -var types = { - num: new TokenType("num", { startsExpr: startsExpr }), - regexp: new TokenType("regexp", { startsExpr: startsExpr }), - string: new TokenType("string", { startsExpr: startsExpr }), - name: new TokenType("name", { startsExpr: startsExpr }), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - bracketR: new TokenType("]"), - braceL: new TokenType("{", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceBarL: new TokenType("{|", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - braceR: new TokenType("}"), - braceBarR: new TokenType("|}"), - parenL: new TokenType("(", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - parenR: new TokenType(")"), - comma: new TokenType(",", { beforeExpr: beforeExpr }), - semi: new TokenType(";", { beforeExpr: beforeExpr }), - colon: new TokenType(":", { beforeExpr: beforeExpr }), - doubleColon: new TokenType("::", { beforeExpr: beforeExpr }), - dot: new TokenType("."), - question: new TokenType("?", { beforeExpr: beforeExpr }), - arrow: new TokenType("=>", { beforeExpr: beforeExpr }), - template: new TokenType("template"), - ellipsis: new TokenType("...", { beforeExpr: beforeExpr }), - backQuote: new TokenType("`", { startsExpr: startsExpr }), - dollarBraceL: new TokenType("${", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - at: new TokenType("@"), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", { beforeExpr: beforeExpr, isAssign: isAssign }), - assign: new TokenType("_=", { beforeExpr: beforeExpr, isAssign: isAssign }), - incDec: new TokenType("++/--", { prefix: prefix, postfix: postfix, startsExpr: startsExpr }), - prefix: new TokenType("prefix", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - logicalOR: new BinopTokenType("||", 1), - logicalAND: new BinopTokenType("&&", 2), - bitwiseOR: new BinopTokenType("|", 3), - bitwiseXOR: new BinopTokenType("^", 4), - bitwiseAND: new BinopTokenType("&", 5), - equality: new BinopTokenType("==/!=", 6), - relational: new BinopTokenType("", 7), - bitShift: new BinopTokenType("<>", 8), - plusMin: new TokenType("+/-", { beforeExpr: beforeExpr, binop: 9, prefix: prefix, startsExpr: startsExpr }), - modulo: new BinopTokenType("%", 10), - star: new BinopTokenType("*", 10), - slash: new BinopTokenType("/", 10), - exponent: new TokenType("**", { beforeExpr: beforeExpr, binop: 11, rightAssociative: true }) -}; - -var keywords = { - "break": new KeywordTokenType("break"), - "case": new KeywordTokenType("case", { beforeExpr: beforeExpr }), - "catch": new KeywordTokenType("catch"), - "continue": new KeywordTokenType("continue"), - "debugger": new KeywordTokenType("debugger"), - "default": new KeywordTokenType("default", { beforeExpr: beforeExpr }), - "do": new KeywordTokenType("do", { isLoop: isLoop, beforeExpr: beforeExpr }), - "else": new KeywordTokenType("else", { beforeExpr: beforeExpr }), - "finally": new KeywordTokenType("finally"), - "for": new KeywordTokenType("for", { isLoop: isLoop }), - "function": new KeywordTokenType("function", { startsExpr: startsExpr }), - "if": new KeywordTokenType("if"), - "return": new KeywordTokenType("return", { beforeExpr: beforeExpr }), - "switch": new KeywordTokenType("switch"), - "throw": new KeywordTokenType("throw", { beforeExpr: beforeExpr }), - "try": new KeywordTokenType("try"), - "var": new KeywordTokenType("var"), - "let": new KeywordTokenType("let"), - "const": new KeywordTokenType("const"), - "while": new KeywordTokenType("while", { isLoop: isLoop }), - "with": new KeywordTokenType("with"), - "new": new KeywordTokenType("new", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "this": new KeywordTokenType("this", { startsExpr: startsExpr }), - "super": new KeywordTokenType("super", { startsExpr: startsExpr }), - "class": new KeywordTokenType("class"), - "extends": new KeywordTokenType("extends", { beforeExpr: beforeExpr }), - "export": new KeywordTokenType("export"), - "import": new KeywordTokenType("import"), - "yield": new KeywordTokenType("yield", { beforeExpr: beforeExpr, startsExpr: startsExpr }), - "null": new KeywordTokenType("null", { startsExpr: startsExpr }), - "true": new KeywordTokenType("true", { startsExpr: startsExpr }), - "false": new KeywordTokenType("false", { startsExpr: startsExpr }), - "in": new KeywordTokenType("in", { beforeExpr: beforeExpr, binop: 7 }), - "instanceof": new KeywordTokenType("instanceof", { beforeExpr: beforeExpr, binop: 7 }), - "typeof": new KeywordTokenType("typeof", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "void": new KeywordTokenType("void", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }), - "delete": new KeywordTokenType("delete", { beforeExpr: beforeExpr, prefix: prefix, startsExpr: startsExpr }) -}; - -// Map keyword names to token types. -Object.keys(keywords).forEach(function (name) { - types["_" + name] = keywords[name]; -}); - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -var lineBreak = /\r\n?|\n|\u2028|\u2029/; -var lineBreakG = new RegExp(lineBreak.source, "g"); - -function isNewLine(code) { - return code === 10 || code === 13 || code === 0x2028 || code === 0x2029; -} - -var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - -// The algorithm used to determine whether a regexp can appear at a -// given point in the program is loosely based on sweet.js' approach. -// See https://github.com/mozilla/sweet.js/wiki/design - -var TokContext = function TokContext(token, isExpr, preserveSpace, override) { - classCallCheck(this, TokContext); - - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; -}; - -var types$1 = { - braceStatement: new TokContext("{", false), - braceExpression: new TokContext("{", true), - templateQuasi: new TokContext("${", true), - parenStatement: new TokContext("(", false), - parenExpression: new TokContext("(", true), - template: new TokContext("`", true, true, function (p) { - return p.readTmplToken(); - }), - functionExpression: new TokContext("function", true) -}; - -// Token-specific context update code - -types.parenR.updateContext = types.braceR.updateContext = function () { - if (this.state.context.length === 1) { - this.state.exprAllowed = true; - return; - } - - var out = this.state.context.pop(); - if (out === types$1.braceStatement && this.curContext() === types$1.functionExpression) { - this.state.context.pop(); - this.state.exprAllowed = false; - } else if (out === types$1.templateQuasi) { - this.state.exprAllowed = true; - } else { - this.state.exprAllowed = !out.isExpr; - } -}; - -types.name.updateContext = function (prevType) { - this.state.exprAllowed = false; - - if (prevType === types._let || prevType === types._const || prevType === types._var) { - if (lineBreak.test(this.input.slice(this.state.end))) { - this.state.exprAllowed = true; - } - } -}; - -types.braceL.updateContext = function (prevType) { - this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); - this.state.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function () { - this.state.context.push(types$1.templateQuasi); - this.state.exprAllowed = true; -}; - -types.parenL.updateContext = function (prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); - this.state.exprAllowed = true; -}; - -types.incDec.updateContext = function () { - // tokExprAllowed stays unchanged -}; - -types._function.updateContext = function () { - if (this.curContext() !== types$1.braceStatement) { - this.state.context.push(types$1.functionExpression); - } - - this.state.exprAllowed = false; -}; - -types.backQuote.updateContext = function () { - if (this.curContext() === types$1.template) { - this.state.context.pop(); - } else { - this.state.context.push(types$1.template); - } - this.state.exprAllowed = false; -}; - -// These are used when `options.locations` is on, for the -// `startLoc` and `endLoc` properties. - -var Position = function Position(line, col) { - classCallCheck(this, Position); - - this.line = line; - this.column = col; -}; - -var SourceLocation = function SourceLocation(start, end) { - classCallCheck(this, SourceLocation); - - this.start = start; - this.end = end; -}; - -// The `getLineInfo` function is mostly useful when the -// `locations` option is off (for performance reasons) and you -// want to find the line/column position for a given character -// offset. `input` should be the code string that the offset refers -// into. - -function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur); - } - } -} - -var State = function () { - function State() { - classCallCheck(this, State); - } - - State.prototype.init = function init(options, input) { - this.strict = options.strictMode === false ? false : options.sourceType === "module"; - - this.input = input; - - this.potentialArrowAt = -1; - - this.inMethod = this.inFunction = this.inGenerator = this.inAsync = this.inPropertyName = this.inType = this.noAnonFunctionType = false; - - this.labels = []; - - this.decorators = []; - - this.tokens = []; - - this.comments = []; - - this.trailingComments = []; - this.leadingComments = []; - this.commentStack = []; - - this.pos = this.lineStart = 0; - this.curLine = options.startLine; - - this.type = types.eof; - this.value = null; - this.start = this.end = this.pos; - this.startLoc = this.endLoc = this.curPosition(); - - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; - - this.context = [types$1.braceStatement]; - this.exprAllowed = true; - - this.containsEsc = this.containsOctal = false; - this.octalPosition = null; - - this.exportedIdentifiers = []; - - return this; - }; - - // TODO - - - // TODO - - - // Used to signify the start of a potential arrow function - - - // Flags to track whether we are in a function, a generator. - - - // Labels in scope. - - - // Leading decorators. - - - // Token store. - - - // Comment store. - - - // Comment attachment store - - - // The current position of the tokenizer in the input. - - - // Properties of the current token: - // Its type - - - // For tokens that include more information than their type, the value - - - // Its start and end offset - - - // And, if locations are used, the {line, column} object - // corresponding to those offsets - - - // Position information for the previous token - - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - - - // TODO - - - // Names of exports store. `default` is stored as a name for both - // `export default foo;` and `export { foo as default };`. - - - State.prototype.curPosition = function curPosition() { - return new Position(this.curLine, this.pos - this.lineStart); - }; - - State.prototype.clone = function clone(skipArrays) { - var state = new State(); - for (var key in this) { - var val = this[key]; - - if ((!skipArrays || key === "context") && Array.isArray(val)) { - val = val.slice(); - } - - state[key] = val; - } - return state; - }; - - return State; -}(); - -// Object type used to represent tokens. Note that normally, tokens -// simply exist as properties on the parser object. This is only -// used for the onToken callback and the external tokenizer. - -var Token = function Token(state) { - classCallCheck(this, Token); - - this.type = state.type; - this.value = state.value; - this.start = state.start; - this.end = state.end; - this.loc = new SourceLocation(state.startLoc, state.endLoc); -}; - -// ## Tokenizer - -function codePointToString(code) { - // UTF-16 Decoding - if (code <= 0xFFFF) { - return String.fromCharCode(code); - } else { - return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00); - } -} - -var Tokenizer = function () { - function Tokenizer(options, input) { - classCallCheck(this, Tokenizer); - - this.state = new State(); - this.state.init(options, input); - } - - // Move to the next token - - Tokenizer.prototype.next = function next() { - if (!this.isLookahead) { - this.state.tokens.push(new Token(this.state)); - } - - this.state.lastTokEnd = this.state.end; - this.state.lastTokStart = this.state.start; - this.state.lastTokEndLoc = this.state.endLoc; - this.state.lastTokStartLoc = this.state.startLoc; - this.nextToken(); - }; - - // TODO - - Tokenizer.prototype.eat = function eat(type) { - if (this.match(type)) { - this.next(); - return true; - } else { - return false; - } - }; - - // TODO - - Tokenizer.prototype.match = function match(type) { - return this.state.type === type; - }; - - // TODO - - Tokenizer.prototype.isKeyword = function isKeyword$$1(word) { - return isKeyword(word); - }; - - // TODO - - Tokenizer.prototype.lookahead = function lookahead() { - var old = this.state; - this.state = old.clone(true); - - this.isLookahead = true; - this.next(); - this.isLookahead = false; - - var curr = this.state.clone(true); - this.state = old; - return curr; - }; - - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - Tokenizer.prototype.setStrict = function setStrict(strict) { - this.state.strict = strict; - if (!this.match(types.num) && !this.match(types.string)) return; - this.state.pos = this.state.start; - while (this.state.pos < this.state.lineStart) { - this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; - --this.state.curLine; - } - this.nextToken(); - }; - - Tokenizer.prototype.curContext = function curContext() { - return this.state.context[this.state.context.length - 1]; - }; - - // Read a single token, updating the parser object's token-related - // properties. - - Tokenizer.prototype.nextToken = function nextToken() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) this.skipSpace(); - - this.state.containsOctal = false; - this.state.octalPosition = null; - this.state.start = this.state.pos; - this.state.startLoc = this.state.curPosition(); - if (this.state.pos >= this.input.length) return this.finishToken(types.eof); - - if (curContext.override) { - return curContext.override(this); - } else { - return this.readToken(this.fullCharCodeAtPos()); - } - }; - - Tokenizer.prototype.readToken = function readToken(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code) || code === 92 /* '\' */) { - return this.readWord(); - } else { - return this.getTokenFromCode(code); - } - }; - - Tokenizer.prototype.fullCharCodeAtPos = function fullCharCodeAtPos() { - var code = this.input.charCodeAt(this.state.pos); - if (code <= 0xd7ff || code >= 0xe000) return code; - - var next = this.input.charCodeAt(this.state.pos + 1); - return (code << 10) + next - 0x35fdc00; - }; - - Tokenizer.prototype.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "CommentBlock" : "CommentLine", - value: text, - start: start, - end: end, - loc: new SourceLocation(startLoc, endLoc) - }; - - if (!this.isLookahead) { - this.state.tokens.push(comment); - this.state.comments.push(comment); - this.addComment(comment); - } - }; - - Tokenizer.prototype.skipBlockComment = function skipBlockComment() { - var startLoc = this.state.curPosition(); - var start = this.state.pos; - var end = this.input.indexOf("*/", this.state.pos += 2); - if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); - - this.state.pos = end + 2; - lineBreakG.lastIndex = start; - var match = void 0; - while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { - ++this.state.curLine; - this.state.lineStart = match.index + match[0].length; - } - - this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); - }; - - Tokenizer.prototype.skipLineComment = function skipLineComment(startSkip) { - var start = this.state.pos; - var startLoc = this.state.curPosition(); - var ch = this.input.charCodeAt(this.state.pos += startSkip); - while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { - ++this.state.pos; - ch = this.input.charCodeAt(this.state.pos); - } - - this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); - }; - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - Tokenizer.prototype.skipSpace = function skipSpace() { - loop: while (this.state.pos < this.input.length) { - var ch = this.input.charCodeAt(this.state.pos); - switch (ch) { - case 32:case 160: - // ' ' - ++this.state.pos; - break; - - case 13: - if (this.input.charCodeAt(this.state.pos + 1) === 10) { - ++this.state.pos; - } - - case 10:case 8232:case 8233: - ++this.state.pos; - ++this.state.curLine; - this.state.lineStart = this.state.pos; - break; - - case 47: - // '/' - switch (this.input.charCodeAt(this.state.pos + 1)) { - case 42: - // '*' - this.skipBlockComment(); - break; - - case 47: - this.skipLineComment(2); - break; - - default: - break loop; - } - break; - - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.state.pos; - } else { - break loop; - } - } - } - }; - - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. - - Tokenizer.prototype.finishToken = function finishToken(type, val) { - this.state.end = this.state.pos; - this.state.endLoc = this.state.curPosition(); - var prevType = this.state.type; - this.state.type = type; - this.state.value = val; - - this.updateContext(prevType); - }; - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - - - Tokenizer.prototype.readToken_dot = function readToken_dot() { - var next = this.input.charCodeAt(this.state.pos + 1); - if (next >= 48 && next <= 57) { - return this.readNumber(true); - } - - var next2 = this.input.charCodeAt(this.state.pos + 2); - if (next === 46 && next2 === 46) { - // 46 = dot '.' - this.state.pos += 3; - return this.finishToken(types.ellipsis); - } else { - ++this.state.pos; - return this.finishToken(types.dot); - } - }; - - Tokenizer.prototype.readToken_slash = function readToken_slash() { - // '/' - if (this.state.exprAllowed) { - ++this.state.pos; - return this.readRegexp(); - } - - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.slash, 1); - } - }; - - Tokenizer.prototype.readToken_mult_modulo = function readToken_mult_modulo(code) { - // '%*' - var type = code === 42 ? types.star : types.modulo; - var width = 1; - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === 42) { - // '*' - width++; - next = this.input.charCodeAt(this.state.pos + 2); - type = types.exponent; - } - - if (next === 61) { - width++; - type = types.assign; - } - - return this.finishOp(type, width); - }; - - Tokenizer.prototype.readToken_pipe_amp = function readToken_pipe_amp(code) { - // '|&' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === code) return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); - if (next === 61) return this.finishOp(types.assign, 2); - if (code === 124 && next === 125 && this.hasPlugin("flow")) return this.finishOp(types.braceBarR, 2); - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); - }; - - Tokenizer.prototype.readToken_caret = function readToken_caret() { - // '^' - var next = this.input.charCodeAt(this.state.pos + 1); - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.bitwiseXOR, 1); - } - }; - - Tokenizer.prototype.readToken_plus_min = function readToken_plus_min(code) { - // '+-' - var next = this.input.charCodeAt(this.state.pos + 1); - - if (next === code) { - if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken(); - } - return this.finishOp(types.incDec, 2); - } - - if (next === 61) { - return this.finishOp(types.assign, 2); - } else { - return this.finishOp(types.plusMin, 1); - } - }; - - Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) { - // '<>' - var next = this.input.charCodeAt(this.state.pos + 1); - var size = 1; - - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(types.assign, size + 1); - return this.finishOp(types.bitShift, size); - } - - if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { - if (this.inModule) this.unexpected(); - // ` regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - - this.debug(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) - - this.debug(this.pattern, set) - - this.set = set -} - -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - - if (options.nonegate) return - - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} - -Minimatch.prototype.braceExpand = braceExpand - -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } - - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - return expand(pattern) -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue - } - - if (!stateChar) { - re += '\\(' - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } - - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } - - clearStateChar() - re += '|' - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += '\\' + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } - - re += c - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } - - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter - - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} - -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} - -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} - -},{"brace-expansion":119,"path":469}],467:[function(require,module,exports){ -/** - * Helpers. - */ - -var s = 1000 -var m = s * 60 -var h = m * 60 -var d = h * 24 -var y = d * 365.25 - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function (val, options) { - options = options || {} - var type = typeof val - if (type === 'string' && val.length > 0) { - return parse(val) - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? - fmtLong(val) : - fmtShort(val) - } - throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) -} - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str) - if (str.length > 10000) { - return - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) - if (!match) { - return - } - var n = parseFloat(match[1]) - var type = (match[2] || 'ms').toLowerCase() - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y - case 'days': - case 'day': - case 'd': - return n * d - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n - default: - return undefined - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd' - } - if (ms >= h) { - return Math.round(ms / h) + 'h' - } - if (ms >= m) { - return Math.round(ms / m) + 'm' - } - if (ms >= s) { - return Math.round(ms / s) + 's' - } - return ms + 'ms' -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms' -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name - } - return Math.ceil(ms / n) + ' ' + name + 's' -} - -},{}],468:[function(require,module,exports){ -'use strict'; -module.exports = Number.isNaN || function (x) { - return x !== x; -}; - -},{}],469:[function(require,module,exports){ -(function (process){ -// Copyright Joyent, Inc. and other Node 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. - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; - - -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; - -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// String.prototype.substr - negative index don't work in IE8 -var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } -; - -}).call(this,require('_process')) -},{"_process":471}],470:[function(require,module,exports){ -(function (process){ -'use strict'; - -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; - -}).call(this,require('_process')) -},{"_process":471}],471:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],472:[function(require,module,exports){ -'use strict'; -var isFinite = require('is-finite'); - -module.exports = function (str, n) { - if (typeof str !== 'string') { - throw new TypeError('Expected `input` to be a string'); - } - - if (n < 0 || !isFinite(n)) { - throw new TypeError('Expected `count` to be a positive finite number'); - } - - var ret = ''; - - do { - if (n & 1) { - ret += str; - } - - str += str; - } while ((n >>= 1)); - - return ret; -}; - -},{"is-finite":246}],473:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var isExtendedLengthPath = /^\\\\\?\\/.test(str); - var hasNonAscii = /[^\x00-\x80]+/.test(str); - - if (isExtendedLengthPath || hasNonAscii) { - return str; - } - - return str.replace(/\\/g, '/'); -}; - -},{}],474:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); -var has = Object.prototype.hasOwnProperty; - -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet() { - this._array = []; - this._set = Object.create(null); -} - -/** - * Static method for creating ArraySet instances from an existing array. - */ -ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; -}; - -/** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ -ArraySet.prototype.size = function ArraySet_size() { - return Object.getOwnPropertyNames(this._set).length; -}; - -/** - * Add the given string to this set. - * - * @param String aStr - */ -ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = util.toSetString(aStr); - var isDuplicate = has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - this._set[sStr] = idx; - } -}; - -/** - * Is the given string a member of this set? - * - * @param String aStr - */ -ArraySet.prototype.has = function ArraySet_has(aStr) { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); -}; - -/** - * What is the index of the given string in the array? - * - * @param String aStr - */ -ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - throw new Error('"' + aStr + '" is not in the set.'); -}; - -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; - -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -exports.ArraySet = ArraySet; - -},{"./util":483}],475:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -var base64 = require('./base64'); - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; - -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; - -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; - -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} - -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; - -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; - -},{"./base64":476}],476:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -exports.encode = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -exports.decode = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; -}; - -},{}],477:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; - -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } -} - -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; -}; - -},{}],478:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2014 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); - -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} - -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} - -/** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ -MappingList.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; - -/** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ -MappingList.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -exports.MappingList = MappingList; - -},{"./util":483}],479:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - -/** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} - -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); -} - -/** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } -} - -/** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -exports.quickSort = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; - -},{}],480:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var util = require('./util'); -var binarySearch = require('./binary-search'); -var ArraySet = require('./array-set').ArraySet; -var base64VLQ = require('./base64-vlq'); -var quickSort = require('./quick-sort').quickSort; - -function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap) - : new BasicSourceMapConsumer(sourceMap); -} - -SourceMapConsumer.fromSourceMap = function(aSourceMap) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap); -} - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. - -SourceMapConsumer.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } -}); - -SourceMapConsumer.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } -}); - -SourceMapConsumer.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer.GENERATED_ORDER = 1; -SourceMapConsumer.ORIGINAL_ORDER = 2; - -SourceMapConsumer.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - if (source != null && sourceRoot != null) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: Optional. the column number in the original source. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -SourceMapConsumer.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - if (this.sourceRoot != null) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - if (!this._sources.has(needle.source)) { - return []; - } - needle.source = this._sources.indexOf(needle.source); - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -exports.SourceMapConsumer = SourceMapConsumer; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; -} - -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; - }, this); - } -}); - -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64VLQ.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - if (this.sourceRoot != null) { - source = util.join(this.sourceRoot, source); - } - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot != null) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - if (this.sourceRoot != null) { - source = util.relative(this.sourceRoot, source); - } - if (!this._sources.has(source)) { - return { - line: null, - column: null, - lastColumn: null - }; - } - source = this._sources.indexOf(source); - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -exports.BasicSourceMapConsumer = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The only parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer(util.getArg(s, 'map')) - } - }); -} - -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } -}); - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - if (section.consumer.sourceRoot !== null) { - source = util.join(section.consumer.sourceRoot, source); - } - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - -},{"./array-set":474,"./base64-vlq":475,"./binary-search":477,"./quick-sort":479,"./util":483}],481:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var base64VLQ = require('./base64-vlq'); -var util = require('./util'); -var ArraySet = require('./array-set').ArraySet; -var MappingList = require('./mapping-list').MappingList; - -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator(aArgs) { - if (!aArgs) { - aArgs = {}; - } - this._file = util.getArg(aArgs, 'file', null); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._skipValidation = util.getArg(aArgs, 'skipValidation', false); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} - -SourceMapGenerator.prototype._version = 3; - -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source) - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = '' - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64VLQ.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64VLQ.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - -SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - -/** - * Externalize the source map. - */ -SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - -exports.SourceMapGenerator = SourceMapGenerator; - -},{"./array-set":474,"./base64-vlq":475,"./mapping-list":478,"./util":483}],482:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; -var util = require('./util'); - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; - -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); -} - -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are removed from this array, by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var shiftNextLine = function() { - var lineContents = remainingLines.shift(); - // The last line of a file might not have a newline. - var newLine = remainingLines.shift() || ""; - return lineContents + newLine; - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[0]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[0] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[0]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[0] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLines.length > 0) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; - -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; - -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; -}; - -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; - -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; -}; - -exports.SourceNode = SourceNode; - -},{"./source-map-generator":481,"./util":483}],483:[function(require,module,exports){ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; - -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; - -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; - -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; - -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; - -/** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; -} -exports.join = join; - -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); -}; - -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; - -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); - -function identity (s) { - return s; -} - -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; - -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; - -function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; -} - -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByOriginalPositions = compareByOriginalPositions; - -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = mappingA.source - mappingB.source; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return mappingA.name - mappingB.name; -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; -} - -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - -},{}],484:[function(require,module,exports){ -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; -exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; -exports.SourceNode = require('./lib/source-node').SourceNode; - -},{"./lib/source-map-consumer":480,"./lib/source-map-generator":481,"./lib/source-node":482}],485:[function(require,module,exports){ -'use strict'; -var ansiRegex = require('ansi-regex')(); - -module.exports = function (str) { - return typeof str === 'string' ? str.replace(ansiRegex, '') : str; -}; - -},{"ansi-regex":1}],486:[function(require,module,exports){ -(function (process){ -'use strict'; -var argv = process.argv; - -var terminator = argv.indexOf('--'); -var hasFlag = function (flag) { - flag = '--' + flag; - var pos = argv.indexOf(flag); - return pos !== -1 && (terminator !== -1 ? pos < terminator : true); -}; - -module.exports = (function () { - if ('FORCE_COLOR' in process.env) { - return true; - } - - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return false; - } - - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return true; - } - - if (process.stdout && !process.stdout.isTTY) { - return false; - } - - if (process.platform === 'win32') { - return true; - } - - if ('COLORTERM' in process.env) { - return true; - } - - if (process.env.TERM === 'dumb') { - return false; - } - - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } - - return false; -})(); - -}).call(this,require('_process')) -},{"_process":471}],487:[function(require,module,exports){ -'use strict'; -module.exports = function toFastProperties(obj) { - function f() {} - f.prototype = obj; - new f(); - return; - eval(obj); -}; - -},{}],488:[function(require,module,exports){ -'use strict'; -module.exports = function (str) { - var tail = str.length; - - while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { - tail--; - } - - return str.slice(0, tail); -}; - -},{}],489:[function(require,module,exports){ -exports.isatty = function () { return false; }; - -function ReadStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.ReadStream = ReadStream; - -function WriteStream() { - throw new Error('tty.ReadStream is not implemented'); -} -exports.WriteStream = WriteStream; - -},{}],490:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],491:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],492:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node 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. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":491,"_process":471,"inherits":490}],493:[function(require,module,exports){ -/*import { transform as babelTransform } from 'babel-core'; -import babelTransformDynamicImport from 'babel-plugin-syntax-dynamic-import'; -import babelTransformES2015ModulesSystemJS from 'babel-plugin-transform-es2015-modules-systemjs';*/ - -// sadly, due to how rollup works, we can't use es6 imports here -var babelTransform = require('babel-core').transform; -var babelTransformDynamicImport = require('babel-plugin-syntax-dynamic-import'); -var babelTransformES2015ModulesSystemJS = require('babel-plugin-transform-es2015-modules-systemjs'); - -self.onmessage = function (evt) { - // transform source with Babel - var output = babelTransform(evt.data.source, { - compact: false, - filename: evt.data.key + '!transpiled', - sourceFileName: evt.data.key, - moduleIds: false, - sourceMaps: 'inline', - babelrc: false, - plugins: [babelTransformDynamicImport, babelTransformES2015ModulesSystemJS], - }); - - self.postMessage({key: evt.data.key, code: output.code, source: evt.data.source}); -}; - -},{"babel-core":4,"babel-plugin-syntax-dynamic-import":54,"babel-plugin-transform-es2015-modules-systemjs":55}]},{},[493]); diff --git a/vendor/browser-es-module-loader/dist/browser-es-module-loader.js b/vendor/browser-es-module-loader/dist/browser-es-module-loader.js deleted file mode 100644 index 3aa2e5168..000000000 --- a/vendor/browser-es-module-loader/dist/browser-es-module-loader.js +++ /dev/null @@ -1,1420 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.BrowserESModuleLoader = factory()); -}(this, (function () { 'use strict'; - -/* - * Environment - */ -var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; -var isNode = typeof process !== 'undefined' && process.versions && process.versions.node; -var isWindows = typeof process !== 'undefined' && typeof process.platform === 'string' && process.platform.match(/^win/); - -var envGlobal = typeof self !== 'undefined' ? self : global; -/* - * Simple Symbol() shim - */ -var hasSymbol = typeof Symbol !== 'undefined'; -function createSymbol (name) { - return hasSymbol ? Symbol() : '@@' + name; -} - - - - - -/* - * Environment baseURI - */ -var baseURI; - -// environent baseURI detection -if (typeof document != 'undefined' && document.getElementsByTagName) { - baseURI = document.baseURI; - - if (!baseURI) { - var bases = document.getElementsByTagName('base'); - baseURI = bases[0] && bases[0].href || window.location.href; - } -} -else if (typeof location != 'undefined') { - baseURI = location.href; -} - -// sanitize out the hash and querystring -if (baseURI) { - baseURI = baseURI.split('#')[0].split('?')[0]; - var slashIndex = baseURI.lastIndexOf('/'); - if (slashIndex !== -1) - baseURI = baseURI.substr(0, slashIndex + 1); -} -else if (typeof process !== 'undefined' && process.cwd) { - baseURI = 'file://' + (isWindows ? '/' : '') + process.cwd(); - if (isWindows) - baseURI = baseURI.replace(/\\/g, '/'); -} -else { - throw new TypeError('No environment baseURI'); -} - -// ensure baseURI has trailing "/" -if (baseURI[baseURI.length - 1] !== '/') - baseURI += '/'; - -/* - * LoaderError with chaining for loader stacks - */ -var errArgs = new Error(0, '_').fileName == '_'; -function LoaderError__Check_error_message_for_loader_stack (childErr, newMessage) { - // Convert file:/// URLs to paths in Node - if (!isBrowser) - newMessage = newMessage.replace(isWindows ? /file:\/\/\//g : /file:\/\//g, ''); - - var message = (childErr.message || childErr) + '\n ' + newMessage; - - var err; - if (errArgs && childErr.fileName) - err = new Error(message, childErr.fileName, childErr.lineNumber); - else - err = new Error(message); - - - var stack = childErr.originalErr ? childErr.originalErr.stack : childErr.stack; - - if (isNode) - // node doesn't show the message otherwise - err.stack = message + '\n ' + stack; - else - err.stack = stack; - - err.originalErr = childErr.originalErr || childErr; - - return err; -} - -var resolvedPromise = Promise.resolve(); - -/* - * Simple Array values shim - */ -function arrayValues (arr) { - if (arr.values) - return arr.values(); - - if (typeof Symbol === 'undefined' || !Symbol.iterator) - throw new Error('Symbol.iterator not supported in this browser'); - - var iterable = {}; - iterable[Symbol.iterator] = function () { - var keys = Object.keys(arr); - var keyIndex = 0; - return { - next: function () { - if (keyIndex < keys.length) - return { - value: arr[keys[keyIndex++]], - done: false - }; - else - return { - value: undefined, - done: true - }; - } - }; - }; - return iterable; -} - -/* - * 3. Reflect.Loader - * - * We skip the entire native internal pipeline, just providing the bare API - */ -// 3.1.1 -function Loader () { - this.registry = new Registry(); -} -// 3.3.1 -Loader.prototype.constructor = Loader; - -function ensureInstantiated (module) { - if (!(module instanceof ModuleNamespace)) - throw new TypeError('Module instantiation did not return a valid namespace object.'); - return module; -} - -// 3.3.2 -Loader.prototype.import = function (key, parent) { - if (typeof key !== 'string') - throw new TypeError('Loader import method must be passed a module key string'); - // custom resolveInstantiate combined hook for better perf - var loader = this; - return resolvedPromise - .then(function () { - return loader[RESOLVE_INSTANTIATE](key, parent); - }) - .then(ensureInstantiated) - //.then(Module.evaluate) - .catch(function (err) { - throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); - }); -}; -// 3.3.3 -var RESOLVE = Loader.resolve = createSymbol('resolve'); - -/* - * Combined resolve / instantiate hook - * - * Not in current reduced spec, but necessary to separate RESOLVE from RESOLVE + INSTANTIATE as described - * in the spec notes of this repo to ensure that loader.resolve doesn't instantiate when not wanted. - * - * We implement RESOLVE_INSTANTIATE as a single hook instead of a separate INSTANTIATE in order to avoid - * the need for double registry lookups as a performance optimization. - */ -var RESOLVE_INSTANTIATE = Loader.resolveInstantiate = createSymbol('resolveInstantiate'); - -// default resolveInstantiate is just to call resolve and then get from the registry -// this provides compatibility for the resolveInstantiate optimization -Loader.prototype[RESOLVE_INSTANTIATE] = function (key, parent) { - var loader = this; - return loader.resolve(key, parent) - .then(function (resolved) { - return loader.registry.get(resolved); - }); -}; - -function ensureResolution (resolvedKey) { - if (resolvedKey === undefined) - throw new RangeError('No resolution found.'); - return resolvedKey; -} - -Loader.prototype.resolve = function (key, parent) { - var loader = this; - return resolvedPromise - .then(function() { - return loader[RESOLVE](key, parent); - }) - .then(ensureResolution) - .catch(function (err) { - throw LoaderError__Check_error_message_for_loader_stack(err, 'Resolving ' + key + (parent ? ' to ' + parent : '')); - }); -}; - -// 3.3.4 (import without evaluate) -// this is not documented because the use of deferred evaluation as in Module.evaluate is not -// documented, as it is not considered a stable feature to be encouraged -// Loader.prototype.load may well be deprecated if this stays disabled -/* Loader.prototype.load = function (key, parent) { - return Promise.resolve(this[RESOLVE_INSTANTIATE](key, parent || this.key)) - .catch(function (err) { - throw addToError(err, 'Loading ' + key + (parent ? ' from ' + parent : '')); - }); -}; */ - -/* - * 4. Registry - * - * Instead of structuring through a Map, just use a dictionary object - * We throw for construction attempts so this doesn't affect the public API - * - * Registry has been adjusted to use Namespace objects over ModuleStatus objects - * as part of simplifying loader API implementation - */ -var iteratorSupport = typeof Symbol !== 'undefined' && Symbol.iterator; -var REGISTRY = createSymbol('registry'); -function Registry() { - this[REGISTRY] = {}; -} -// 4.4.1 -if (iteratorSupport) { - // 4.4.2 - Registry.prototype[Symbol.iterator] = function () { - return this.entries()[Symbol.iterator](); - }; - - // 4.4.3 - Registry.prototype.entries = function () { - var registry = this[REGISTRY]; - return arrayValues(Object.keys(registry).map(function (key) { - return [key, registry[key]]; - })); - }; -} - -// 4.4.4 -Registry.prototype.keys = function () { - return arrayValues(Object.keys(this[REGISTRY])); -}; -// 4.4.5 -Registry.prototype.values = function () { - var registry = this[REGISTRY]; - return arrayValues(Object.keys(registry).map(function (key) { - return registry[key]; - })); -}; -// 4.4.6 -Registry.prototype.get = function (key) { - return this[REGISTRY][key]; -}; -// 4.4.7 -Registry.prototype.set = function (key, namespace) { - if (!(namespace instanceof ModuleNamespace)) - throw new Error('Registry must be set with an instance of Module Namespace'); - this[REGISTRY][key] = namespace; - return this; -}; -// 4.4.8 -Registry.prototype.has = function (key) { - return Object.hasOwnProperty.call(this[REGISTRY], key); -}; -// 4.4.9 -Registry.prototype.delete = function (key) { - if (Object.hasOwnProperty.call(this[REGISTRY], key)) { - delete this[REGISTRY][key]; - return true; - } - return false; -}; - -/* - * Simple ModuleNamespace Exotic object based on a baseObject - * We export this for allowing a fast-path for module namespace creation over Module descriptors - */ -// var EVALUATE = createSymbol('evaluate'); -var BASE_OBJECT = createSymbol('baseObject'); - -// 8.3.1 Reflect.Module -/* - * Best-effort simplified non-spec implementation based on - * a baseObject referenced via getters. - * - * Allows: - * - * loader.registry.set('x', new Module({ default: 'x' })); - * - * Optional evaluation function provides experimental Module.evaluate - * support for non-executed modules in registry. - */ -function ModuleNamespace (baseObject/*, evaluate*/) { - Object.defineProperty(this, BASE_OBJECT, { - value: baseObject - }); - - // evaluate defers namespace population - /* if (evaluate) { - Object.defineProperty(this, EVALUATE, { - value: evaluate, - configurable: true, - writable: true - }); - } - else { */ - Object.keys(baseObject).forEach(extendNamespace, this); - //} -} -// 8.4.2 -ModuleNamespace.prototype = Object.create(null); - -if (typeof Symbol !== 'undefined' && Symbol.toStringTag) - Object.defineProperty(ModuleNamespace.prototype, Symbol.toStringTag, { - value: 'Module' - }); - -function extendNamespace (key) { - Object.defineProperty(this, key, { - enumerable: true, - get: function () { - return this[BASE_OBJECT][key]; - } - }); -} - -/* function doEvaluate (evaluate, context) { - try { - evaluate.call(context); - } - catch (e) { - return e; - } -} - -// 8.4.1 Module.evaluate... not documented or used because this is potentially unstable -Module.evaluate = function (ns) { - var evaluate = ns[EVALUATE]; - if (evaluate) { - ns[EVALUATE] = undefined; - var err = doEvaluate(evaluate); - if (err) { - // cache the error - ns[EVALUATE] = function () { - throw err; - }; - throw err; - } - Object.keys(ns[BASE_OBJECT]).forEach(extendNamespace, ns); - } - // make chainable - return ns; -}; */ - -/* - * Optimized URL normalization assuming a syntax-valid URL parent - */ -function throwResolveError (relUrl, parentUrl) { - throw new RangeError('Unable to resolve "' + relUrl + '" to ' + parentUrl); -} -function resolveIfNotPlain (relUrl, parentUrl) { - relUrl = relUrl.trim(); - var parentProtocol = parentUrl && parentUrl.substr(0, parentUrl.indexOf(':') + 1); - - var firstChar = relUrl[0]; - var secondChar = relUrl[1]; - - // protocol-relative - if (firstChar === '/' && secondChar === '/') { - if (!parentProtocol) - throwResolveError(relUrl, parentUrl); - return parentProtocol + relUrl; - } - // relative-url - else if (firstChar === '.' && (secondChar === '/' || secondChar === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) || - relUrl.length === 1 && (relUrl += '/')) || - firstChar === '/') { - var parentIsPlain = !parentProtocol || parentUrl[parentProtocol.length] !== '/'; - - // read pathname from parent if a URL - // pathname taken to be part after leading "/" - var pathname; - if (parentIsPlain) { - // resolving to a plain parent -> skip standard URL prefix, and treat entire parent as pathname - if (parentUrl === undefined) - throwResolveError(relUrl, parentUrl); - pathname = parentUrl; - } - else if (parentUrl[parentProtocol.length + 1] === '/') { - // resolving to a :// so we need to read out the auth and host - if (parentProtocol !== 'file:') { - pathname = parentUrl.substr(parentProtocol.length + 2); - pathname = pathname.substr(pathname.indexOf('/') + 1); - } - else { - pathname = parentUrl.substr(8); - } - } - else { - // resolving to :/ so pathname is the /... part - pathname = parentUrl.substr(parentProtocol.length + 1); - } - - if (firstChar === '/') { - if (parentIsPlain) - throwResolveError(relUrl, parentUrl); - else - return parentUrl.substr(0, parentUrl.length - pathname.length - 1) + relUrl; - } - - // join together and split for removal of .. and . segments - // looping the string instead of anything fancy for perf reasons - // '../../../../../z' resolved to 'x/y' is just 'z' regardless of parentIsPlain - var segmented = pathname.substr(0, pathname.lastIndexOf('/') + 1) + relUrl; - - var output = []; - var segmentIndex = -1; - - for (var i = 0; i < segmented.length; i++) { - // busy reading a segment - only terminate on '/' - if (segmentIndex !== -1) { - if (segmented[i] === '/') { - output.push(segmented.substring(segmentIndex, i + 1)); - segmentIndex = -1; - } - continue; - } - - // new segment - check if it is relative - if (segmented[i] === '.') { - // ../ segment - if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) { - output.pop(); - i += 2; - } - // ./ segment - else if (segmented[i + 1] === '/' || i + 1 === segmented.length) { - i += 1; - } - else { - // the start of a new segment as below - segmentIndex = i; - continue; - } - - // this is the plain URI backtracking error (../, package:x -> error) - if (parentIsPlain && output.length === 0) - throwResolveError(relUrl, parentUrl); - - continue; - } - - // it is the start of a new segment - segmentIndex = i; - } - // finish reading out the last segment - if (segmentIndex !== -1) - output.push(segmented.substr(segmentIndex)); - - return parentUrl.substr(0, parentUrl.length - pathname.length) + output.join(''); - } - - // sanitizes and verifies (by returning undefined if not a valid URL-like form) - // Windows filepath compatibility is an added convenience here - var protocolIndex = relUrl.indexOf(':'); - if (protocolIndex !== -1) { - if (isNode) { - // C:\x becomes file:///c:/x (we don't support C|\x) - if (relUrl[1] === ':' && relUrl[2] === '\\' && relUrl[0].match(/[a-z]/i)) - return 'file:///' + relUrl.replace(/\\/g, '/'); - } - return relUrl; - } -} - -/* - * Register Loader - * - * Builds directly on top of loader polyfill to provide: - * - loader.register support - * - hookable higher-level resolve - * - instantiate hook returning a ModuleNamespace or undefined for es module loading - * - loader error behaviour as in HTML and loader specs, caching load and eval errors separately - * - build tracing support by providing a .trace=true and .loads object format - */ - -var REGISTER_INTERNAL = createSymbol('register-internal'); - -function RegisterLoader$1 () { - Loader.call(this); - - var registryDelete = this.registry.delete; - this.registry.delete = function (key) { - var deleted = registryDelete.call(this, key); - - // also delete from register registry if linked - if (records.hasOwnProperty(key) && !records[key].linkRecord) { - delete records[key]; - deleted = true; - } - - return deleted; - }; - - var records = {}; - - this[REGISTER_INTERNAL] = { - // last anonymous System.register call - lastRegister: undefined, - // in-flight es module load records - records: records - }; - - // tracing - this.trace = false; -} - -RegisterLoader$1.prototype = Object.create(Loader.prototype); -RegisterLoader$1.prototype.constructor = RegisterLoader$1; - -var INSTANTIATE = RegisterLoader$1.instantiate = createSymbol('instantiate'); - -// default normalize is the WhatWG style normalizer -RegisterLoader$1.prototype[RegisterLoader$1.resolve = Loader.resolve] = function (key, parentKey) { - return resolveIfNotPlain(key, parentKey || baseURI); -}; - -RegisterLoader$1.prototype[INSTANTIATE] = function (key, processAnonRegister) {}; - -// once evaluated, the linkRecord is set to undefined leaving just the other load record properties -// this allows tracking new binding listeners for es modules through importerSetters -// for dynamic modules, the load record is removed entirely. -function createLoadRecord (state, key, registration) { - return state.records[key] = { - key: key, - - // defined System.register cache - registration: registration, - - // module namespace object - module: undefined, - - // es-only - // this sticks around so new module loads can listen to binding changes - // for already-loaded modules by adding themselves to their importerSetters - importerSetters: undefined, - - loadError: undefined, - evalError: undefined, - - // in-flight linking record - linkRecord: { - // promise for instantiated - instantiatePromise: undefined, - dependencies: undefined, - execute: undefined, - executingRequire: false, - - // underlying module object bindings - moduleObj: undefined, - - // es only, also indicates if es or not - setters: undefined, - - // promise for instantiated dependencies (dependencyInstantiations populated) - depsInstantiatePromise: undefined, - // will be the array of dependency load record or a module namespace - dependencyInstantiations: undefined, - - // NB optimization and way of ensuring module objects in setters - // indicates setters which should run pre-execution of that dependency - // setters is then just for completely executed module objects - // alternatively we just pass the partially filled module objects as - // arguments into the execute function - // hoisted: undefined - } - }; -} - -RegisterLoader$1.prototype[Loader.resolveInstantiate] = function (key, parentKey) { - var loader = this; - var state = this[REGISTER_INTERNAL]; - var registry = this.registry[REGISTRY]; - - return resolveInstantiate(loader, key, parentKey, registry, state) - .then(function (instantiated) { - if (instantiated instanceof ModuleNamespace) - return instantiated; - - // resolveInstantiate always returns a load record with a link record and no module value - var link = instantiated.linkRecord; - - // if already beaten to done, return - if (!link) { - if (instantiated.module) - return instantiated.module; - throw instantiated.evalError; - } - - return deepInstantiateDeps(loader, instantiated, link, registry, state) - .then(function () { - return ensureEvaluate(loader, instantiated, link, registry, state, undefined); - }); - }); -}; - -function resolveInstantiate (loader, key, parentKey, registry, state) { - // normalization shortpath for already-normalized key - // could add a plain name filter, but doesn't yet seem necessary for perf - var module = registry[key]; - if (module) - return Promise.resolve(module); - - var load = state.records[key]; - - // already linked but not in main registry is ignored - if (load && !load.module) { - if (load.loadError) - return Promise.reject(load.loadError); - return instantiate(loader, load, load.linkRecord, registry, state); - } - - return loader.resolve(key, parentKey) - .then(function (resolvedKey) { - // main loader registry always takes preference - module = registry[resolvedKey]; - if (module) - return module; - - load = state.records[resolvedKey]; - - // already has a module value but not already in the registry (load.module) - // means it was removed by registry.delete, so we should - // disgard the current load record creating a new one over it - // but keep any existing registration - if (!load || load.module) - load = createLoadRecord(state, resolvedKey, load && load.registration); - - if (load.loadError) - return Promise.reject(load.loadError); - - var link = load.linkRecord; - if (!link) - return load; - - return instantiate(loader, load, link, registry, state); - }); -} - -function createProcessAnonRegister (loader, load, state) { - return function () { - var lastRegister = state.lastRegister; - - if (!lastRegister) - return !!load.registration; - - state.lastRegister = undefined; - load.registration = lastRegister; - - return true; - }; -} - -function instantiate (loader, load, link, registry, state) { - return link.instantiatePromise || (link.instantiatePromise = - // if there is already an existing registration, skip running instantiate - (load.registration ? Promise.resolve() : Promise.resolve().then(function () { - state.lastRegister = undefined; - return loader[INSTANTIATE](load.key, loader[INSTANTIATE].length > 1 && createProcessAnonRegister(loader, load, state)); - })) - .then(function (instantiation) { - // direct module return from instantiate -> we're done - if (instantiation !== undefined) { - if (!(instantiation instanceof ModuleNamespace)) - throw new TypeError('Instantiate did not return a valid Module object.'); - - delete state.records[load.key]; - if (loader.trace) - traceLoad(loader, load, link); - return registry[load.key] = instantiation; - } - - // run the cached loader.register declaration if there is one - var registration = load.registration; - // clear to allow new registrations for future loads (combined with registry delete) - load.registration = undefined; - if (!registration) - throw new TypeError('Module instantiation did not call an anonymous or correctly named System.register.'); - - link.dependencies = registration[0]; - - load.importerSetters = []; - - link.moduleObj = {}; - - // process System.registerDynamic declaration - if (registration[2]) { - link.moduleObj.default = link.moduleObj.__useDefault = {}; - link.executingRequire = registration[1]; - link.execute = registration[2]; - } - - // process System.register declaration - else { - registerDeclarative(loader, load, link, registration[1]); - } - - return load; - }) - .catch(function (err) { - load.linkRecord = undefined; - throw load.loadError = load.loadError || LoaderError__Check_error_message_for_loader_stack(err, 'Instantiating ' + load.key); - })); -} - -// like resolveInstantiate, but returning load records for linking -function resolveInstantiateDep (loader, key, parentKey, registry, state, traceDepMap) { - // normalization shortpaths for already-normalized key - // DISABLED to prioritise consistent resolver calls - // could add a plain name filter, but doesn't yet seem necessary for perf - /* var load = state.records[key]; - var module = registry[key]; - - if (module) { - if (traceDepMap) - traceDepMap[key] = key; - - // registry authority check in case module was deleted or replaced in main registry - if (load && load.module && load.module === module) - return load; - else - return module; - } - - // already linked but not in main registry is ignored - if (load && !load.module) { - if (traceDepMap) - traceDepMap[key] = key; - return instantiate(loader, load, load.linkRecord, registry, state); - } */ - return loader.resolve(key, parentKey) - .then(function (resolvedKey) { - if (traceDepMap) - traceDepMap[key] = resolvedKey; - - // normalization shortpaths for already-normalized key - var load = state.records[resolvedKey]; - var module = registry[resolvedKey]; - - // main loader registry always takes preference - if (module && (!load || load.module && module !== load.module)) - return module; - - if (load && load.loadError) - throw load.loadError; - - // already has a module value but not already in the registry (load.module) - // means it was removed by registry.delete, so we should - // disgard the current load record creating a new one over it - // but keep any existing registration - if (!load || !module && load.module) - load = createLoadRecord(state, resolvedKey, load && load.registration); - - var link = load.linkRecord; - if (!link) - return load; - - return instantiate(loader, load, link, registry, state); - }); -} - -function traceLoad (loader, load, link) { - loader.loads = loader.loads || {}; - loader.loads[load.key] = { - key: load.key, - deps: link.dependencies, - dynamicDeps: [], - depMap: link.depMap || {} - }; -} - -/* - * Convert a CJS module.exports into a valid object for new Module: - * - * new Module(getEsModule(module.exports)) - * - * Sets the default value to the module, while also reading off named exports carefully. - */ -function registerDeclarative (loader, load, link, declare) { - var moduleObj = link.moduleObj; - var importerSetters = load.importerSetters; - - var definedExports = false; - - // closure especially not based on link to allow link record disposal - var declared = declare.call(envGlobal, function (name, value) { - if (typeof name === 'object') { - var changed = false; - for (var p in name) { - value = name[p]; - if (p !== '__useDefault' && (!(p in moduleObj) || moduleObj[p] !== value)) { - changed = true; - moduleObj[p] = value; - } - } - if (changed === false) - return value; - } - else { - if ((definedExports || name in moduleObj) && moduleObj[name] === value) - return value; - moduleObj[name] = value; - } - - for (var i = 0; i < importerSetters.length; i++) - importerSetters[i](moduleObj); - - return value; - }, new ContextualLoader(loader, load.key)); - - link.setters = declared.setters; - link.execute = declared.execute; - if (declared.exports) { - link.moduleObj = moduleObj = declared.exports; - definedExports = true; - } -} - -function instantiateDeps (loader, load, link, registry, state) { - if (link.depsInstantiatePromise) - return link.depsInstantiatePromise; - - var depsInstantiatePromises = Array(link.dependencies.length); - - for (var i = 0; i < link.dependencies.length; i++) - depsInstantiatePromises[i] = resolveInstantiateDep(loader, link.dependencies[i], load.key, registry, state, loader.trace && link.depMap || (link.depMap = {})); - - var depsInstantiatePromise = Promise.all(depsInstantiatePromises) - .then(function (dependencyInstantiations) { - link.dependencyInstantiations = dependencyInstantiations; - - // run setters to set up bindings to instantiated dependencies - if (link.setters) { - for (var i = 0; i < dependencyInstantiations.length; i++) { - var setter = link.setters[i]; - if (setter) { - var instantiation = dependencyInstantiations[i]; - - if (instantiation instanceof ModuleNamespace) { - setter(instantiation); - } - else { - if (instantiation.loadError) - throw instantiation.loadError; - setter(instantiation.module || instantiation.linkRecord.moduleObj); - // this applies to both es and dynamic registrations - if (instantiation.importerSetters) - instantiation.importerSetters.push(setter); - } - } - } - } - - return load; - }); - - if (loader.trace) - depsInstantiatePromise = depsInstantiatePromise.then(function () { - traceLoad(loader, load, link); - return load; - }); - - depsInstantiatePromise = depsInstantiatePromise.catch(function (err) { - // throw up the instantiateDeps stack - link.depsInstantiatePromise = undefined; - throw LoaderError__Check_error_message_for_loader_stack(err, 'Loading ' + load.key); - }); - - depsInstantiatePromise.catch(function () {}); - - return link.depsInstantiatePromise = depsInstantiatePromise; -} - -function deepInstantiateDeps (loader, load, link, registry, state) { - return new Promise(function (resolve, reject) { - var seen = []; - var loadCnt = 0; - function queueLoad (load) { - var link = load.linkRecord; - if (!link) - return; - - if (seen.indexOf(load) !== -1) - return; - seen.push(load); - - loadCnt++; - instantiateDeps(loader, load, link, registry, state) - .then(processLoad, reject); - } - function processLoad (load) { - loadCnt--; - var link = load.linkRecord; - if (link) { - for (var i = 0; i < link.dependencies.length; i++) { - var depLoad = link.dependencyInstantiations[i]; - if (!(depLoad instanceof ModuleNamespace)) - queueLoad(depLoad); - } - } - if (loadCnt === 0) - resolve(); - } - queueLoad(load); - }); -} - -/* - * System.register - */ -RegisterLoader$1.prototype.register = function (key, deps, declare) { - var state = this[REGISTER_INTERNAL]; - - // anonymous modules get stored as lastAnon - if (declare === undefined) { - state.lastRegister = [key, deps, undefined]; - } - - // everything else registers into the register cache - else { - var load = state.records[key] || createLoadRecord(state, key, undefined); - load.registration = [deps, declare, undefined]; - } -}; - -/* - * System.registerDyanmic - */ -RegisterLoader$1.prototype.registerDynamic = function (key, deps, executingRequire, execute) { - var state = this[REGISTER_INTERNAL]; - - // anonymous modules get stored as lastAnon - if (typeof key !== 'string') { - state.lastRegister = [key, deps, executingRequire]; - } - - // everything else registers into the register cache - else { - var load = state.records[key] || createLoadRecord(state, key, undefined); - load.registration = [deps, executingRequire, execute]; - } -}; - -// ContextualLoader class -// backwards-compatible with previous System.register context argument by exposing .id, .key -function ContextualLoader (loader, key) { - this.loader = loader; - this.key = this.id = key; - this.meta = { - url: key - // scriptElement: null - }; -} -/*ContextualLoader.prototype.constructor = function () { - throw new TypeError('Cannot subclass the contextual loader only Reflect.Loader.'); -};*/ -ContextualLoader.prototype.import = function (key) { - if (this.loader.trace) - this.loader.loads[this.key].dynamicDeps.push(key); - return this.loader.import(key, this.key); -}; -/*ContextualLoader.prototype.resolve = function (key) { - return this.loader.resolve(key, this.key); -};*/ - -// this is the execution function bound to the Module namespace record -function ensureEvaluate (loader, load, link, registry, state, seen) { - if (load.module) - return load.module; - - if (load.evalError) - throw load.evalError; - - if (seen && seen.indexOf(load) !== -1) - return load.linkRecord.moduleObj; - - // for ES loads we always run ensureEvaluate on top-level, so empty seen is passed regardless - // for dynamic loads, we pass seen if also dynamic - var err = doEvaluate(loader, load, link, registry, state, link.setters ? [] : seen || []); - if (err) - throw err; - - return load.module; -} - -function makeDynamicRequire (loader, key, dependencies, dependencyInstantiations, registry, state, seen) { - // we can only require from already-known dependencies - return function (name) { - for (var i = 0; i < dependencies.length; i++) { - if (dependencies[i] === name) { - var depLoad = dependencyInstantiations[i]; - var module; - - if (depLoad instanceof ModuleNamespace) - module = depLoad; - else - module = ensureEvaluate(loader, depLoad, depLoad.linkRecord, registry, state, seen); - - return '__useDefault' in module ? module.__useDefault : module; - } - } - throw new Error('Module ' + name + ' not declared as a System.registerDynamic dependency of ' + key); - }; -} - -// ensures the given es load is evaluated -// returns the error if any -function doEvaluate (loader, load, link, registry, state, seen) { - seen.push(load); - - var err; - - // es modules evaluate dependencies first - // non es modules explicitly call moduleEvaluate through require - if (link.setters) { - var depLoad, depLink; - for (var i = 0; i < link.dependencies.length; i++) { - depLoad = link.dependencyInstantiations[i]; - - if (depLoad instanceof ModuleNamespace) - continue; - - // custom Module returned from instantiate - depLink = depLoad.linkRecord; - if (depLink && seen.indexOf(depLoad) === -1) { - if (depLoad.evalError) - err = depLoad.evalError; - else - // dynamic / declarative boundaries clear the "seen" list - // we just let cross format circular throw as would happen in real implementations - err = doEvaluate(loader, depLoad, depLink, registry, state, depLink.setters ? seen : []); - } - - if (err) { - load.linkRecord = undefined; - load.evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key); - return load.evalError; - } - } - } - - // link.execute won't exist for Module returns from instantiate on top-level load - if (link.execute) { - // ES System.register execute - // "this" is null in ES - if (link.setters) { - err = declarativeExecute(link.execute); - } - // System.registerDynamic execute - // "this" is "exports" in CJS - else { - var module = { id: load.key }; - var moduleObj = link.moduleObj; - Object.defineProperty(module, 'exports', { - configurable: true, - set: function (exports) { - moduleObj.default = moduleObj.__useDefault = exports; - }, - get: function () { - return moduleObj.__useDefault; - } - }); - - var require = makeDynamicRequire(loader, load.key, link.dependencies, link.dependencyInstantiations, registry, state, seen); - - // evaluate deps first - if (!link.executingRequire) - for (var i = 0; i < link.dependencies.length; i++) - require(link.dependencies[i]); - - err = dynamicExecute(link.execute, require, moduleObj.default, module); - - // pick up defineProperty calls to module.exports when we can - if (module.exports !== moduleObj.__useDefault) - moduleObj.default = moduleObj.__useDefault = module.exports; - - var moduleDefault = moduleObj.default; - - // __esModule flag extension support via lifting - if (moduleDefault && moduleDefault.__esModule) { - for (var p in moduleDefault) { - if (Object.hasOwnProperty.call(moduleDefault, p)) - moduleObj[p] = moduleDefault[p]; - } - } - } - } - - // dispose link record - load.linkRecord = undefined; - - if (err) - return load.evalError = LoaderError__Check_error_message_for_loader_stack(err, 'Evaluating ' + load.key); - - registry[load.key] = load.module = new ModuleNamespace(link.moduleObj); - - // if not an esm module, run importer setters and clear them - // this allows dynamic modules to update themselves into es modules - // as soon as execution has completed - if (!link.setters) { - if (load.importerSetters) - for (var i = 0; i < load.importerSetters.length; i++) - load.importerSetters[i](load.module); - load.importerSetters = undefined; - } -} - -// {} is the closest we can get to call(undefined) -var nullContext = {}; -if (Object.freeze) - Object.freeze(nullContext); - -function declarativeExecute (execute) { - try { - execute.call(nullContext); - } - catch (e) { - return e; - } -} - -function dynamicExecute (execute, require, exports, module) { - try { - var output = execute.call(envGlobal, require, exports, module); - if (output !== undefined) - module.exports = output; - } - catch (e) { - return e; - } -} - -var loader; - -// - - - - - - - - + - @@ -100,113 +66,103 @@
-

no
VNC

+

no
VNC

+ +
- + title="Move/Drag Viewport">
- - - - + id="noVNC_keyboard_button" class="noVNC_button" title="Show Keyboard">
-
- -
-
- - - - - -
-
+ +
+
+ + + + + + +
+ title="Shutdown/Reboot...">
- Power + Power
- - - + + +
+ title="Clipboard">
- Clipboard + Clipboard
+

+ Edit clipboard content in the textarea below. +

-
-
- + title="Full Screen"> + title="Settings">
+
+ Settings +
    -
  • - Settings -
  • - +
  • - +

  • - +
  • @@ -220,37 +176,50 @@

    no
    VNC

  • Advanced
      +
    • + + +
    • +
    • + + +
    • +

    • - +
    • WebSocket
      • - +
      • - +
      • - +
      • - +

    • - +
    • - + +
    • +

    • +
    • +

    • @@ -262,6 +231,11 @@

      no
      VNC

  • +

  • +
  • + Version: + +
@@ -269,40 +243,74 @@

no
VNC

+ title="Disconnect">
-
- +
+
+
+
+
- -
- Connect -
+ +
+ +
+ +
+
+
+ Server identity +
+
+ The server has provided the following identifying information: +
+
+ Fingerprint: + +
+
+ Please verify that the information is correct and press + "Approve". Otherwise press "Reject". +
+
+ + +
+
+
+
-
-
    -
  • - - -
  • -
  • - -
  • -
+
+
+ Credentials +
+
+ + +
+
+ + +
+
+ +
@@ -310,27 +318,19 @@

no
VNC

- +
+
- -
- - - - - Canvas not supported. - -
- + +