Repository: krakenjs/zoid Branch: main Commit: f88d82187fc1 Files: 199 Total size: 8.9 MB Directory structure: gitextract_3tngctqw/ ├── .eslintignore ├── .eslintrc.js ├── .flowconfig ├── .github/ │ ├── CODEOWNERS │ └── workflows/ │ ├── main.yml │ └── publish.yml ├── .gitignore ├── .husky/ │ ├── .gitignore │ ├── commit-msg │ └── pre-commit ├── .npmrc ├── .prettierignore ├── .prettierrc.json ├── AUTHORS.md ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── babel.config.js ├── commitlint.config.js ├── demo/ │ ├── advanced/ │ │ ├── props/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ ├── react-end-to-end/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ ├── redirect-different-domain/ │ │ │ ├── index.htm │ │ │ ├── login-button.htm │ │ │ ├── login-button.js │ │ │ ├── login.htm │ │ │ ├── login.js │ │ │ └── redirect.htm │ │ ├── remote/ │ │ │ ├── index.htm │ │ │ ├── login-button.htm │ │ │ ├── login-button.js │ │ │ ├── login.htm │ │ │ └── login.js │ │ └── remote-popup/ │ │ ├── index.htm │ │ ├── login-button.htm │ │ ├── login-button.js │ │ ├── login.htm │ │ └── login.js │ ├── basic/ │ │ ├── iframe/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ └── popup/ │ │ ├── index.htm │ │ ├── login.htm │ │ └── login.js │ ├── common/ │ │ ├── common.js │ │ ├── index.css │ │ └── login.css │ ├── frameworks/ │ │ ├── angular/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ ├── angular2/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ ├── angular2_TypeScript/ │ │ │ ├── app-component.html │ │ │ ├── app-component.ts │ │ │ ├── app-module.ts │ │ │ ├── config.js │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ ├── login.js │ │ │ ├── main.ts │ │ │ ├── start.cmd │ │ │ └── start.sh │ │ ├── react/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ ├── vue/ │ │ │ ├── index.htm │ │ │ ├── login.htm │ │ │ └── login.js │ │ └── vue3/ │ │ ├── index.htm │ │ ├── login.htm │ │ └── login.js │ └── index.htm ├── dist/ │ ├── zoid.frame.js │ ├── zoid.frameworks.frame.js │ ├── zoid.frameworks.js │ └── zoid.js ├── docs/ │ ├── api/ │ │ ├── component.md │ │ ├── create.md │ │ ├── index.md │ │ ├── instance.md │ │ ├── parent-props.md │ │ ├── prop-definitions.md │ │ ├── render.md │ │ └── xprops.md │ └── example.md ├── flow-typed/ │ └── npm/ │ ├── @commitlint/ │ │ ├── cli_vx.x.x.js │ │ └── config-conventional_vx.x.x.js │ ├── @krakenjs/ │ │ ├── belter_vx.x.x.js │ │ ├── cross-domain-utils_vx.x.x.js │ │ ├── grumbler-scripts_vx.x.x.js │ │ ├── jsx-pragmatic_vx.x.x.js │ │ ├── post-robot_vx.x.x.js │ │ └── zalgo-promise_vx.x.x.js │ ├── @octokit/ │ │ └── rest_v18.x.x.js │ ├── colors_v1.x.x.js │ ├── cross-env_vx.x.x.js │ ├── flow-bin_v0.x.x.js │ ├── fs-extra_v8.x.x.js │ ├── glob_v7.x.x.js │ ├── husky_vx.x.x.js │ ├── jest_v29.x.x.js │ ├── lint-staged_vx.x.x.js │ ├── md5_v2.x.x.js │ ├── mkdirp_v1.x.x.js │ ├── mocha_v4.x.x.js │ ├── node-stream-zip_v1.x.x.js │ ├── prettier_v1.x.x.js │ ├── prettier_vx.x.x.js │ ├── rimraf_v3.x.x.js │ ├── semver_v7.x.x.js │ ├── serve_vx.x.x.js │ ├── standard-version_vx.x.x.js │ └── yargs_v15.x.x.js ├── globals.js ├── index.js ├── karma.conf.js ├── package.json ├── src/ │ ├── babel.config.js │ ├── child/ │ │ ├── child.js │ │ ├── index.js │ │ └── props.js │ ├── component/ │ │ ├── component.js │ │ ├── index.js │ │ ├── props.js │ │ ├── templates/ │ │ │ ├── component.js │ │ │ ├── container.js │ │ │ └── index.js │ │ └── validate.js │ ├── constants.js │ ├── declarations.js │ ├── drivers/ │ │ ├── angular.js │ │ ├── angular2.js │ │ ├── index.js │ │ ├── react.js │ │ ├── vue.js │ │ └── vue3.js │ ├── index.js │ ├── lib/ │ │ ├── global.js │ │ ├── index.js │ │ ├── serialize.js │ │ └── window.js │ ├── parent/ │ │ ├── index.js │ │ ├── parent.js │ │ └── props.js │ └── types.js ├── test/ │ ├── babel.config.js │ ├── common.js │ ├── index.js │ ├── lib/ │ │ ├── angular-12/ │ │ │ ├── angular-12-common.js │ │ │ ├── angular-12-compiler.js │ │ │ ├── angular-12-core.js │ │ │ ├── angular-12-platform-browser-dynamic.js │ │ │ ├── angular-12-platform-browser.js │ │ │ ├── rxjs_v6.2.0.js │ │ │ └── zone_v0.8.12.js │ │ ├── angular-4.js │ │ ├── react-dom_v15.1.0.js │ │ ├── react-dom_v16.0.0.js │ │ ├── react_v15.1.0.js │ │ ├── react_v16.0.0.js │ │ └── vue_v3.2.1.js │ ├── test.js │ ├── tests/ │ │ ├── actions.jsx │ │ ├── attributes.js │ │ ├── bridge.js │ │ ├── child.js │ │ ├── children.jsx │ │ ├── clone.jsx │ │ ├── dimensions.jsx │ │ ├── domain.js │ │ ├── drivers.js │ │ ├── eligible.jsx │ │ ├── error.js │ │ ├── exports.js │ │ ├── extensions.jsx │ │ ├── happy.jsx │ │ ├── index.js │ │ ├── method.jsx │ │ ├── props.js │ │ ├── remove.jsx │ │ ├── renderto.jsx │ │ ├── rerender.js │ │ ├── validation.js │ │ └── window.js │ ├── windows/ │ │ ├── basicchild/ │ │ │ ├── index.htm │ │ │ └── index.js │ │ ├── bridge/ │ │ │ ├── index.htm │ │ │ └── index.js │ │ └── child/ │ │ ├── index.htm │ │ └── index.js │ ├── zoid.global.js │ └── zoid.js └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintignore ================================================ test/lib demo dist test/.eslintrc.js ================================================ FILE: .eslintrc.js ================================================ /* @flow */ module.exports = { extends: "@krakenjs/eslint-config-grumbler/eslintrc-browser", globals: { __ZOID__: true, __POST_ROBOT__: true, }, rules: { "react/display-name": "off", "react/prop-types": "off", }, overrides: [ { files: ["test/**/*"], rules: { "max-lines": "off", "compat/compat": "off", }, }, ], }; ================================================ FILE: .flowconfig ================================================ [ignore] .*/node_modules/babel-plugin-flow-runtime .*/node_modules/flow-runtime .*/node_modules/npm .*/node_modules/jsonlint .*/node_modules/resolve .*/dist/module [include] [libs] flow-typed src/declarations.js node_modules/@krakenjs/post-robot/src/declarations.js [options] module.name_mapper='^src\(.*\)$' -> '/src/\1' experimental.const_params=false ================================================ FILE: .github/CODEOWNERS ================================================ # Owner for everything in the repo * @krakenjs/checkout-sdk ================================================ FILE: .github/workflows/main.yml ================================================ name: build on: push: branches: - main pull_request: {} jobs: main: runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@v2 with: fetch-depth: 0 - name: ⎔ Setup node uses: actions/setup-node@v2 with: node-version: "16" registry-url: "https://registry.npmjs.org" - name: 📥 Download deps uses: bahmutov/npm-install@v1 with: useLockFile: false - name: 👕 Lint commit messages uses: wagoid/commitlint-github-action@v4 - name: ▶️ Run build and test script run: npm run build - name: ⬆️ Upload karma coverage report uses: codecov/codecov-action@v2 ================================================ FILE: .github/workflows/publish.yml ================================================ name: publish to npm on: workflow_dispatch jobs: main: runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@v2 with: fetch-depth: 0 - name: ⎔ Setup node # sets up the .npmrc file to publish to npm uses: actions/setup-node@v2 with: node-version: "16" registry-url: "https://registry.npmjs.org" - name: 📥 Download deps uses: bahmutov/npm-install@v1 with: useLockFile: false - name: Configure git user run: | git config --global user.email ${{ github.actor }}@users.noreply.github.com git config --global user.name ${{ github.actor }} - name: Publish to npm (main branch) if: github.ref_name == 'main' run: npm run release env: NODE_AUTH_TOKEN: ${{ secrets.KRAKENJS_PAYPAL_SDK_NPM_AUTH_TOKEN }} - name: Publish alpha to npm (non-main branch) if: github.ref_name != 'main' run: npm run release:alpha env: NODE_AUTH_TOKEN: ${{ secrets.KRAKENJS_PAYPAL_SDK_NPM_AUTH_TOKEN }} ================================================ FILE: .gitignore ================================================ # Logs logs *.log # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # Dependency directory # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git node_modules #IDE .idea/* .DS_Store package-lock.json ================================================ FILE: .husky/.gitignore ================================================ _ ================================================ FILE: .husky/commit-msg ================================================ #!/bin/sh . "$(dirname "$0")/_/husky.sh" npx --no -- commitlint --edit "$1" ================================================ FILE: .husky/pre-commit ================================================ #!/bin/sh . "$(dirname "$0")/_/husky.sh" npx lint-staged ================================================ FILE: .npmrc ================================================ registry=https://registry.npmjs.org/ package-lock=false save=false ================================================ FILE: .prettierignore ================================================ build dist coverage flow-typed test/lib/ CHANGELOG.md ================================================ FILE: .prettierrc.json ================================================ {} ================================================ FILE: AUTHORS.md ================================================ Daniel Brain Anurag Sinha ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### [10.5.1](https://github.com/krakenjs/zoid/compare/v10.5.0...v10.5.1) (2026-03-23) ## [10.5.0](https://github.com/krakenjs/zoid/compare/v10.4.0...v10.5.0) (2026-01-07) ### Features * add support for publishing alpha branches to npm ([#474](https://github.com/krakenjs/zoid/issues/474)) ([90c0b73](https://github.com/krakenjs/zoid/commit/90c0b73b2e658b5931f644cf8ae1f2871bc8f829)) ## [10.4.0](https://github.com/krakenjs/zoid/compare/v10.3.3...v10.4.0) (2024-12-19) ### Features * add getExtensions method to extend zoid component instance ([#468](https://github.com/krakenjs/zoid/issues/468)) ([44d2d24](https://github.com/krakenjs/zoid/commit/44d2d242dc60765a015821b7b3153fdfa18d7c00)) * support additional properties to be added to zoid component from the client ([#464](https://github.com/krakenjs/zoid/issues/464)) ([d2f3f09](https://github.com/krakenjs/zoid/commit/d2f3f0992ae9947e709d20875a666aedce645e3c)) ### Bug Fixes * commit flow-typed to fix ci ([#457](https://github.com/krakenjs/zoid/issues/457)) ([e4da223](https://github.com/krakenjs/zoid/commit/e4da22308b286fb2212af543574a1e66de7c70d1)) * resolve the promise when component is closed/destroyed ([#455](https://github.com/krakenjs/zoid/issues/455)) ([b42cc03](https://github.com/krakenjs/zoid/commit/b42cc038ec0019165848aa95ebffa652960e61d7)) * skip failing test ([#466](https://github.com/krakenjs/zoid/issues/466)) ([a70f250](https://github.com/krakenjs/zoid/commit/a70f250501cdfeba253a36afcdc8937afc2c42ee)) ### [10.3.3](https://github.com/krakenjs/zoid/compare/v10.3.2...v10.3.3) (2023-11-02) ### Bug Fixes * **initChild:** setName is applied in popup context ([#444](https://github.com/krakenjs/zoid/issues/444)) ([b26b8cb](https://github.com/krakenjs/zoid/commit/b26b8cba89324710beecbc09b99551ccf6630e32)) ### [10.3.2](https://github.com/krakenjs/zoid/compare/v10.3.1...v10.3.2) (2023-10-30) ### Bug Fixes * reduce frequency of iframe removed error ([#429](https://github.com/krakenjs/zoid/issues/429)) ([fd2ec05](https://github.com/krakenjs/zoid/commit/fd2ec05cab35143abc287649f6868ace4eb5626e)) * **venmo:** window name ([#443](https://github.com/krakenjs/zoid/issues/443)) ([02bcaab](https://github.com/krakenjs/zoid/commit/02bcaab83512d5339c921fe240f5929b4580e97d)) ### [10.3.1](https://github.com/krakenjs/zoid/compare/v10.3.0...v10.3.1) (2023-06-13) ### Bug Fixes * **prop:** trusted domain ([#440](https://github.com/krakenjs/zoid/issues/440)) ([081d0d5](https://github.com/krakenjs/zoid/commit/081d0d5a77bbd496284ef9e138f353a4386b6ee8)) ## [10.3.0](https://github.com/krakenjs/zoid/compare/v10.2.4...v10.3.0) (2023-06-12) ### Features * **venmo:** allow trusted domains ([#439](https://github.com/krakenjs/zoid/issues/439)) ([5f3bf00](https://github.com/krakenjs/zoid/commit/5f3bf00a08715154ff110023f0a1b862d560670e)) * **docs:** update npm badge ([#437](https://github.com/krakenjs/zoid/issues/437)) ([2ef6fdb](https://github.com/krakenjs/zoid/commit/2ef6fdb4efeeecdbbe446623cf45650499d598fa)) ### [10.2.4](https://github.com/krakenjs/zoid/compare/v10.2.3...v10.2.4) (2023-05-22) ### [10.2.3](https://github.com/krakenjs/zoid/compare/v10.2.2...v10.2.3) (2023-05-03) ### [10.2.2](https://github.com/krakenjs/zoid/compare/v10.2.1...v10.2.2) (2023-05-01) ### Bug Fixes * reduce frequency of "Detected iframe close" error ([#426](https://github.com/krakenjs/zoid/issues/426)) ([5343277](https://github.com/krakenjs/zoid/commit/53432775742a56aad8377c84258ec8d7a17d0450)) ### [10.2.1](https://github.com/krakenjs/zoid/compare/v10.2.0...v10.2.1) (2023-04-25) ### Bug Fixes * only throw errors for major version changes ([#425](https://github.com/krakenjs/zoid/issues/425)) ([57e8989](https://github.com/krakenjs/zoid/commit/57e8989fedf94ea1e1084827acc21fedfad6e267)) ## [10.2.0](https://github.com/krakenjs/zoid/compare/v10.1.0...v10.2.0) (2023-04-24) ### Features * upgrade to grumbler scripts 8 ([#414](https://github.com/krakenjs/zoid/issues/414)) ([b857e89](https://github.com/krakenjs/zoid/commit/b857e8930e76ebae77d755f5e9e0f5ac432a5790)) ### Bug Fixes * avoid throwing errors if container is no longer in page ([#424](https://github.com/krakenjs/zoid/issues/424)) ([e2825bb](https://github.com/krakenjs/zoid/commit/e2825bb5e08eadde14e8fc7b6b76d9069c5a3daf)) * **docs:** update github actions badge url ([#419](https://github.com/krakenjs/zoid/issues/419)) ([31d59fb](https://github.com/krakenjs/zoid/commit/31d59fbd1c89697e3773a5f043a506c95ee009a5)) * fix typos in parent-props and xprops docs ([#408](https://github.com/krakenjs/zoid/issues/408)) ([2fe2858](https://github.com/krakenjs/zoid/commit/2fe28584d75f9f740ec7a6d162b8d775c9cf39a0)) * remove token from publish action ([#422](https://github.com/krakenjs/zoid/issues/422)) ([3c6fa18](https://github.com/krakenjs/zoid/commit/3c6fa180c564b248d0e1b2ed66a2eaef8e2527e6)) * update babel config ([#418](https://github.com/krakenjs/zoid/issues/418)) ([2657252](https://github.com/krakenjs/zoid/commit/2657252085d401d64740fc3c8b372f085705bbf6)) * use prettier ([#401](https://github.com/krakenjs/zoid/issues/401)) ([3974c52](https://github.com/krakenjs/zoid/commit/3974c52a880e8b7a72201c9ad205b576611e7c65)) ## [10.1.0](https://github.com/krakenjs/zoid/compare/v10.0.0...v10.1.0) (2022-05-03) ### Features * add events on prerender start and finish ([#403](https://github.com/krakenjs/zoid/issues/403)) ([c603048](https://github.com/krakenjs/zoid/commit/c6030488dcbb4bb182b630acf722b6a8bbafc5dd)) * move devDependencies to [@krakenjs](https://github.com/krakenjs) scope ([#400](https://github.com/krakenjs/zoid/issues/400)) ([a085f40](https://github.com/krakenjs/zoid/commit/a085f408ff4f20d95f22ab5b44acb490038c33d7)) ## [10.0.0](https://github.com/krakenjs/zoid/compare/v9.0.87...v10.0.0) (2022-03-01) ### ⚠ BREAKING CHANGES * move to krakenjs scope (#395) * fix build badge ([eb8677a](https://github.com/krakenjs/zoid/commit/eb8677a3c41f8ad52158ad946573d0df9a47538d)) * move to krakenjs scope ([#395](https://github.com/krakenjs/zoid/issues/395)) ([c10ac41](https://github.com/krakenjs/zoid/commit/c10ac415ce6a2174c7ef08f2451da95bb9795888)) * standardize configs ([7504244](https://github.com/krakenjs/zoid/commit/7504244fe9c856a74e210008ed5fac00d2bf114d)) ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to zoid We are always looking for ways to make our modules better. Adding features and fixing bugs allows everyone who depends on this code to create better, more stable applications. Feel free to raise a pull request to us. Our team would review your proposed modifications and, if appropriate, merge your changes into our code. Ideas and other comments are also welcome. ## Getting Started 1. Create your own [fork](https://help.github.com/articles/fork-a-repo) of this [repository](../../fork). ```bash # Clone it $ git clone git@github.com:me/zoid.git # Change directory $ cd zoid # Add the upstream repo $ git remote add upstream git://github.com/krakenjs/zoid.git # Get the latest upstream changes $ git pull upstream # Install dependencies $ npm install # Run scripts to verify installation $ npm test $ npm run-script lint $ npm run-script cover ``` ## Making Changes 1. Make sure that your changes adhere to the current coding conventions used throughout the project, indentation, accurate comments, etc. 2. Lint your code regularly and ensure it passes prior to submitting a PR: `$ npm run lint`. 3. Ensure existing tests pass (`$ npm test`) and include test cases which fail without your change and succeed with it. ## Submitting Changes 1. Ensure that no errors are generated by ESLint. 2. Commit your changes in logical chunks, i.e. keep your changes small per single commit. 3. Locally merge (or rebase) the upstream branch into your topic branch: `$ git pull upstream && git merge`. 4. Push your topic branch up to your fork: `$ git push origin `. 5. Open a [Pull Request](https://help.github.com/articles/using-pull-requests) with a clear title and description. If you have any questions about contributing, please feel free to contact us by posting your questions on GitHub. Copyright 2016, PayPal under [the Apache 2.0 license](LICENSE.txt). ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2017 PayPal Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================

zoid

--- [![build status][build-badge]][build] [![code coverage][coverage-badge]][coverage] [![npm version][version-badge]][package] [build-badge]: https://img.shields.io/github/actions/workflow/status/krakenjs/zoid/main.yml?branch=main&logo=github&style=flat-square [build]: https://github.com/krakenjs/zoid/actions/workflows/main.yml?query=workflow:build [coverage-badge]: https://img.shields.io/codecov/c/github/krakenjs/zoid.svg?style=flat-square [coverage]: https://codecov.io/github/krakenjs/zoid/ [version-badge]: https://img.shields.io/npm/v/@krakenjs/zoid.svg?style=flat-square [package]: https://www.npmjs.com/package/@krakenjs/zoid A cross-domain component toolkit, supporting: - Render an iframe or popup on a different domain, and pass down props, including objects and functions - Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions - Create and expose components to share functionality from your site to others! - Render your component directly as a React, Vue or Angular component! It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups! --- ### [API Docs](./docs/api/index.md) Public options and methods supported by zoid ### [Demos](http://krakenjs.com/zoid/demo/index.htm) Working demos of different zoid patterns ### [Demo App](https://github.com/krakenjs/zoid-demo) Forkable demo app with build, test, publishing and demos pre-configured. ### [Example](./docs/example.md) A full example of a cross-domain component using zoid --- ### Quick example Define a component to be put on both the parent and child pages: ```javascript var MyLoginComponent = zoid.create({ tag: "my-login-component", url: "http://www.my-site.com/my-login-component", }); ``` Render the component on the parent page: ```javascript
``` Implement the component in the iframe: ```javascript ``` ### Useful Links - [Introducing zoid](https://medium.com/@bluepnume/introducing-zoid-seamless-cross-domain-web-components-from-paypal-c0144f3e82bf#.ikbg9r1ml) - [Turn your web-app into a cross-domain component with five lines of code](https://medium.com/@bluepnume/turn-your-web-app-into-a-cross-domain-component-with-5-lines-of-code-ced01e6795f9#.w8ea7h6ky) - [A full example of how to implement and use a zoid](./docs/example.md) - [Building PayPal's Button with zoid](https://medium.com/@bluepnume/less-is-more-reducing-thousands-of-paypal-buttons-into-a-single-iframe-using-zoid-d902d71d8875#.o3ib7y58n) - [PayPal Checkout - zoid powered Button and Checkout components](https://github.com/paypal/paypal-checkout) - [Post-Robot - the cross-domain messaging library which powers zoid](https://github.com/krakenjs/post-robot) - [Implementing Zoid video tutorial](https://www.youtube.com/watch?v=UpXavGv7FaI) #### Framework Specific - [Build a cross-domain React component](https://medium.com/@bluepnume/creating-a-cross-domain-react-component-with-zoid-fbcccc4778fd#.73jnwv44c) - [Introducing support for cross-domain Glimmer components, with zoid](https://medium.com/@bluepnume/introducing-support-for-cross-domain-glimmer-components-with-zoid-21287c9f91f1) ## Rationale **Writing cross domain components is tricky.** Consider this: I own `foo.com`, you own `bar.com`, and I have some functionality I want to share on your page. I could just give you some javascript to load in your page. But then: - What if I've written a component in React, but you're using some other framework? - What if I have secure form fields, or secure data I don't want your site to spy on? - What if I need to make secure calls to my back-end, without resorting to CORS? **What about an iframe?** You could just use a vanilla iframe for all of this. But: - You have to pass data down in the url, or with a post-message. - You need to set up post-message listeners to get events back up from the child. - You need to deal with error cases, like if your iframe fails to load or doesn't respond to a post-message. - You need to think carefully about how to expose all this functionality behind a simple, clear interface. **zoid solves all of these problems.** - You pass data and callbacks down as a javascript object - zoid renders the component and passes down the data - The child calls your callbacks when it's ready It will even automatically generate React and Angular bindings, so people can drop-in your component anywhere and not worry about iframes or post-messages. ## FAQ - **Do I need to use a particular framework like React to use zoid?** No, zoid is framework agnostic. You can: - Use it with vanilla javascript. - Use it with any framework of your choice. - Use it with React or Angular and take advantage of the automatic bindings on the parent page - **Why write another ui / component library?** This isn't designed to replace libraries like React, which are responsible for rendering same-domain components. In fact, the only real rendering zoid does is iframes and popups; the rest is up to you! You can build your components using any framework, library or pattern you want, then use zoid to expose your components cross-domain. It should play nicely with any other framework! - **Aren't iframes really slow?** Yes, but there are a few things to bear in mind here: - zoid isn't designed for building components for your own site. For that you should use native component libraries like React, which render quickly onto your page. Use zoid to share functionality with other sites, that you can't share native-javascript components with - zoid also provides mechanisms for pre-rendering html and css into iframes and popups, so you can at least render a loading spinner, or maybe something more advanced, while the new window loads its content. - **I don't want to bother with popups, can I get zoid with just the iframe support?** You can indeed. There's an `zoid.frame.js` and `zoid.frame.min.js` in the `dist/` folder. There's a lot of magic that's needed to make popups work with IE, and that's all trimmed out. - **Can I contribute?** By all means! But please raise an issue first if it's more than a small change, to discuss the feasibility. - **Is this different to [react-frame-component](https://github.com/ryanseddon/react-frame-component)?** Yes. `react-frame-component` allows you to render html into a sandboxed iframe on the same domain. `zoid` is geared around sharing functionality from one domain to another, in a cross-domain iframe. ## Browser Support - Internet Explorer 9+ - Chrome 27+ - Firefox 30+ - Safari 5.1+ - Opera 23+ ================================================ FILE: SECURITY.md ================================================ # Security Policy ## How is Zoid secure? Zoid uses [Post Robot](https://github.com/krakenjs/post-robot) to do [post messaging](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) between multiple domains. Zoid helps secure messaging through iframe sandboxing, domain validation, and data protection. - **Iframe sandboxing** is a default browser feature that blocks others from accessing the data of your iframe instance. - **Domain Validation** checks the domain of the connection made to the Zoid child component, if requested. If domains don’t match accepted domains the connect fails. This is to stop access to secure components. - **Data Protection** is the way Zoid manages checking domains of where the data was sent from to help protect against malicious data being injected through events. ## Things Zoid does NOT protect against - **Clickjacking** cannot be avoided. Even though the data is secure, the click is happening outside the scope of Zoid, therefore, Zoid cannot validate those actions. To learn more about **clickjacking** read [this](https://en.wikipedia.org/wiki/Clickjacking). ## Contact us We take security very seriously and ask that you follow the following process. If you think you may have found a security bug we ask that you privately send the details to DL-PP-Kraken-Js@paypal.com. Please make sure to use a descriptive title in the email. ## Expectations We will generally get back to you within **24 hours**, but a more detailed response may take up to **48 hours**. If you feel we're not responding back in time, please send us a message _without detail_ on Twitter [@kraken_js](https://twitter.com/kraken_js). ## History No reported issues ================================================ FILE: babel.config.js ================================================ /* @flow */ // eslint-disable-next-line import/no-commonjs module.exports = { extends: "@krakenjs/babel-config-grumbler/babelrc-node", ignore: ["test/lib"], }; ================================================ FILE: commitlint.config.js ================================================ /* @flow */ /* eslint import/no-commonjs: off */ module.exports = { extends: ["@commitlint/config-conventional"], }; ================================================ FILE: demo/advanced/props/index.htm ================================================

Log in on xyz.com



================================================ FILE: demo/advanced/props/login.htm ================================================


================================================ FILE: demo/advanced/props/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, // The properties they can (or must) pass down to my component props: { prefilledEmail: { type: "string", required: false, }, onLogin: { type: "function", }, }, }); ================================================ FILE: demo/advanced/react-end-to-end/index.htm ================================================
================================================ FILE: demo/advanced/react-end-to-end/login.htm ================================================
================================================ FILE: demo/advanced/react-end-to-end/login.js ================================================ window.LoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/advanced/redirect-different-domain/index.htm ================================================

Log in on xyz.com


================================================ FILE: demo/advanced/redirect-different-domain/login-button.htm ================================================
================================================ FILE: demo/advanced/redirect-different-domain/login-button.js ================================================ window.MyLoginButtonComponent = zoid.create({ // The html tag used to render my component tag: "my-login-button-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login-button.htm", window.location.href).href, // The size of the component on their page dimensions: { width: "250px", height: "100px", }, }); ================================================ FILE: demo/advanced/redirect-different-domain/login.htm ================================================


================================================ FILE: demo/advanced/redirect-different-domain/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("redirect.htm", window.location.href).href, domain: [/.*loca.*8080/, /.*loca.*8001/], }); ================================================ FILE: demo/advanced/redirect-different-domain/redirect.htm ================================================ ================================================ FILE: demo/advanced/remote/index.htm ================================================

Log in on xyz.com


================================================ FILE: demo/advanced/remote/login-button.htm ================================================
================================================ FILE: demo/advanced/remote/login-button.js ================================================ window.MyLoginButtonComponent = zoid.create({ // The html tag used to render my component tag: "my-login-button-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login-button.htm", window.location.href).href, // The size of the component on their page dimensions: { width: "250px", height: "100px", }, }); ================================================ FILE: demo/advanced/remote/login.htm ================================================


================================================ FILE: demo/advanced/remote/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/advanced/remote-popup/index.htm ================================================

Log in on xyz.com


================================================ FILE: demo/advanced/remote-popup/login-button.htm ================================================
================================================ FILE: demo/advanced/remote-popup/login-button.js ================================================ window.MyLoginButtonComponent = zoid.create({ // The html tag used to render my component tag: "my-login-button-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login-button.htm", window.location.href).href, // The size of the component on their page dimensions: { width: "250px", height: "100px", }, }); ================================================ FILE: demo/advanced/remote-popup/login.htm ================================================


================================================ FILE: demo/advanced/remote-popup/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/basic/iframe/index.htm ================================================

Log in on xyz.com

================================================ FILE: demo/basic/iframe/login.htm ================================================


================================================ FILE: demo/basic/iframe/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ dimensions: { width: "300px", height: "150px", }, // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/basic/popup/index.htm ================================================

Log in on xyz.com

================================================ FILE: demo/basic/popup/login.htm ================================================


================================================ FILE: demo/basic/popup/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, dimensions: { width: "300px", height: "150px", }, // The background overlay containerTemplate: ({ uid, tag, context, focus, close, doc }) => { function closeComponent(event) { event.preventDefault(); event.stopPropagation(); return close(); } function focusComponent(event) { event.preventDefault(); event.stopPropagation(); return focus(); } return pragmatic .node( "div", { id: uid, onClick: focusComponent, class: `${tag} ${tag}-context-${context} ${tag}-focus`, }, pragmatic.node("a", { href: "#", onClick: closeComponent, class: `${tag}-close`, }), pragmatic.node( "style", null, ` #${uid} { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.8); } #${uid}.${tag}-context-${zoid.CONTEXT.POPUP} { cursor: pointer; } #${uid} .${tag}-close { position: absolute; right: 16px; top: 16px; width: 16px; height: 16px; opacity: 0.6; } #${uid} .${tag}-close:hover { opacity: 1; } #${uid} .${tag}-close:before, #${uid} .${tag}-close:after { position: absolute; left: 8px; content: ' '; height: 16px; width: 2px; background-color: white; } #${uid} .${tag}-close:before { transform: rotate(45deg); } #${uid} .${tag}-close:after { transform: rotate(-45deg); } ` ) ) .render(pragmatic.dom({ doc })); }, }); ================================================ FILE: demo/common/common.js ================================================ ================================================ FILE: demo/common/index.css ================================================ body { text-align: center; } h3 { margin: 50px; } #container { display: inline-block; } ================================================ FILE: demo/common/login.css ================================================ html, body { overflow: hidden; } body { text-align: center; border: 1px solid #ccc; height: 100%; width: 100%; } form, input, button { text-align: center; margin-top: 10px; } input { text-align: left; padding-left: 10px; } .spinner { animation: rotator 1.4s linear infinite; display: inline-block; margin-top: 40px; } @keyframes rotator { 0% { transform: rotate(0deg); } 100% { transform: rotate(270deg); } } .path { stroke-dasharray: 187; stroke-dashoffset: 0; transform-origin: center; animation: dash 1.4s ease-in-out infinite, colors 5.6s ease-in-out infinite; } @keyframes colors { 0% { stroke: #4285f4; } 25% { stroke: #de3e35; } 50% { stroke: #f7c223; } 75% { stroke: #1b9a59; } 100% { stroke: #4285f4; } } @keyframes dash { 0% { stroke-dashoffset: 187; } 50% { stroke-dashoffset: 47; transform: rotate(135deg); } 100% { stroke-dashoffset: 187; transform: rotate(450deg); } } ================================================ FILE: demo/frameworks/angular/index.htm ================================================

Log in on xyz.com

User logged in with email: {{email}}
================================================ FILE: demo/frameworks/angular/login.htm ================================================


================================================ FILE: demo/frameworks/angular/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/frameworks/angular2/index.htm ================================================ Loading... ================================================ FILE: demo/frameworks/angular2/login.htm ================================================


================================================ FILE: demo/frameworks/angular2/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/frameworks/angular2_TypeScript/app-component.html ================================================

Log in on xyz.com

User logged in with email: {{email}}
================================================ FILE: demo/frameworks/angular2_TypeScript/app-component.ts ================================================ import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app-component.html", }) export class AppComponent { prefilledEmail: string; email: string; constructor() { this.prefilledEmail = "foo@bar.com"; this.onLogin = this.onLogin.bind(this); } public onLogin(email) { console.log("User logged in with email:", email); this.email = email; } } ================================================ FILE: demo/frameworks/angular2_TypeScript/app-module.ts ================================================ import * as ngCore from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { AppComponent } from "./app-component"; declare const zoid: any; declare const MyLoginZoidComponent: any; const MyLoginZoidComponentModule = MyLoginZoidComponent.driver( "angular2", ngCore ); @ngCore.NgModule({ imports: [BrowserModule, MyLoginZoidComponentModule], declarations: [AppComponent], bootstrap: [AppComponent], }) export class AppModule { constructor() {} } ================================================ FILE: demo/frameworks/angular2_TypeScript/config.js ================================================ System.config({ // use typescript for compilation transpiler: "typescript", // typescript compiler options typescriptOptions: { emitDecoratorMetadata: true, }, paths: { "npm:": "https://unpkg.com/", }, // map tells the System loader where to look for things map: { app: "./", "@angular/core": "npm:@angular/core/bundles/core.umd.js", "@angular/common": "npm:@angular/common/bundles/common.umd.js", "@angular/compiler": "npm:@angular/compiler/bundles/compiler.umd.js", "@angular/platform-browser": "npm:@angular/platform-browser/bundles/platform-browser.umd.js", "@angular/platform-browser-dynamic": "npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js", rxjs: "npm:rxjs", typescript: "npm:typescript@2.2.1/lib/typescript.js", }, // packages defines our app package packages: { app: { main: "./main.ts", defaultExtension: "ts", }, rxjs: { defaultExtension: "js", }, }, }); ================================================ FILE: demo/frameworks/angular2_TypeScript/index.htm ================================================ angular2 loading... ================================================ FILE: demo/frameworks/angular2_TypeScript/login.htm ================================================


================================================ FILE: demo/frameworks/angular2_TypeScript/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, props: { prefilledEmail: { type: "string", required: false, }, onLogin: { type: "function", required: true, }, }, }); ================================================ FILE: demo/frameworks/angular2_TypeScript/main.ts ================================================ //main entry point import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; import { AppModule } from "./app-module"; platformBrowserDynamic().bootstrapModule(AppModule); ================================================ FILE: demo/frameworks/angular2_TypeScript/start.cmd ================================================ Chrome.exe %CD%/index.htm --allow-file-access-from-files ================================================ FILE: demo/frameworks/angular2_TypeScript/start.sh ================================================ google-chrome $PWD/index.htm --allow-file-access-from-files ================================================ FILE: demo/frameworks/react/index.htm ================================================
================================================ FILE: demo/frameworks/react/login.htm ================================================


================================================ FILE: demo/frameworks/react/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/frameworks/vue/index.htm ================================================
================================================ FILE: demo/frameworks/vue/login.htm ================================================


================================================ FILE: demo/frameworks/vue/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/frameworks/vue3/index.htm ================================================
================================================ FILE: demo/frameworks/vue3/login.htm ================================================


================================================ FILE: demo/frameworks/vue3/login.js ================================================ window.MyLoginZoidComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: new URL("login.htm", window.location.href).href, }); ================================================ FILE: demo/index.htm ================================================ ================================================ FILE: dist/zoid.frame.js ================================================ !function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define("zoid", [], factory) : "object" == typeof exports ? exports.zoid = factory() : root.zoid = factory(); }("undefined" != typeof self ? self : this, (function() { return function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module = installedModules[moduleId] = { i: moduleId, l: !1, exports: {} }; modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); module.l = !0; return module.exports; } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d = function(exports, name, getter) { __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, { enumerable: !0, get: getter }); }; __webpack_require__.r = function(exports) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); Object.defineProperty(exports, "__esModule", { value: !0 }); }; __webpack_require__.t = function(value, mode) { 1 & mode && (value = __webpack_require__(value)); if (8 & mode) return value; if (4 & mode && "object" == typeof value && value && value.__esModule) return value; var ns = Object.create(null); __webpack_require__.r(ns); Object.defineProperty(ns, "default", { enumerable: !0, value: value }); if (2 & mode && "string" != typeof value) for (var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); return ns; }; __webpack_require__.n = function(module) { var getter = module && module.__esModule ? function() { return module.default; } : function() { return module; }; __webpack_require__.d(getter, "a", getter); return getter; }; __webpack_require__.o = function(object, property) { return {}.hasOwnProperty.call(object, property); }; __webpack_require__.p = ""; return __webpack_require__(__webpack_require__.s = 0); }([ function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, "PopupOpenError", (function() { return dom_PopupOpenError; })); __webpack_require__.d(__webpack_exports__, "create", (function() { return component_create; })); __webpack_require__.d(__webpack_exports__, "destroy", (function() { return component_destroy; })); __webpack_require__.d(__webpack_exports__, "destroyComponents", (function() { return destroyComponents; })); __webpack_require__.d(__webpack_exports__, "destroyAll", (function() { return destroyAll; })); __webpack_require__.d(__webpack_exports__, "PROP_TYPE", (function() { return PROP_TYPE; })); __webpack_require__.d(__webpack_exports__, "PROP_SERIALIZATION", (function() { return PROP_SERIALIZATION; })); __webpack_require__.d(__webpack_exports__, "CONTEXT", (function() { return CONTEXT; })); __webpack_require__.d(__webpack_exports__, "EVENT", (function() { return EVENT; })); function _setPrototypeOf(o, p) { return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) { o.__proto__ = p; return o; })(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _extends() { return (_extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) ({}).hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }).apply(this, arguments); } function utils_isPromise(item) { try { if (!item) return !1; if ("undefined" != typeof Promise && item instanceof Promise) return !0; if ("undefined" != typeof window && "function" == typeof window.Window && item instanceof window.Window) return !1; if ("undefined" != typeof window && "function" == typeof window.constructor && item instanceof window.constructor) return !1; var _toString = {}.toString; if (_toString) { var name = _toString.call(item); if ("[object Window]" === name || "[object global]" === name || "[object DOMWindow]" === name) return !1; } if ("function" == typeof item.then) return !0; } catch (err) { return !1; } return !1; } var dispatchedErrors = []; var possiblyUnhandledPromiseHandlers = []; var activeCount = 0; var flushPromise; function flushActive() { if (!activeCount && flushPromise) { var promise = flushPromise; flushPromise = null; promise.resolve(); } } function startActive() { activeCount += 1; } function endActive() { activeCount -= 1; flushActive(); } var promise_ZalgoPromise = function() { function ZalgoPromise(handler) { var _this = this; this.resolved = void 0; this.rejected = void 0; this.errorHandled = void 0; this.value = void 0; this.error = void 0; this.handlers = void 0; this.dispatching = void 0; this.stack = void 0; this.resolved = !1; this.rejected = !1; this.errorHandled = !1; this.handlers = []; if (handler) { var _result; var _error; var resolved = !1; var rejected = !1; var isAsync = !1; startActive(); try { handler((function(res) { if (isAsync) _this.resolve(res); else { resolved = !0; _result = res; } }), (function(err) { if (isAsync) _this.reject(err); else { rejected = !0; _error = err; } })); } catch (err) { endActive(); this.reject(err); return; } endActive(); isAsync = !0; resolved ? this.resolve(_result) : rejected && this.reject(_error); } } var _proto = ZalgoPromise.prototype; _proto.resolve = function(result) { if (this.resolved || this.rejected) return this; if (utils_isPromise(result)) throw new Error("Can not resolve promise with another promise"); this.resolved = !0; this.value = result; this.dispatch(); return this; }; _proto.reject = function(error) { var _this2 = this; if (this.resolved || this.rejected) return this; if (utils_isPromise(error)) throw new Error("Can not reject promise with another promise"); if (!error) { var _err = error && "function" == typeof error.toString ? error.toString() : {}.toString.call(error); error = new Error("Expected reject to be called with Error, got " + _err); } this.rejected = !0; this.error = error; this.errorHandled || setTimeout((function() { _this2.errorHandled || function(err, promise) { if (-1 === dispatchedErrors.indexOf(err)) { dispatchedErrors.push(err); setTimeout((function() { throw err; }), 1); for (var j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) possiblyUnhandledPromiseHandlers[j](err, promise); } }(error, _this2); }), 1); this.dispatch(); return this; }; _proto.asyncReject = function(error) { this.errorHandled = !0; this.reject(error); return this; }; _proto.dispatch = function() { var resolved = this.resolved, rejected = this.rejected, handlers = this.handlers; if (!this.dispatching && (resolved || rejected)) { this.dispatching = !0; startActive(); var chain = function(firstPromise, secondPromise) { return firstPromise.then((function(res) { secondPromise.resolve(res); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < handlers.length; i++) { var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise; var _result2 = void 0; if (resolved) try { _result2 = onSuccess ? onSuccess(this.value) : this.value; } catch (err) { promise.reject(err); continue; } else if (rejected) { if (!onError) { promise.reject(this.error); continue; } try { _result2 = onError(this.error); } catch (err) { promise.reject(err); continue; } } if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) { var promiseResult = _result2; promiseResult.resolved ? promise.resolve(promiseResult.value) : promise.reject(promiseResult.error); promiseResult.errorHandled = !0; } else utils_isPromise(_result2) ? _result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected) ? _result2.resolved ? promise.resolve(_result2.value) : promise.reject(_result2.error) : chain(_result2, promise) : promise.resolve(_result2); } handlers.length = 0; this.dispatching = !1; endActive(); } }; _proto.then = function(onSuccess, onError) { if (onSuccess && "function" != typeof onSuccess && !onSuccess.call) throw new Error("Promise.then expected a function for success handler"); if (onError && "function" != typeof onError && !onError.call) throw new Error("Promise.then expected a function for error handler"); var promise = new ZalgoPromise; this.handlers.push({ promise: promise, onSuccess: onSuccess, onError: onError }); this.errorHandled = !0; this.dispatch(); return promise; }; _proto.catch = function(onError) { return this.then(void 0, onError); }; _proto.finally = function(onFinally) { if (onFinally && "function" != typeof onFinally && !onFinally.call) throw new Error("Promise.finally expected a function"); return this.then((function(result) { return ZalgoPromise.try(onFinally).then((function() { return result; })); }), (function(err) { return ZalgoPromise.try(onFinally).then((function() { throw err; })); })); }; _proto.timeout = function(time, err) { var _this3 = this; if (this.resolved || this.rejected) return this; var timeout = setTimeout((function() { _this3.resolved || _this3.rejected || _this3.reject(err || new Error("Promise timed out after " + time + "ms")); }), time); return this.then((function(result) { clearTimeout(timeout); return result; })); }; _proto.toPromise = function() { if ("undefined" == typeof Promise) throw new TypeError("Could not find Promise"); return Promise.resolve(this); }; _proto.lazy = function() { this.errorHandled = !0; return this; }; ZalgoPromise.resolve = function(value) { return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise((function(resolve, reject) { return value.then(resolve, reject); })) : (new ZalgoPromise).resolve(value); }; ZalgoPromise.reject = function(error) { return (new ZalgoPromise).reject(error); }; ZalgoPromise.asyncReject = function(error) { return (new ZalgoPromise).asyncReject(error); }; ZalgoPromise.all = function(promises) { var promise = new ZalgoPromise; var count = promises.length; var results = [].slice(); if (!count) { promise.resolve(results); return promise; } var chain = function(i, firstPromise, secondPromise) { return firstPromise.then((function(res) { results[i] = res; 0 == (count -= 1) && promise.resolve(results); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < promises.length; i++) { var prom = promises[i]; if (prom instanceof ZalgoPromise) { if (prom.resolved) { results[i] = prom.value; count -= 1; continue; } } else if (!utils_isPromise(prom)) { results[i] = prom; count -= 1; continue; } chain(i, ZalgoPromise.resolve(prom), promise); } 0 === count && promise.resolve(results); return promise; }; ZalgoPromise.hash = function(promises) { var result = {}; var awaitPromises = []; var _loop = function(key) { if (promises.hasOwnProperty(key)) { var value = promises[key]; utils_isPromise(value) ? awaitPromises.push(value.then((function(res) { result[key] = res; }))) : result[key] = value; } }; for (var key in promises) _loop(key); return ZalgoPromise.all(awaitPromises).then((function() { return result; })); }; ZalgoPromise.map = function(items, method) { return ZalgoPromise.all(items.map(method)); }; ZalgoPromise.onPossiblyUnhandledException = function(handler) { return function(handler) { possiblyUnhandledPromiseHandlers.push(handler); return { cancel: function() { possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1); } }; }(handler); }; ZalgoPromise.try = function(method, context, args) { if (method && "function" != typeof method && !method.call) throw new Error("Promise.try expected a function"); var result; startActive(); try { result = method.apply(context, args || []); } catch (err) { endActive(); return ZalgoPromise.reject(err); } endActive(); return ZalgoPromise.resolve(result); }; ZalgoPromise.delay = function(_delay) { return new ZalgoPromise((function(resolve) { setTimeout(resolve, _delay); })); }; ZalgoPromise.isPromise = function(value) { return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value); }; ZalgoPromise.flush = function() { return function(Zalgo) { var promise = flushPromise = flushPromise || new Zalgo; flushActive(); return promise; }(ZalgoPromise); }; return ZalgoPromise; }(); function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return getActualProtocol(win); } function isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === getProtocol(win); } function utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function getOpener(win) { void 0 === win && (win = window); if (win && !utils_getParent(win)) try { return win.opener; } catch (err) {} } function canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = utils_getParent(win); return parent && canReadFromWindow() ? getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function getDomain(win) { void 0 === win && (win = window); var domain = getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (isAboutProtocol(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === getProtocol(win); }(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (getActualDomain(win) === getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (isAboutProtocol(win) && canReadFromWindow()) return !0; if (getDomain(window) === getDomain(win)) return !0; } catch (err) {} return !1; } function assertSameDomain(win) { if (!isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (utils_getParent(win) === win) return win; try { if (isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (utils_getParent(frame) === frame) return frame; } } function getAllFramesInWindow(win) { var top = getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], getAllChildFrames(win))); return result; } var iframeWindows = []; var iframeFrames = []; function isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || err.message !== IE_WIN_ACCESS_ERROR; } if (allowMock && isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(iframeWindows, win); if (-1 !== iframeIndex) { var frame = iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function getAncestor(win) { void 0 === win && (win = window); return getOpener(win = win || window) || utils_getParent(win) || void 0; } function anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some((function(subpattern) { return matchDomain(subpattern, origin); }))); } function isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function getFrameForWindow(win) { if (isSameDomain(win)) return assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { var frame = _document$querySelect2[_i21]; if (frame && frame.contentWindow && frame.contentWindow === win) return frame; } } function closeWindow(win) { if (function(win) { void 0 === win && (win = window); return Boolean(utils_getParent(win)); }(win)) { var frame = getFrameForWindow(win); if (frame && frame.parentElement) { frame.parentElement.removeChild(frame); return; } } try { win.close(); } catch (err) {} } function util_safeIndexOf(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; } var weakmap_CrossDomainSafeWeakMap = function() { function CrossDomainSafeWeakMap() { this.name = void 0; this.weakmap = void 0; this.keys = void 0; this.values = void 0; this.name = "__weakmap_" + (1e9 * Math.random() >>> 0) + "__"; if (function() { if ("undefined" == typeof WeakMap) return !1; if (void 0 === Object.freeze) return !1; try { var testWeakMap = new WeakMap; var testKey = {}; Object.freeze(testKey); testWeakMap.set(testKey, "__testvalue__"); return "__testvalue__" === testWeakMap.get(testKey); } catch (err) { return !1; } }()) try { this.weakmap = new WeakMap; } catch (err) {} this.keys = []; this.values = []; } var _proto = CrossDomainSafeWeakMap.prototype; _proto._cleanupClosedWindows = function() { var weakmap = this.weakmap; var keys = this.keys; for (var i = 0; i < keys.length; i++) { var value = keys[i]; if (isWindow(value) && isWindowClosed(value)) { if (weakmap) try { weakmap.delete(value); } catch (err) {} keys.splice(i, 1); this.values.splice(i, 1); i -= 1; } } }; _proto.isSafeToReadWrite = function(key) { return !isWindow(key); }; _proto.set = function(key, value) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.set(key, value); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var name = this.name; var entry = key[name]; entry && entry[0] === key ? entry[1] = value : Object.defineProperty(key, name, { value: [ key, value ], writable: !0 }); return; } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var values = this.values; var index = util_safeIndexOf(keys, key); if (-1 === index) { keys.push(key); values.push(value); } else values[index] = value; }; _proto.get = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return weakmap.get(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return entry && entry[0] === key ? entry[1] : void 0; } catch (err) {} this._cleanupClosedWindows(); var index = util_safeIndexOf(this.keys, key); if (-1 !== index) return this.values[index]; }; _proto.delete = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.delete(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; entry && entry[0] === key && (entry[0] = entry[1] = void 0); } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var index = util_safeIndexOf(keys, key); if (-1 !== index) { keys.splice(index, 1); this.values.splice(index, 1); } }; _proto.has = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return !0; } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return !(!entry || entry[0] !== key); } catch (err) {} this._cleanupClosedWindows(); return -1 !== util_safeIndexOf(this.keys, key); }; _proto.getOrSet = function(key, getter) { if (this.has(key)) return this.get(key); var value = getter(); this.set(key, value); return value; }; return CrossDomainSafeWeakMap; }(); function _getPrototypeOf(o) { return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) { return o.__proto__ || Object.getPrototypeOf(o); })(o); } function _isNativeReflectConstruct() { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { Date.prototype.toString.call(Reflect.construct(Date, [], (function() {}))); return !0; } catch (e) { return !1; } } function construct_construct(Parent, args, Class) { return (construct_construct = _isNativeReflectConstruct() ? Reflect.construct : function(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var instance = new (Function.bind.apply(Parent, a)); Class && _setPrototypeOf(instance, Class.prototype); return instance; }).apply(null, arguments); } function wrapNativeSuper_wrapNativeSuper(Class) { var _cache = "function" == typeof Map ? new Map : void 0; return (wrapNativeSuper_wrapNativeSuper = function(Class) { if (null === Class || !(fn = Class, -1 !== Function.toString.call(fn).indexOf("[native code]"))) return Class; var fn; if ("function" != typeof Class) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== _cache) { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct_construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }); return _setPrototypeOf(Wrapper, Class); })(Class); } function isElement(element) { var passed = !1; try { (element instanceof window.Element || null !== element && "object" == typeof element && 1 === element.nodeType && "object" == typeof element.style && "object" == typeof element.ownerDocument) && (passed = !0); } catch (_) {} return passed; } function getFunctionName(fn) { return fn.name || fn.__name__ || fn.displayName || "anonymous"; } function setFunctionName(fn, name) { try { delete fn.name; fn.name = name; } catch (err) {} fn.__name__ = fn.displayName = name; return fn; } function base64encode(str) { if ("function" == typeof btoa) return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (function(m, p1) { return String.fromCharCode(parseInt(p1, 16)); }))).replace(/[=]/g, ""); if ("undefined" != typeof Buffer) return Buffer.from(str, "utf8").toString("base64").replace(/[=]/g, ""); throw new Error("Can not find window.btoa or Buffer"); } function uniqueID() { var chars = "0123456789abcdef"; return "uid_" + "xxxxxxxxxx".replace(/./g, (function() { return chars.charAt(Math.floor(Math.random() * chars.length)); })) + "_" + base64encode((new Date).toISOString().slice(11, 19).replace("T", ".")).replace(/[^a-zA-Z0-9]/g, "").toLowerCase(); } var objectIDs; function serializeArgs(args) { try { return JSON.stringify([].slice.call(args), (function(subkey, val) { return "function" == typeof val ? "memoize[" + function(obj) { objectIDs = objectIDs || new weakmap_CrossDomainSafeWeakMap; if (null == obj || "object" != typeof obj && "function" != typeof obj) throw new Error("Invalid object"); var uid = objectIDs.get(obj); if (!uid) { uid = typeof obj + ":" + uniqueID(); objectIDs.set(obj, uid); } return uid; }(val) + "]" : isElement(val) ? {} : val; })); } catch (err) { throw new Error("Arguments not serializable -- can not be used to memoize"); } } function getEmptyObject() { return {}; } var memoizeGlobalIndex = 0; var memoizeGlobalIndexValidFrom = 0; function memoize(method, options) { void 0 === options && (options = {}); var _options$thisNamespac = options.thisNamespace, thisNamespace = void 0 !== _options$thisNamespac && _options$thisNamespac, cacheTime = options.time; var simpleCache; var thisCache; var memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; var memoizedFunction = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; if (memoizeIndex < memoizeGlobalIndexValidFrom) { simpleCache = null; thisCache = null; memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; } var cache; cache = thisNamespace ? (thisCache = thisCache || new weakmap_CrossDomainSafeWeakMap).getOrSet(this, getEmptyObject) : simpleCache = simpleCache || {}; var cacheKey; try { cacheKey = serializeArgs(args); } catch (_unused) { return method.apply(this, arguments); } var cacheResult = cache[cacheKey]; if (cacheResult && cacheTime && Date.now() - cacheResult.time < cacheTime) { delete cache[cacheKey]; cacheResult = null; } if (cacheResult) return cacheResult.value; var time = Date.now(); var value = method.apply(this, arguments); cache[cacheKey] = { time: time, value: value }; return value; }; memoizedFunction.reset = function() { simpleCache = null; thisCache = null; }; return setFunctionName(memoizedFunction, (options.name || getFunctionName(method)) + "::memoized"); } memoize.clear = function() { memoizeGlobalIndexValidFrom = memoizeGlobalIndex; }; function memoizePromise(method) { var cache = {}; function memoizedPromiseFunction() { var _arguments = arguments, _this = this; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; var key = serializeArgs(args); if (cache.hasOwnProperty(key)) return cache[key]; cache[key] = promise_ZalgoPromise.try((function() { return method.apply(_this, _arguments); })).finally((function() { delete cache[key]; })); return cache[key]; } memoizedPromiseFunction.reset = function() { cache = {}; }; return setFunctionName(memoizedPromiseFunction, getFunctionName(method) + "::promiseMemoized"); } function src_util_noop() {} function once(method) { var called = !1; return setFunctionName((function() { if (!called) { called = !0; return method.apply(this, arguments); } }), getFunctionName(method) + "::once"); } function stringifyError(err, level) { void 0 === level && (level = 1); if (level >= 3) return "stringifyError stack overflow"; try { if (!err) return ""; if ("string" == typeof err) return err; if (err instanceof Error) { var stack = err && err.stack; var message = err && err.message; if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + "\n" + stack; if (stack) return stack; if (message) return message; } return err && err.toString && "function" == typeof err.toString ? err.toString() : {}.toString.call(err); } catch (newErr) { return "Error while stringifying error: " + stringifyError(newErr, level + 1); } } function stringify(item) { return "string" == typeof item ? item : item && item.toString && "function" == typeof item.toString ? item.toString() : {}.toString.call(item); } function extend(obj, source) { if (!source) return obj; if (Object.assign) return Object.assign(obj, source); for (var key in source) source.hasOwnProperty(key) && (obj[key] = source[key]); return obj; } memoize((function(obj) { if (Object.values) return Object.values(obj); var result = []; for (var key in obj) obj.hasOwnProperty(key) && result.push(obj[key]); return result; })); function identity(item) { return item; } function safeInterval(method, time) { var timeout; !function loop() { timeout = setTimeout((function() { method(); loop(); }), time); }(); return { cancel: function() { clearTimeout(timeout); } }; } function arrayFrom(item) { return [].slice.call(item); } function isDefined(value) { return null != value; } function util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function util_getOrSet(obj, key, getter) { if (obj.hasOwnProperty(key)) return obj[key]; var val = getter(); obj[key] = val; return val; } function cleanup(obj) { var tasks = []; var cleaned = !1; var cleanErr; var cleaner = { set: function(name, item) { if (!cleaned) { obj[name] = item; cleaner.register((function() { delete obj[name]; })); } return item; }, register: function(method) { var task = once((function() { return method(cleanErr); })); cleaned ? method(cleanErr) : tasks.push(task); return { cancel: function() { var index = tasks.indexOf(task); -1 !== index && tasks.splice(index, 1); } }; }, all: function(err) { cleanErr = err; var results = []; cleaned = !0; for (;tasks.length; ) { var task = tasks.shift(); results.push(task()); } return promise_ZalgoPromise.all(results).then(src_util_noop); } }; return cleaner; } function assertExists(name, thing) { if (null == thing) throw new Error("Expected " + name + " to be present"); return thing; } var util_ExtendableError = function(_Error) { _inheritsLoose(ExtendableError, _Error); function ExtendableError(message) { var _this6; (_this6 = _Error.call(this, message) || this).name = _this6.constructor.name; "function" == typeof Error.captureStackTrace ? Error.captureStackTrace(function(self) { if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; }(_this6), _this6.constructor) : _this6.stack = new Error(message).stack; return _this6; } return ExtendableError; }(wrapNativeSuper_wrapNativeSuper(Error)); function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); return body; } function isDocumentReady() { return Boolean(document.body) && "complete" === document.readyState; } function isDocumentInteractive() { return Boolean(document.body) && "interactive" === document.readyState; } function urlEncode(str) { return encodeURIComponent(str); } memoize((function() { return new promise_ZalgoPromise((function(resolve) { if (isDocumentReady() || isDocumentInteractive()) return resolve(); var interval = setInterval((function() { if (isDocumentReady() || isDocumentInteractive()) { clearInterval(interval); return resolve(); } }), 10); })); })); function parseQuery(queryString) { return function(method, logic, args) { void 0 === args && (args = []); var cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {}; var key = serializeArgs(args); return cache.hasOwnProperty(key) ? cache[key] : cache[key] = function() { var params = {}; if (!queryString) return params; if (-1 === queryString.indexOf("=")) return params; for (var _i2 = 0, _queryString$split2 = queryString.split("&"); _i2 < _queryString$split2.length; _i2++) { var pair = _queryString$split2[_i2]; (pair = pair.split("="))[0] && pair[1] && (params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1])); } return params; }.apply(void 0, args); }(parseQuery, 0, [ queryString ]); } function extendQuery(originalQuery, props) { void 0 === props && (props = {}); return props && Object.keys(props).length ? function(obj) { void 0 === obj && (obj = {}); return Object.keys(obj).filter((function(key) { return "string" == typeof obj[key] || "boolean" == typeof obj[key]; })).map((function(key) { var val = obj[key]; if ("string" != typeof val && "boolean" != typeof val) throw new TypeError("Invalid type for query"); return urlEncode(key) + "=" + urlEncode(val.toString()); })).join("&"); }(_extends({}, parseQuery(originalQuery), props)) : originalQuery; } function appendChild(container, child) { container.appendChild(child); } function getElementSafe(id, doc) { void 0 === doc && (doc = document); return isElement(id) ? id : "string" == typeof id ? doc.querySelector(id) : void 0; } function elementReady(id) { return new promise_ZalgoPromise((function(resolve, reject) { var name = stringify(id); var el = getElementSafe(id); if (el) return resolve(el); if (isDocumentReady()) return reject(new Error("Document is ready and element " + name + " does not exist")); var interval = setInterval((function() { if (el = getElementSafe(id)) { resolve(el); clearInterval(interval); } else if (isDocumentReady()) { clearInterval(interval); return reject(new Error("Document is ready and element " + name + " does not exist")); } }), 10); })); } var dom_PopupOpenError = function(_ExtendableError) { _inheritsLoose(PopupOpenError, _ExtendableError); function PopupOpenError() { return _ExtendableError.apply(this, arguments) || this; } return PopupOpenError; }(util_ExtendableError); var awaitFrameLoadPromises; function awaitFrameLoad(frame) { if ((awaitFrameLoadPromises = awaitFrameLoadPromises || new weakmap_CrossDomainSafeWeakMap).has(frame)) { var _promise = awaitFrameLoadPromises.get(frame); if (_promise) return _promise; } var promise = new promise_ZalgoPromise((function(resolve, reject) { frame.addEventListener("load", (function() { !function(frame) { !function() { for (var i = 0; i < iframeWindows.length; i++) { var closed = !1; try { closed = iframeWindows[i].closed; } catch (err) {} if (closed) { iframeFrames.splice(i, 1); iframeWindows.splice(i, 1); } } }(); if (frame && frame.contentWindow) try { iframeWindows.push(frame.contentWindow); iframeFrames.push(frame); } catch (err) {} }(frame); resolve(frame); })); frame.addEventListener("error", (function(err) { frame.contentWindow ? resolve(frame) : reject(err); })); })); awaitFrameLoadPromises.set(frame, promise); return promise; } function awaitFrameWindow(frame) { return awaitFrameLoad(frame).then((function(loadedFrame) { if (!loadedFrame.contentWindow) throw new Error("Could not find window in iframe"); return loadedFrame.contentWindow; })); } function dom_iframe(options, container) { void 0 === options && (options = {}); var style = options.style || {}; var frame = function(tag, options, container) { void 0 === tag && (tag = "div"); void 0 === options && (options = {}); tag = tag.toLowerCase(); var element = document.createElement(tag); options.style && extend(element.style, options.style); options.class && (element.className = options.class.join(" ")); options.id && element.setAttribute("id", options.id); if (options.attributes) for (var _i10 = 0, _Object$keys2 = Object.keys(options.attributes); _i10 < _Object$keys2.length; _i10++) { var key = _Object$keys2[_i10]; element.setAttribute(key, options.attributes[key]); } options.styleSheet && function(el, styleText, doc) { void 0 === doc && (doc = window.document); el.styleSheet ? el.styleSheet.cssText = styleText : el.appendChild(doc.createTextNode(styleText)); }(element, options.styleSheet); if (options.html) { if ("iframe" === tag) throw new Error("Iframe html can not be written unless container provided and iframe in DOM"); element.innerHTML = options.html; } return element; }("iframe", { attributes: _extends({ allowTransparency: "true" }, options.attributes || {}), style: _extends({ backgroundColor: "transparent", border: "none" }, style), html: options.html, class: options.class }); var isIE = window.navigator.userAgent.match(/MSIE|Edge/i); frame.hasAttribute("id") || frame.setAttribute("id", uniqueID()); awaitFrameLoad(frame); container && function(id, doc) { void 0 === doc && (doc = document); var element = getElementSafe(id, doc); if (element) return element; throw new Error("Can not find element: " + stringify(id)); }(container).appendChild(frame); (options.url || isIE) && frame.setAttribute("src", options.url || "about:blank"); return frame; } function addEventListener(obj, event, handler) { obj.addEventListener(event, handler); return { cancel: function() { obj.removeEventListener(event, handler); } }; } function showElement(element) { element.style.setProperty("display", ""); } function hideElement(element) { element.style.setProperty("display", "none", "important"); } function destroyElement(element) { element && element.parentNode && element.parentNode.removeChild(element); } function isElementClosed(el) { return !(el && el.parentNode && el.ownerDocument && el.ownerDocument.documentElement && el.ownerDocument.documentElement.contains(el)); } function onResize(el, handler, _temp) { var _ref2 = void 0 === _temp ? {} : _temp, _ref2$width = _ref2.width, width = void 0 === _ref2$width || _ref2$width, _ref2$height = _ref2.height, height = void 0 === _ref2$height || _ref2$height, _ref2$interval = _ref2.interval, interval = void 0 === _ref2$interval ? 100 : _ref2$interval, _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win; var currentWidth = el.offsetWidth; var currentHeight = el.offsetHeight; var canceled = !1; handler({ width: currentWidth, height: currentHeight }); var check = function() { if (!canceled && function(el) { return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length); }(el)) { var newWidth = el.offsetWidth; var newHeight = el.offsetHeight; (width && newWidth !== currentWidth || height && newHeight !== currentHeight) && handler({ width: newWidth, height: newHeight }); currentWidth = newWidth; currentHeight = newHeight; } }; var observer; var timeout; win.addEventListener("resize", check); if (void 0 !== win.ResizeObserver) { (observer = new win.ResizeObserver(check)).observe(el); timeout = safeInterval(check, 10 * interval); } else if (void 0 !== win.MutationObserver) { (observer = new win.MutationObserver(check)).observe(el, { attributes: !0, childList: !0, subtree: !0, characterData: !1 }); timeout = safeInterval(check, 10 * interval); } else timeout = safeInterval(check, interval); return { cancel: function() { canceled = !0; observer.disconnect(); window.removeEventListener("resize", check); timeout.cancel(); } }; } function isShadowElement(element) { for (;element.parentNode; ) element = element.parentNode; return "[object ShadowRoot]" === element.toString(); } var currentScript = "undefined" != typeof document ? document.currentScript : null; var getCurrentScript = memoize((function() { if (currentScript) return currentScript; if (currentScript = function() { try { var stack = function() { try { throw new Error("_"); } catch (err) { return err.stack || ""; } }(); var stackDetails = /.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(stack); var scriptLocation = stackDetails && stackDetails[1]; if (!scriptLocation) return; for (var _i22 = 0, _Array$prototype$slic2 = [].slice.call(document.getElementsByTagName("script")).reverse(); _i22 < _Array$prototype$slic2.length; _i22++) { var script = _Array$prototype$slic2[_i22]; if (script.src && script.src === scriptLocation) return script; } } catch (err) {} }()) return currentScript; throw new Error("Can not determine current script"); })); var currentUID = uniqueID(); memoize((function() { var script; try { script = getCurrentScript(); } catch (err) { return currentUID; } var uid = script.getAttribute("data-uid"); if (uid && "string" == typeof uid) return uid; if ((uid = script.getAttribute("data-uid-auto")) && "string" == typeof uid) return uid; if (script.src) { var hashedString = function(str) { var hash = ""; for (var i = 0; i < str.length; i++) { var total = str[i].charCodeAt(0) * i; str[i + 1] && (total += str[i + 1].charCodeAt(0) * (i - 1)); hash += String.fromCharCode(97 + Math.abs(total) % 26); } return hash; }(JSON.stringify({ src: script.src, dataset: script.dataset })); uid = "uid_" + hashedString.slice(hashedString.length - 30); } else uid = uniqueID(); script.setAttribute("data-uid-auto", uid); return uid; })); function toPx(val) { return function(val) { if ("number" == typeof val) return val; var match = val.match(/^([0-9]+)(px|%)$/); if (!match) throw new Error("Could not match css value from " + val); return parseInt(match[1], 10); }(val) + "px"; } function toCSS(val) { return "number" == typeof val ? toPx(val) : "string" == typeof (str = val) && /^[0-9]+%$/.test(str) ? val : toPx(val); var str; } function global_getGlobal(win) { void 0 === win && (win = window); var globalKey = "__post_robot_10_0_46__"; return win !== window ? win[globalKey] : win[globalKey] = win[globalKey] || {}; } var getObj = function() { return {}; }; function globalStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return util_getOrSet(global_getGlobal(), key, (function() { var store = defStore(); return { has: function(storeKey) { return store.hasOwnProperty(storeKey); }, get: function(storeKey, defVal) { return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal; }, set: function(storeKey, val) { store[storeKey] = val; return val; }, del: function(storeKey) { delete store[storeKey]; }, getOrSet: function(storeKey, getter) { return util_getOrSet(store, storeKey, getter); }, reset: function() { store = defStore(); }, keys: function() { return Object.keys(store); } }; })); } var WildCard = function() {}; function getWildcard() { var global = global_getGlobal(); global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard; return global.WINDOW_WILDCARD; } function windowStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return globalStore("windowStore").getOrSet(key, (function() { var winStore = new weakmap_CrossDomainSafeWeakMap; var getStore = function(win) { return winStore.getOrSet(win, defStore); }; return { has: function(win) { return getStore(win).hasOwnProperty(key); }, get: function(win, defVal) { var store = getStore(win); return store.hasOwnProperty(key) ? store[key] : defVal; }, set: function(win, val) { getStore(win)[key] = val; return val; }, del: function(win) { delete getStore(win)[key]; }, getOrSet: function(win, getter) { return util_getOrSet(getStore(win), key, getter); } }; })); } function getInstanceID() { return globalStore("instance").getOrSet("instanceID", uniqueID); } function resolveHelloPromise(win, _ref) { var domain = _ref.domain; var helloPromises = windowStore("helloPromises"); var existingPromise = helloPromises.get(win); existingPromise && existingPromise.resolve({ domain: domain }); var newPromise = promise_ZalgoPromise.resolve({ domain: domain }); helloPromises.set(win, newPromise); return newPromise; } function sayHello(win, _ref4) { return (0, _ref4.send)(win, "postrobot_hello", { instanceID: getInstanceID() }, { domain: "*", timeout: -1 }).then((function(_ref5) { var origin = _ref5.origin, instanceID = _ref5.data.instanceID; resolveHelloPromise(win, { domain: origin }); return { win: win, domain: origin, instanceID: instanceID }; })); } function getWindowInstanceID(win, _ref6) { var send = _ref6.send; return windowStore("windowInstanceIDPromises").getOrSet(win, (function() { return sayHello(win, { send: send }).then((function(_ref7) { return _ref7.instanceID; })); })); } function markWindowKnown(win) { windowStore("knownWindows").set(win, !0); } function isSerializedType(item) { return "object" == typeof item && null !== item && "string" == typeof item.__type__; } function determineType(val) { return void 0 === val ? "undefined" : null === val ? "null" : Array.isArray(val) ? "array" : "function" == typeof val ? "function" : "object" == typeof val ? val instanceof Error ? "error" : "function" == typeof val.then ? "promise" : "[object RegExp]" === {}.toString.call(val) ? "regex" : "[object Date]" === {}.toString.call(val) ? "date" : "object" : "string" == typeof val ? "string" : "number" == typeof val ? "number" : "boolean" == typeof val ? "boolean" : void 0; } function serializeType(type, val) { return { __type__: type, __val__: val }; } var _SERIALIZER; var SERIALIZER = ((_SERIALIZER = {}).function = function() {}, _SERIALIZER.error = function(_ref) { return serializeType("error", { message: _ref.message, stack: _ref.stack, code: _ref.code, data: _ref.data }); }, _SERIALIZER.promise = function() {}, _SERIALIZER.regex = function(val) { return serializeType("regex", val.source); }, _SERIALIZER.date = function(val) { return serializeType("date", val.toJSON()); }, _SERIALIZER.array = function(val) { return val; }, _SERIALIZER.object = function(val) { return val; }, _SERIALIZER.string = function(val) { return val; }, _SERIALIZER.number = function(val) { return val; }, _SERIALIZER.boolean = function(val) { return val; }, _SERIALIZER.null = function(val) { return val; }, _SERIALIZER[void 0] = function(val) { return serializeType("undefined", val); }, _SERIALIZER); var defaultSerializers = {}; var _DESERIALIZER; var DESERIALIZER = ((_DESERIALIZER = {}).function = function() { throw new Error("Function serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.error = function(_ref2) { var stack = _ref2.stack, code = _ref2.code, data = _ref2.data; var error = new Error(_ref2.message); error.code = code; data && (error.data = data); error.stack = stack + "\n\n" + error.stack; return error; }, _DESERIALIZER.promise = function() { throw new Error("Promise serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.regex = function(val) { return new RegExp(val); }, _DESERIALIZER.date = function(val) { return new Date(val); }, _DESERIALIZER.array = function(val) { return val; }, _DESERIALIZER.object = function(val) { return val; }, _DESERIALIZER.string = function(val) { return val; }, _DESERIALIZER.number = function(val) { return val; }, _DESERIALIZER.boolean = function(val) { return val; }, _DESERIALIZER.null = function(val) { return val; }, _DESERIALIZER[void 0] = function() {}, _DESERIALIZER); var defaultDeserializers = {}; new promise_ZalgoPromise((function(resolve) { if (window.document && window.document.body) return resolve(window.document.body); var interval = setInterval((function() { if (window.document && window.document.body) { clearInterval(interval); return resolve(window.document.body); } }), 10); })); function cleanupProxyWindows() { var idToProxyWindow = globalStore("idToProxyWindow"); for (var _i2 = 0, _idToProxyWindow$keys2 = idToProxyWindow.keys(); _i2 < _idToProxyWindow$keys2.length; _i2++) { var id = _idToProxyWindow$keys2[_i2]; idToProxyWindow.get(id).shouldClean() && idToProxyWindow.del(id); } } function getSerializedWindow(winPromise, _ref) { var send = _ref.send, _ref$id = _ref.id, id = void 0 === _ref$id ? uniqueID() : _ref$id; var windowNamePromise = winPromise.then((function(win) { if (isSameDomain(win)) return assertSameDomain(win).name; })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); return getOpener(window) ? "popup" : "iframe"; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); var getName = function() { return winPromise.then((function(win) { if (!isWindowClosed(win)) return isSameDomain(win) ? assertSameDomain(win).name : windowNamePromise; })); }; return { id: id, getType: function() { return windowTypePromise; }, getInstanceID: memoizePromise((function() { return winPromise.then((function(win) { return getWindowInstanceID(win, { send: send }); })); })), close: function() { return winPromise.then(closeWindow); }, getName: getName, focus: function() { return winPromise.then((function(win) { win.focus(); })); }, isClosed: function() { return winPromise.then((function(win) { return isWindowClosed(win); })); }, setLocation: function(href, opts) { void 0 === opts && (opts = {}); return winPromise.then((function(win) { var domain = window.location.protocol + "//" + window.location.host; var _opts$method = opts.method, method = void 0 === _opts$method ? "get" : _opts$method, body = opts.body; if (0 === href.indexOf("/")) href = "" + domain + href; else if (!href.match(/^https?:\/\//) && 0 !== href.indexOf(domain)) throw new Error("Expected url to be http or https url, or absolute path, got " + JSON.stringify(href)); if ("post" === method) return getName().then((function(name) { if (!name) throw new Error("Can not post to window without target name"); !function(_ref3) { var url = _ref3.url, target = _ref3.target, body = _ref3.body, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "post" : _ref3$method; var form = document.createElement("form"); form.setAttribute("target", target); form.setAttribute("method", method); form.setAttribute("action", url); form.style.display = "none"; if (body) for (var _i24 = 0, _Object$keys4 = Object.keys(body); _i24 < _Object$keys4.length; _i24++) { var _body$key; var key = _Object$keys4[_i24]; var input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", null == (_body$key = body[key]) ? void 0 : _body$key.toString()); form.appendChild(input); } getBody().appendChild(form); form.submit(); getBody().removeChild(form); }({ url: href, target: name, method: method, body: body }); })); if ("get" !== method) throw new Error("Unsupported method: " + method); if (isSameDomain(win)) try { if (win.location && "function" == typeof win.location.replace) { win.location.replace(href); return; } } catch (err) {} win.location = href; })); }, setName: function(name) { return winPromise.then((function(win) { var sameDomain = isSameDomain(win); var frame = getFrameForWindow(win); if (!sameDomain) throw new Error("Can not set name for cross-domain window: " + name); assertSameDomain(win).name = name; frame && frame.setAttribute("name", name); windowNamePromise = promise_ZalgoPromise.resolve(name); })); } }; } var window_ProxyWindow = function() { function ProxyWindow(_ref2) { var send = _ref2.send, win = _ref2.win, serializedWindow = _ref2.serializedWindow; this.id = void 0; this.isProxyWindow = !0; this.serializedWindow = void 0; this.actualWindow = void 0; this.actualWindowPromise = void 0; this.send = void 0; this.name = void 0; this.actualWindowPromise = new promise_ZalgoPromise; this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send: send }); globalStore("idToProxyWindow").set(this.getID(), this); win && this.setWindow(win, { send: send }); } var _proto = ProxyWindow.prototype; _proto.getID = function() { return this.serializedWindow.id; }; _proto.getType = function() { return this.serializedWindow.getType(); }; _proto.isPopup = function() { return this.getType().then((function(type) { return "popup" === type; })); }; _proto.setLocation = function(href, opts) { var _this = this; return this.serializedWindow.setLocation(href, opts).then((function() { return _this; })); }; _proto.getName = function() { return this.serializedWindow.getName(); }; _proto.setName = function(name) { var _this2 = this; return this.serializedWindow.setName(name).then((function() { return _this2; })); }; _proto.close = function() { var _this3 = this; return this.serializedWindow.close().then((function() { return _this3; })); }; _proto.focus = function() { var _this4 = this; var isPopupPromise = this.isPopup(); var getNamePromise = this.getName(); var reopenPromise = promise_ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then((function(_ref3) { var name = _ref3.name; _ref3.isPopup && name && window.open("", name, "noopener"); })); var focusPromise = this.serializedWindow.focus(); return promise_ZalgoPromise.all([ reopenPromise, focusPromise ]).then((function() { return _this4; })); }; _proto.isClosed = function() { return this.serializedWindow.isClosed(); }; _proto.getWindow = function() { return this.actualWindow; }; _proto.setWindow = function(win, _ref4) { var send = _ref4.send; this.actualWindow = win; this.actualWindowPromise.resolve(this.actualWindow); this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send: send, id: this.getID() }); windowStore("winToProxyWindow").set(win, this); }; _proto.awaitWindow = function() { return this.actualWindowPromise; }; _proto.matchWindow = function(win, _ref5) { var _this5 = this; var send = _ref5.send; return promise_ZalgoPromise.try((function() { return _this5.actualWindow ? win === _this5.actualWindow : promise_ZalgoPromise.hash({ proxyInstanceID: _this5.getInstanceID(), knownWindowInstanceID: getWindowInstanceID(win, { send: send }) }).then((function(_ref6) { var match = _ref6.proxyInstanceID === _ref6.knownWindowInstanceID; match && _this5.setWindow(win, { send: send }); return match; })); })); }; _proto.unwrap = function() { return this.actualWindow || this; }; _proto.getInstanceID = function() { return this.serializedWindow.getInstanceID(); }; _proto.shouldClean = function() { return Boolean(this.actualWindow && isWindowClosed(this.actualWindow)); }; _proto.serialize = function() { return this.serializedWindow; }; ProxyWindow.unwrap = function(win) { return ProxyWindow.isProxyWindow(win) ? win.unwrap() : win; }; ProxyWindow.serialize = function(win, _ref7) { var send = _ref7.send; cleanupProxyWindows(); return ProxyWindow.toProxyWindow(win, { send: send }).serialize(); }; ProxyWindow.deserialize = function(serializedWindow, _ref8) { var send = _ref8.send; cleanupProxyWindows(); return globalStore("idToProxyWindow").get(serializedWindow.id) || new ProxyWindow({ serializedWindow: serializedWindow, send: send }); }; ProxyWindow.isProxyWindow = function(obj) { return Boolean(obj && !isWindow(obj) && obj.isProxyWindow); }; ProxyWindow.toProxyWindow = function(win, _ref9) { var send = _ref9.send; cleanupProxyWindows(); if (ProxyWindow.isProxyWindow(win)) return win; var actualWindow = win; return windowStore("winToProxyWindow").get(actualWindow) || new ProxyWindow({ win: actualWindow, send: send }); }; return ProxyWindow; }(); function addMethod(id, val, name, source, domain) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); if (window_ProxyWindow.isProxyWindow(source)) proxyWindowMethods.set(id, { val: val, name: name, domain: domain, source: source }); else { proxyWindowMethods.del(id); methodStore.getOrSet(source, (function() { return {}; }))[id] = { domain: domain, name: name, val: val, source: source }; } } function lookupMethod(source, id) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); return methodStore.getOrSet(source, (function() { return {}; }))[id] || proxyWindowMethods.get(id); } function function_serializeFunction(destination, domain, val, key, _ref3) { on = (_ref = { on: _ref3.on, send: _ref3.send }).on, send = _ref.send, globalStore("builtinListeners").getOrSet("functionCalls", (function() { return on("postrobot_method", { domain: "*" }, (function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; var id = data.id, name = data.name; var meth = lookupMethod(source, id); if (!meth) throw new Error("Could not find method '" + name + "' with id: " + data.id + " in " + getDomain(window)); var methodSource = meth.source, domain = meth.domain, val = meth.val; return promise_ZalgoPromise.try((function() { if (!matchDomain(domain, origin)) throw new Error("Method '" + data.name + "' domain " + JSON.stringify(util_isRegex(meth.domain) ? meth.domain.source : meth.domain) + " does not match origin " + origin + " in " + getDomain(window)); if (window_ProxyWindow.isProxyWindow(methodSource)) return methodSource.matchWindow(source, { send: send }).then((function(match) { if (!match) throw new Error("Method call '" + data.name + "' failed - proxy window does not match source in " + getDomain(window)); })); })).then((function() { return val.apply({ source: source, origin: origin }, data.args); }), (function(err) { return promise_ZalgoPromise.try((function() { if (val.onError) return val.onError(err); })).then((function() { err.stack && (err.stack = "Remote call to " + name + "(" + function(args) { void 0 === args && (args = []); return arrayFrom(args).map((function(arg) { return "string" == typeof arg ? "'" + arg + "'" : void 0 === arg ? "undefined" : null === arg ? "null" : "boolean" == typeof arg ? arg.toString() : Array.isArray(arg) ? "[ ... ]" : "object" == typeof arg ? "{ ... }" : "function" == typeof arg ? "() => { ... }" : "<" + typeof arg + ">"; })).join(", "); }(data.args) + ") failed\n\n" + err.stack); throw err; })); })).then((function(result) { return { result: result, id: id, name: name }; })); })); })); var _ref, on, send; var id = val.__id__ || uniqueID(); destination = window_ProxyWindow.unwrap(destination); var name = val.__name__ || val.name || key; "string" == typeof name && "function" == typeof name.indexOf && 0 === name.indexOf("anonymous::") && (name = name.replace("anonymous::", key + "::")); if (window_ProxyWindow.isProxyWindow(destination)) { addMethod(id, val, name, destination, domain); destination.awaitWindow().then((function(win) { addMethod(id, val, name, win, domain); })); } else addMethod(id, val, name, destination, domain); return serializeType("cross_domain_function", { id: id, name: name }); } function serializeMessage(destination, domain, obj, _ref) { var _serialize; var on = _ref.on, send = _ref.send; return function(obj, serializers) { void 0 === serializers && (serializers = defaultSerializers); var result = JSON.stringify(obj, (function(key) { var val = this[key]; if (isSerializedType(this)) return val; var type = determineType(val); if (!type) return val; var serializer = serializers[type] || SERIALIZER[type]; return serializer ? serializer(val, key) : val; })); return void 0 === result ? "undefined" : result; }(obj, ((_serialize = {}).promise = function(val, key) { return function(destination, domain, val, key, _ref) { return serializeType("cross_domain_zalgo_promise", { then: function_serializeFunction(destination, domain, (function(resolve, reject) { return val.then(resolve, reject); }), key, { on: _ref.on, send: _ref.send }) }); }(destination, domain, val, key, { on: on, send: send }); }, _serialize.function = function(val, key) { return function_serializeFunction(destination, domain, val, key, { on: on, send: send }); }, _serialize.object = function(val) { return isWindow(val) || window_ProxyWindow.isProxyWindow(val) ? serializeType("cross_domain_window", window_ProxyWindow.serialize(val, { send: send })) : val; }, _serialize)); } function deserializeMessage(source, origin, message, _ref2) { var _deserialize; var send = _ref2.send; return function(str, deserializers) { void 0 === deserializers && (deserializers = defaultDeserializers); if ("undefined" !== str) return JSON.parse(str, (function(key, val) { if (isSerializedType(this)) return val; var type; var value; if (isSerializedType(val)) { type = val.__type__; value = val.__val__; } else { type = determineType(val); value = val; } if (!type) return value; var deserializer = deserializers[type] || DESERIALIZER[type]; return deserializer ? deserializer(value, key) : value; })); }(message, ((_deserialize = {}).cross_domain_zalgo_promise = function(serializedPromise) { return function(source, origin, _ref2) { return new promise_ZalgoPromise(_ref2.then); }(0, 0, serializedPromise); }, _deserialize.cross_domain_function = function(serializedFunction) { return function(source, origin, _ref4, _ref5) { var id = _ref4.id, name = _ref4.name; var send = _ref5.send; var getDeserializedFunction = function(opts) { void 0 === opts && (opts = {}); function crossDomainFunctionWrapper() { var _arguments = arguments; return window_ProxyWindow.toProxyWindow(source, { send: send }).awaitWindow().then((function(win) { var meth = lookupMethod(win, id); if (meth && meth.val !== crossDomainFunctionWrapper) return meth.val.apply({ source: window, origin: getDomain() }, _arguments); var _args = [].slice.call(_arguments); return opts.fireAndForget ? send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !0 }) : send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !1 }).then((function(res) { return res.data.result; })); })).catch((function(err) { throw err; })); } crossDomainFunctionWrapper.__name__ = name; crossDomainFunctionWrapper.__origin__ = origin; crossDomainFunctionWrapper.__source__ = source; crossDomainFunctionWrapper.__id__ = id; crossDomainFunctionWrapper.origin = origin; return crossDomainFunctionWrapper; }; var crossDomainFunctionWrapper = getDeserializedFunction(); crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: !0 }); return crossDomainFunctionWrapper; }(source, origin, serializedFunction, { send: send }); }, _deserialize.cross_domain_window = function(serializedWindow) { return window_ProxyWindow.deserialize(serializedWindow, { send: send }); }, _deserialize)); } var SEND_MESSAGE_STRATEGIES = {}; SEND_MESSAGE_STRATEGIES.postrobot_post_message = function(win, serializedMessage, domain) { 0 === domain.indexOf("file:") && (domain = "*"); win.postMessage(serializedMessage, domain); }; SEND_MESSAGE_STRATEGIES.postrobot_global = function(win, serializedMessage) { if (!function(win) { return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent; }(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser"); if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows"); if (!1 !== function(win1, win2) { var top1 = getTop(win1) || win1; var top2 = getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = getAllFramesInWindow(win1); var allFrames2 = getAllFramesInWindow(win2); if (anyMatch(allFrames1, allFrames2)) return !0; var opener1 = getOpener(top1); var opener2 = getOpener(top2); return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), !1; }(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); var foreignGlobal = global_getGlobal(win); if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window"); foreignGlobal.receiveMessage({ source: window, origin: getDomain(), data: serializedMessage }); }; function send_sendMessage(win, domain, message, _ref2) { var on = _ref2.on, send = _ref2.send; return promise_ZalgoPromise.try((function() { var domainBuffer = windowStore().getOrSet(win, (function() { return {}; })); domainBuffer.buffer = domainBuffer.buffer || []; domainBuffer.buffer.push(message); domainBuffer.flush = domainBuffer.flush || promise_ZalgoPromise.flush().then((function() { if (isWindowClosed(win)) throw new Error("Window is closed"); var serializedMessage = serializeMessage(win, domain, ((_ref = {}).__post_robot_10_0_46__ = domainBuffer.buffer || [], _ref), { on: on, send: send }); var _ref; delete domainBuffer.buffer; var strategies = Object.keys(SEND_MESSAGE_STRATEGIES); var errors = []; for (var _i2 = 0; _i2 < strategies.length; _i2++) { var strategyName = strategies[_i2]; try { SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain); } catch (err) { errors.push(err); } } if (errors.length === strategies.length) throw new Error("All post-robot messaging strategies failed:\n\n" + errors.map((function(err, i) { return i + ". " + stringifyError(err); })).join("\n\n")); })); return domainBuffer.flush.then((function() { delete domainBuffer.flush; })); })).then(src_util_noop); } function getResponseListener(hash) { return globalStore("responseListeners").get(hash); } function deleteResponseListener(hash) { globalStore("responseListeners").del(hash); } function isResponseListenerErrored(hash) { return globalStore("erroredResponseListeners").has(hash); } function getRequestListener(_ref) { var name = _ref.name, win = _ref.win, domain = _ref.domain; var requestListeners = windowStore("requestListeners"); "*" === win && (win = null); "*" === domain && (domain = null); if (!name) throw new Error("Name required to get request listener"); for (var _i4 = 0, _ref3 = [ win, getWildcard() ]; _i4 < _ref3.length; _i4++) { var winQualifier = _ref3[_i4]; if (winQualifier) { var nameListeners = requestListeners.get(winQualifier); if (nameListeners) { var domainListeners = nameListeners[name]; if (domainListeners) { if (domain && "string" == typeof domain) { if (domainListeners[domain]) return domainListeners[domain]; if (domainListeners.__domain_regex__) for (var _i6 = 0, _domainListeners$__DO2 = domainListeners.__domain_regex__; _i6 < _domainListeners$__DO2.length; _i6++) { var _domainListeners$__DO3 = _domainListeners$__DO2[_i6], listener = _domainListeners$__DO3.listener; if (matchDomain(_domainListeners$__DO3.regex, domain)) return listener; } } if (domainListeners["*"]) return domainListeners["*"]; } } } } } function handleRequest(source, origin, message, _ref) { var on = _ref.on, send = _ref.send; var options = getRequestListener({ name: message.name, win: source, domain: origin }); var logName = "postrobot_method" === message.name && message.data && "string" == typeof message.data.name ? message.data.name + "()" : message.name; function sendResponse(ack, data, error) { return promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_response", hash: message.hash, name: message.name, ack: ack, data: data, error: error }, { on: on, send: send }); } catch (err) { throw new Error("Send response message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })); } return promise_ZalgoPromise.all([ promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_ack", hash: message.hash, name: message.name }, { on: on, send: send }); } catch (err) { throw new Error("Send ack message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })), promise_ZalgoPromise.try((function() { if (!options) throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); return options.handler({ source: source, origin: origin, data: message.data }); })).then((function(data) { return sendResponse("success", data); }), (function(error) { return sendResponse("error", null, error); })) ]).then(src_util_noop).catch((function(err) { if (options && options.handleError) return options.handleError(err); throw err; })); } function handleAck(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); try { if (!matchDomain(options.domain, origin)) throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString()); if (source !== options.win) throw new Error("Ack source does not match registered window"); } catch (err) { options.promise.reject(err); } options.ack = !0; } } function handleResponse(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); if (!matchDomain(options.domain, origin)) throw new Error("Response origin " + origin + " does not match domain " + (pattern = options.domain, Array.isArray(pattern) ? "(" + pattern.join(" | ") + ")" : isRegex(pattern) ? "RegExp(" + pattern.toString() + ")" : pattern.toString())); var pattern; if (source !== options.win) throw new Error("Response source does not match registered window"); deleteResponseListener(message.hash); "error" === message.ack ? options.promise.reject(message.error) : "success" === message.ack && options.promise.resolve({ source: source, origin: origin, data: message.data }); } } function receive_receiveMessage(event, _ref2) { var on = _ref2.on, send = _ref2.send; var receivedMessages = globalStore("receivedMessages"); try { if (!window || window.closed || !event.source) return; } catch (err) { return; } var source = event.source, origin = event.origin; var messages = function(message, source, origin, _ref) { var on = _ref.on, send = _ref.send; var parsedMessage; try { parsedMessage = deserializeMessage(source, origin, message, { on: on, send: send }); } catch (err) { return; } if (parsedMessage && "object" == typeof parsedMessage && null !== parsedMessage) { var parseMessages = parsedMessage.__post_robot_10_0_46__; if (Array.isArray(parseMessages)) return parseMessages; } }(event.data, source, origin, { on: on, send: send }); if (messages) { markWindowKnown(source); for (var _i2 = 0; _i2 < messages.length; _i2++) { var message = messages[_i2]; if (receivedMessages.has(message.id)) return; receivedMessages.set(message.id, !0); if (isWindowClosed(source) && !message.fireAndForget) return; 0 === message.origin.indexOf("file:") && (origin = "file://"); try { "postrobot_message_request" === message.type ? handleRequest(source, origin, message, { on: on, send: send }) : "postrobot_message_response" === message.type ? handleResponse(source, origin, message) : "postrobot_message_ack" === message.type && handleAck(source, origin, message); } catch (err) { setTimeout((function() { throw err; }), 0); } } } } function on_on(name, options, handler) { if (!name) throw new Error("Expected name"); if ("function" == typeof (options = options || {})) { handler = options; options = {}; } if (!handler) throw new Error("Expected handler"); var requestListener = function addRequestListener(_ref4, listener) { var name = _ref4.name, winCandidate = _ref4.win, domain = _ref4.domain; var requestListeners = windowStore("requestListeners"); if (!name || "string" != typeof name) throw new Error("Name required to add request listener"); if (winCandidate && "*" !== winCandidate && window_ProxyWindow.isProxyWindow(winCandidate)) { var requestListenerPromise = winCandidate.awaitWindow().then((function(actualWin) { return addRequestListener({ name: name, win: actualWin, domain: domain }, listener); })); return { cancel: function() { requestListenerPromise.then((function(requestListener) { return requestListener.cancel(); }), src_util_noop); } }; } var win = winCandidate; if (Array.isArray(win)) { var listenersCollection = []; for (var _i8 = 0, _win2 = win; _i8 < _win2.length; _i8++) listenersCollection.push(addRequestListener({ name: name, domain: domain, win: _win2[_i8] }, listener)); return { cancel: function() { for (var _i10 = 0; _i10 < listenersCollection.length; _i10++) listenersCollection[_i10].cancel(); } }; } if (Array.isArray(domain)) { var _listenersCollection = []; for (var _i12 = 0, _domain2 = domain; _i12 < _domain2.length; _i12++) _listenersCollection.push(addRequestListener({ name: name, win: win, domain: _domain2[_i12] }, listener)); return { cancel: function() { for (var _i14 = 0; _i14 < _listenersCollection.length; _i14++) _listenersCollection[_i14].cancel(); } }; } var existingListener = getRequestListener({ name: name, win: win, domain: domain }); win && "*" !== win || (win = getWildcard()); var strDomain = (domain = domain || "*").toString(); if (existingListener) throw win && domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : win ? new Error("Request listener already exists for " + name + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString()) : new Error("Request listener already exists for " + name); var winNameListeners = requestListeners.getOrSet(win, (function() { return {}; })); var winNameDomainListeners = util_getOrSet(winNameListeners, name, (function() { return {}; })); var winNameDomainRegexListeners; var winNameDomainRegexListener; util_isRegex(domain) ? (winNameDomainRegexListeners = util_getOrSet(winNameDomainListeners, "__domain_regex__", (function() { return []; }))).push(winNameDomainRegexListener = { regex: domain, listener: listener }) : winNameDomainListeners[strDomain] = listener; return { cancel: function() { delete winNameDomainListeners[strDomain]; if (winNameDomainRegexListener) { winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1)); winNameDomainRegexListeners.length || delete winNameDomainListeners.__domain_regex__; } Object.keys(winNameDomainListeners).length || delete winNameListeners[name]; win && !Object.keys(winNameListeners).length && requestListeners.del(win); } }; }({ name: name, win: options.window, domain: options.domain || "*" }, { handler: handler || options.handler, handleError: options.errorHandler || function(err) { throw err; } }); return { cancel: function() { requestListener.cancel(); } }; } var send_send = function send(winOrProxyWin, name, data, options) { var domainMatcher = (options = options || {}).domain || "*"; var responseTimeout = options.timeout || -1; var childTimeout = options.timeout || 5e3; var fireAndForget = options.fireAndForget || !1; return window_ProxyWindow.toProxyWindow(winOrProxyWin, { send: send }).awaitWindow().then((function(win) { return promise_ZalgoPromise.try((function() { !function(name, win, domain) { if (!name) throw new Error("Expected name"); if (domain && "string" != typeof domain && !Array.isArray(domain) && !util_isRegex(domain)) throw new TypeError("Can not send " + name + ". Expected domain " + JSON.stringify(domain) + " to be a string, array, or regex"); if (isWindowClosed(win)) throw new Error("Can not send " + name + ". Target window is closed"); }(name, win, domainMatcher); if (function(parent, child) { var actualParent = getAncestor(child); if (actualParent) return actualParent === parent; if (child === parent) return !1; if (getTop(child) === child) return !1; for (var _i15 = 0, _getFrames8 = getFrames(parent); _i15 < _getFrames8.length; _i15++) if (_getFrames8[_i15] === child) return !0; return !1; }(window, win)) return function(win, timeout, name) { void 0 === timeout && (timeout = 5e3); void 0 === name && (name = "Window"); var promise = function(win) { return windowStore("helloPromises").getOrSet(win, (function() { return new promise_ZalgoPromise; })); }(win); -1 !== timeout && (promise = promise.timeout(timeout, new Error(name + " did not load after " + timeout + "ms"))); return promise; }(win, childTimeout); })).then((function(_temp) { return function(win, targetDomain, actualDomain, _ref) { var send = _ref.send; return promise_ZalgoPromise.try((function() { return "string" == typeof targetDomain ? targetDomain : promise_ZalgoPromise.try((function() { return actualDomain || sayHello(win, { send: send }).then((function(_ref2) { return _ref2.domain; })); })).then((function(normalizedDomain) { if (!matchDomain(targetDomain, targetDomain)) throw new Error("Domain " + stringify(targetDomain) + " does not match " + stringify(targetDomain)); return normalizedDomain; })); })); }(win, domainMatcher, (void 0 === _temp ? {} : _temp).domain, { send: send }); })).then((function(targetDomain) { var domain = targetDomain; var logName = "postrobot_method" === name && data && "string" == typeof data.name ? data.name + "()" : name; var promise = new promise_ZalgoPromise; var hash = name + "_" + uniqueID(); if (!fireAndForget) { var responseListener = { name: name, win: win, domain: domain, promise: promise }; !function(hash, listener) { globalStore("responseListeners").set(hash, listener); }(hash, responseListener); var reqPromises = windowStore("requestPromises").getOrSet(win, (function() { return []; })); reqPromises.push(promise); promise.catch((function() { !function(hash) { globalStore("erroredResponseListeners").set(hash, !0); }(hash); deleteResponseListener(hash); })); var totalAckTimeout = function(win) { return windowStore("knownWindows").get(win, !1); }(win) ? 1e4 : 2e3; var totalResTimeout = responseTimeout; var ackTimeout = totalAckTimeout; var resTimeout = totalResTimeout; var interval = safeInterval((function() { if (isWindowClosed(win)) return promise.reject(new Error("Window closed for " + name + " before " + (responseListener.ack ? "response" : "ack"))); if (responseListener.cancelled) return promise.reject(new Error("Response listener was cancelled for " + name)); ackTimeout = Math.max(ackTimeout - 500, 0); -1 !== resTimeout && (resTimeout = Math.max(resTimeout - 500, 0)); return responseListener.ack || 0 !== ackTimeout ? 0 === resTimeout ? promise.reject(new Error("No response for postMessage " + logName + " in " + getDomain() + " in " + totalResTimeout + "ms")) : void 0 : promise.reject(new Error("No ack for postMessage " + logName + " in " + getDomain() + " in " + totalAckTimeout + "ms")); }), 500); promise.finally((function() { interval.cancel(); reqPromises.splice(reqPromises.indexOf(promise, 1)); })).catch(src_util_noop); } return send_sendMessage(win, domain, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_request", hash: hash, name: name, data: data, fireAndForget: fireAndForget }, { on: on_on, send: send }).then((function() { return fireAndForget ? promise.resolve() : promise; }), (function(err) { throw new Error("Send request message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); })); })); })); }; function setup_toProxyWindow(win) { return window_ProxyWindow.toProxyWindow(win, { send: send_send }); } function src_util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function utils_getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function utils_getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return utils_getActualProtocol(win); } function utils_isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === utils_getProtocol(win); } function src_utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function utils_getOpener(win) { void 0 === win && (win = window); if (win && !src_utils_getParent(win)) try { return win.opener; } catch (err) {} } function utils_canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function utils_getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = utils_getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = src_utils_getParent(win); return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function utils_getDomain(win) { void 0 === win && (win = window); var domain = utils_getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function utils_isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === utils_getProtocol(win); }(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; if (utils_getDomain(window) === utils_getDomain(win)) return !0; } catch (err) {} return !1; } function utils_assertSameDomain(win) { if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function utils_isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = src_utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function utils_getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function utils_getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function utils_getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (src_utils_getParent(win) === win) return win; try { if (utils_isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (utils_isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (src_utils_getParent(frame) === frame) return frame; } } function utils_getAllFramesInWindow(win) { var top = utils_getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(utils_getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); return result; } var utils_iframeWindows = []; var utils_iframeFrames = []; function utils_isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || "Call was rejected by callee.\r\n" !== err.message; } if (allowMock && utils_isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(utils_iframeWindows, win); if (-1 !== iframeIndex) { var frame = utils_iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function utils_getFrameByName(win, name) { var winFrames = utils_getFrames(win); for (var _i9 = 0; _i9 < winFrames.length; _i9++) { var childFrame = winFrames[_i9]; try { if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; } catch (err) {} } try { if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; } catch (err) {} try { if (-1 !== winFrames.indexOf(win[name])) return win[name]; } catch (err) {} } function utils_getAncestor(win) { void 0 === win && (win = window); return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; } function utils_anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function utils_getDistanceFromTop(win) { void 0 === win && (win = window); var distance = 0; var parent = win; for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); return distance; } function utils_matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (src_util_isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return src_util_isRegex(pattern) ? src_util_isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { return utils_matchDomain(subpattern, origin); }))); } function utils_getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); } function utils_onCloseWindow(win, callback, delay, maxtime) { void 0 === delay && (delay = 1e3); void 0 === maxtime && (maxtime = 1 / 0); var timeout; !function check() { if (utils_isWindowClosed(win)) { timeout && clearTimeout(timeout); return callback(); } if (maxtime <= 0) clearTimeout(timeout); else { maxtime -= delay; timeout = setTimeout(check, delay); } }(); return { cancel: function() { timeout && clearTimeout(timeout); } }; } function utils_isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function lib_global_getGlobal(win) { if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); return win.__zoid_9_0_87__; } function tryGlobal(win, handler) { try { return handler(lib_global_getGlobal(win)); } catch (err) {} } function getProxyObject(obj) { return { get: function() { var _this = this; return promise_ZalgoPromise.try((function() { if (_this.source && _this.source !== window) throw new Error("Can not call get on proxy object from a remote window"); return obj; })); } }; } function basicSerialize(data) { return base64encode(JSON.stringify(data)); } function getUIDRefStore(win) { var global = lib_global_getGlobal(win); global.references = global.references || {}; return global.references; } function crossDomainSerialize(_ref) { var data = _ref.data, metaData = _ref.metaData, sender = _ref.sender, receiver = _ref.receiver, _ref$passByReference = _ref.passByReference, passByReference = void 0 !== _ref$passByReference && _ref$passByReference, _ref$basic = _ref.basic, basic = void 0 !== _ref$basic && _ref$basic; var proxyWin = setup_toProxyWindow(receiver.win); var serializedMessage = basic ? JSON.stringify(data) : serializeMessage(proxyWin, receiver.domain, data, { on: on_on, send: send_send }); var reference = passByReference ? function(val) { var uid = uniqueID(); getUIDRefStore(window)[uid] = val; return { type: "uid", uid: uid }; }(serializedMessage) : { type: "raw", val: serializedMessage }; return { serializedData: basicSerialize({ sender: { domain: sender.domain }, metaData: metaData, reference: reference }), cleanReference: function() { win = window, "uid" === (ref = reference).type && delete getUIDRefStore(win)[ref.uid]; var win, ref; } }; } function crossDomainDeserialize(_ref2) { var sender = _ref2.sender, _ref2$basic = _ref2.basic, basic = void 0 !== _ref2$basic && _ref2$basic; var message = function(serializedData) { return JSON.parse(function(str) { if ("function" == typeof atob) return decodeURIComponent([].map.call(atob(str), (function(c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); })).join("")); if ("undefined" != typeof Buffer) return Buffer.from(str, "base64").toString("utf8"); throw new Error("Can not find window.atob or Buffer"); }(serializedData)); }(_ref2.data); var reference = message.reference, metaData = message.metaData; var win; win = "function" == typeof sender.win ? sender.win({ metaData: metaData }) : sender.win; var domain; domain = "function" == typeof sender.domain ? sender.domain({ metaData: metaData }) : "string" == typeof sender.domain ? sender.domain : message.sender.domain; var serializedData = function(win, ref) { if ("raw" === ref.type) return ref.val; if ("uid" === ref.type) return getUIDRefStore(win)[ref.uid]; throw new Error("Unsupported ref type: " + ref.type); }(win, reference); return { data: basic ? JSON.parse(serializedData) : function(source, origin, message) { return deserializeMessage(source, origin, message, { on: on_on, send: send_send }); }(win, domain, serializedData), metaData: metaData, sender: { win: win, domain: domain }, reference: reference }; } var PROP_TYPE = { STRING: "string", OBJECT: "object", FUNCTION: "function", BOOLEAN: "boolean", NUMBER: "number", ARRAY: "array" }; var PROP_SERIALIZATION = { JSON: "json", DOTIFY: "dotify", BASE64: "base64" }; var CONTEXT = { IFRAME: "iframe", POPUP: "popup" }; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", DISPLAY: "zoid-display", ERROR: "zoid-error", CLOSE: "zoid-close", DESTROY: "zoid-destroy", PROPS: "zoid-props", RESIZE: "zoid-resize", FOCUS: "zoid-focus" }; function buildChildWindowName(_ref) { return "__zoid__" + _ref.name + "__" + _ref.serializedPayload + "__"; } function parseWindowName(windowName) { if (!windowName) throw new Error("No window name"); var _windowName$split = windowName.split("__"), zoidcomp = _windowName$split[1], name = _windowName$split[2], serializedInitialPayload = _windowName$split[3]; if ("zoid" !== zoidcomp) throw new Error("Window not rendered by zoid - got " + zoidcomp); if (!name) throw new Error("Expected component name"); if (!serializedInitialPayload) throw new Error("Expected serialized payload ref"); return { name: name, serializedInitialPayload: serializedInitialPayload }; } var parseInitialParentPayload = memoize((function(windowName) { var _crossDomainDeseriali = crossDomainDeserialize({ data: parseWindowName(windowName).serializedInitialPayload, sender: { win: function(_ref2) { return function(windowRef) { if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { void 0 === n && (n = 1); var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; parent = src_utils_getParent(parent); } return parent; }(win, utils_getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; var ancestor = utils_getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); if (win) return { v: win }; } } }(); if ("object" == typeof _ret) return _ret.v; } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { var frame = utils_getFrameByName(win, name); if (frame) return frame; for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } }(utils_getTop(win) || win, name); }(assertExists("ancestor", utils_getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); } } }); return { parent: _crossDomainDeseriali.sender, payload: _crossDomainDeseriali.data, reference: _crossDomainDeseriali.reference }; })); function getInitialParentPayload() { return parseInitialParentPayload(window.name); } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); if (targetWindow === src_utils_getParent(currentWindow)) return { type: "parent", distance: utils_getDistanceFromTop(targetWindow) }; if (targetWindow === utils_getOpener(currentWindow)) return { type: "opener" }; if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { var windowName = utils_assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName }; } var win; } function normalizeChildProp(propsDef, props, key, value, helpers) { if (!propsDef.hasOwnProperty(key)) return value; var prop = propsDef[key]; return "function" == typeof prop.childDecorate ? prop.childDecorate({ value: value, uid: helpers.uid, tag: helpers.tag, close: helpers.close, focus: helpers.focus, onError: helpers.onError, onProps: helpers.onProps, resize: helpers.resize, getParent: helpers.getParent, getParentDomain: helpers.getParentDomain, show: helpers.show, hide: helpers.hide, export: helpers.export, getSiblings: helpers.getSiblings }) : value; } function child_focus() { return promise_ZalgoPromise.try((function() { window.focus(); })); } function child_destroy() { return promise_ZalgoPromise.try((function() { window.close(); })); } var props_defaultNoop = function() { return src_util_noop; }; var props_decorateOnce = function(_ref) { return once(_ref.value); }; function eachProp(props, propsDef, handler) { for (var _i2 = 0, _Object$keys2 = Object.keys(_extends({}, props, propsDef)); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; handler(key, propsDef[key], props[key]); } } function serializeProps(propsDef, props, method) { var params = {}; return promise_ZalgoPromise.all(function(props, propsDef, handler) { var results = []; eachProp(props, propsDef, (function(key, propDef, value) { var result = function(key, propDef, value) { return promise_ZalgoPromise.resolve().then((function() { var _METHOD$GET$METHOD$PO, _METHOD$GET$METHOD$PO2; if (null != value && propDef) { var getParam = (_METHOD$GET$METHOD$PO = {}, _METHOD$GET$METHOD$PO.get = propDef.queryParam, _METHOD$GET$METHOD$PO.post = propDef.bodyParam, _METHOD$GET$METHOD$PO)[method]; var getValue = (_METHOD$GET$METHOD$PO2 = {}, _METHOD$GET$METHOD$PO2.get = propDef.queryValue, _METHOD$GET$METHOD$PO2.post = propDef.bodyValue, _METHOD$GET$METHOD$PO2)[method]; if (getParam) return promise_ZalgoPromise.hash({ finalParam: promise_ZalgoPromise.try((function() { return "function" == typeof getParam ? getParam({ value: value }) : "string" == typeof getParam ? getParam : key; })), finalValue: promise_ZalgoPromise.try((function() { return "function" == typeof getValue && isDefined(value) ? getValue({ value: value }) : value; })) }).then((function(_ref) { var finalParam = _ref.finalParam, finalValue = _ref.finalValue; var result; if ("boolean" == typeof finalValue) result = finalValue.toString(); else if ("string" == typeof finalValue) result = finalValue.toString(); else if ("object" == typeof finalValue && null !== finalValue) { if (propDef.serialization === PROP_SERIALIZATION.JSON) result = JSON.stringify(finalValue); else if (propDef.serialization === PROP_SERIALIZATION.BASE64) result = base64encode(JSON.stringify(finalValue)); else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) { result = function dotify(obj, prefix, newobj) { void 0 === prefix && (prefix = ""); void 0 === newobj && (newobj = {}); prefix = prefix ? prefix + "." : prefix; for (var key in obj) obj.hasOwnProperty(key) && null != obj[key] && "function" != typeof obj[key] && (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every((function(val) { return "object" != typeof val; })) ? newobj["" + prefix + key + "[]"] = obj[key].join(",") : obj[key] && "object" == typeof obj[key] ? newobj = dotify(obj[key], "" + prefix + key, newobj) : newobj["" + prefix + key] = obj[key].toString()); return newobj; }(finalValue, key); for (var _i2 = 0, _Object$keys2 = Object.keys(result); _i2 < _Object$keys2.length; _i2++) { var dotkey = _Object$keys2[_i2]; params[dotkey] = result[dotkey]; } return; } } else "number" == typeof finalValue && (result = finalValue.toString()); params[finalParam] = result; })); } })); }(key, propDef, value); results.push(result); })); return results; }(props, propsDef)).then((function() { return params; })); } function parentComponent(_ref) { var uid = _ref.uid, options = _ref.options, _ref$overrides = _ref.overrides, overrides = void 0 === _ref$overrides ? {} : _ref$overrides, _ref$parentWin = _ref.parentWin, parentWin = void 0 === _ref$parentWin ? window : _ref$parentWin; var propsDef = options.propsDef, containerTemplate = options.containerTemplate, prerenderTemplate = options.prerenderTemplate, tag = options.tag, name = options.name, attributes = options.attributes, dimensions = options.dimensions, autoResize = options.autoResize, url = options.url, domainMatch = options.domain, xports = options.exports; var initPromise = new promise_ZalgoPromise; var handledErrors = []; var clean = cleanup(); var state = {}; var inputProps = {}; var internalState = { visible: !0 }; var event = overrides.event ? overrides.event : (triggered = {}, handlers = {}, emitter = { on: function(eventName, handler) { var handlerList = handlers[eventName] = handlers[eventName] || []; handlerList.push(handler); var cancelled = !1; return { cancel: function() { if (!cancelled) { cancelled = !0; handlerList.splice(handlerList.indexOf(handler), 1); } } }; }, once: function(eventName, handler) { var listener = emitter.on(eventName, (function() { listener.cancel(); handler(); })); return listener; }, trigger: function(eventName) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3]; var handlerList = handlers[eventName]; var promises = []; if (handlerList) { var _loop = function(_i2) { var handler = handlerList[_i2]; promises.push(promise_ZalgoPromise.try((function() { return handler.apply(void 0, args); }))); }; for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(_i2); } return promise_ZalgoPromise.all(promises).then(src_util_noop); }, triggerOnce: function(eventName) { if (triggered[eventName]) return promise_ZalgoPromise.resolve(); triggered[eventName] = !0; for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) args[_key4 - 1] = arguments[_key4]; return emitter.trigger.apply(emitter, [ eventName ].concat(args)); }, reset: function() { handlers = {}; } }); var triggered, handlers, emitter; var props = overrides.props ? overrides.props : {}; var currentProxyWin; var currentProxyContainer; var childComponent; var currentChildDomain; var currentContainer; var onErrorOverride = overrides.onError; var getProxyContainerOverride = overrides.getProxyContainer; var showOverride = overrides.show; var hideOverride = overrides.hide; var closeOverride = overrides.close; var renderContainerOverride = overrides.renderContainer; var getProxyWindowOverride = overrides.getProxyWindow; var setProxyWinOverride = overrides.setProxyWin; var openFrameOverride = overrides.openFrame; var openPrerenderFrameOverride = overrides.openPrerenderFrame; var prerenderOverride = overrides.prerender; var openOverride = overrides.open; var openPrerenderOverride = overrides.openPrerender; var watchForUnloadOverride = overrides.watchForUnload; var getInternalStateOverride = overrides.getInternalState; var setInternalStateOverride = overrides.setInternalState; var resolveInitPromise = function() { return promise_ZalgoPromise.try((function() { return overrides.resolveInitPromise ? overrides.resolveInitPromise() : initPromise.resolve(); })); }; var rejectInitPromise = function(err) { return promise_ZalgoPromise.try((function() { return overrides.rejectInitPromise ? overrides.rejectInitPromise(err) : initPromise.reject(err); })); }; var getPropsForChild = function(initialChildDomain) { var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; var getInternalState = function() { return promise_ZalgoPromise.try((function() { return getInternalStateOverride ? getInternalStateOverride() : internalState; })); }; var setInternalState = function(newInternalState) { return promise_ZalgoPromise.try((function() { return setInternalStateOverride ? setInternalStateOverride(newInternalState) : internalState = _extends({}, internalState, newInternalState); })); }; var getProxyWindow = function() { return getProxyWindowOverride ? getProxyWindowOverride() : promise_ZalgoPromise.try((function() { var windowProp = props.window; if (windowProp) { var _proxyWin = setup_toProxyWindow(windowProp); clean.register((function() { return windowProp.close(); })); return _proxyWin; } return new window_ProxyWindow({ send: send_send }); })); }; var setProxyWin = function(proxyWin) { return setProxyWinOverride ? setProxyWinOverride(proxyWin) : promise_ZalgoPromise.try((function() { currentProxyWin = proxyWin; })); }; var show = function() { return showOverride ? showOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !0 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null }).then(src_util_noop); }; var hide = function() { return hideOverride ? hideOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !1 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null }).then(src_util_noop); }; var getUrl = function() { return "function" == typeof url ? url({ props: props }) : url; }; var getAttributes = function() { return "function" == typeof attributes ? attributes({ props: props }) : attributes; }; var getInitialChildDomain = function() { return utils_getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; return openFrameOverride ? openFrameOverride(context, { windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: windowName, title: name }, getAttributes().iframe) })); })); }; var openPrerenderFrame = function(context) { return openPrerenderFrameOverride ? openPrerenderFrameOverride(context) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: "__zoid_prerender_frame__" + name + "_" + uniqueID() + "__", title: "prerender__" + name }, getAttributes().iframe) })); })); }; var openPrerender = function(context, proxyWin, proxyPrerenderFrame) { return openPrerenderOverride ? openPrerenderOverride(context, proxyWin, proxyPrerenderFrame) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyPrerenderFrame) throw new Error("Expected proxy frame to be passed"); return proxyPrerenderFrame.get().then((function(prerenderFrame) { clean.register((function() { return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { return utils_assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); })); } throw new Error("No render context available for " + context); })); }; var focus = function() { return promise_ZalgoPromise.try((function() { if (currentProxyWin) return promise_ZalgoPromise.all([ event.trigger(EVENT.FOCUS), currentProxyWin.focus() ]).then(src_util_noop); })); }; var getCurrentWindowReferenceUID = function() { var global = lib_global_getGlobal(window); global.windows = global.windows || {}; global.windows[uid] = window; clean.register((function() { delete global.windows[uid]; })); return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { if (initialChildDomain === utils_getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; if (target !== window) throw new Error("Can not construct cross-domain window reference for different target window"); if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", distance: utils_getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; var initChild = function(childDomain, childExports) { return promise_ZalgoPromise.try((function() { currentChildDomain = childDomain; childComponent = childExports; resolveInitPromise(); clean.register((function() { return childExports.close.fireAndForget().catch(src_util_noop); })); })); }; var resize = function(_ref3) { var width = _ref3.width, height = _ref3.height; return promise_ZalgoPromise.try((function() { event.trigger(EVENT.RESIZE, { width: width, height: height }); })); }; var destroy = function(err) { return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.DESTROY); })).catch(src_util_noop).then((function() { return clean.all(err); })).then((function() { initPromise.asyncReject(err || new Error("Component destroyed")); })); }; var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { if (utils_isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.CLOSE); })).then((function() { return destroy(err || new Error("Component closed")); })); })); })); var open = function(context, _ref4) { var proxyWin = _ref4.proxyWin, proxyFrame = _ref4.proxyFrame, windowName = _ref4.windowName; return openOverride ? openOverride(context, { proxyWin: proxyWin, proxyFrame: proxyFrame, windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyFrame) throw new Error("Expected proxy frame to be passed"); return proxyFrame.get().then((function(frame) { return awaitFrameWindow(frame).then((function(win) { clean.register((function() { return destroyElement(frame); })); clean.register((function() { return function(win) { for (var _i2 = 0, _requestPromises$get2 = windowStore("requestPromises").get(win, []); _i2 < _requestPromises$get2.length; _i2++) _requestPromises$get2[_i2].reject(new Error("Window " + (isWindowClosed(win) ? "closed" : "cleaned up") + " before response")).catch(src_util_noop); }(win); })); return win; })); })); } throw new Error("No render context available for " + context); })).then((function(win) { proxyWin.setWindow(win, { send: send_send }); return proxyWin.setName(windowName).then((function() { return proxyWin; })); })); }; var watchForUnload = function() { return promise_ZalgoPromise.try((function() { var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); })); }; var checkWindowClose = function(proxyWin) { var closed = !1; return proxyWin.isClosed().then((function(isClosed) { if (isClosed) { closed = !0; return close(new Error("Detected component window close")); } return promise_ZalgoPromise.delay(200).then((function() { return proxyWin.isClosed(); })).then((function(secondIsClosed) { if (secondIsClosed) { closed = !0; return close(new Error("Detected component window close")); } })); })).then((function() { return closed; })); }; var onError = function(err) { return onErrorOverride ? onErrorOverride(err) : promise_ZalgoPromise.try((function() { if (-1 === handledErrors.indexOf(err)) { handledErrors.push(err); initPromise.asyncReject(err); return event.trigger(EVENT.ERROR, err); } })); }; var exportsPromise = new promise_ZalgoPromise; var xport = function(actualExports) { return promise_ZalgoPromise.try((function() { exportsPromise.resolve(actualExports); })); }; initChild.onError = onError; var renderTemplate = function(renderer, _ref8) { return renderer({ uid: uid, container: _ref8.container, context: _ref8.context, doc: _ref8.doc, frame: _ref8.frame, prerenderFrame: _ref8.prerenderFrame, focus: focus, close: close, state: state, props: props, tag: tag, dimensions: "function" == typeof dimensions ? dimensions({ props: props }) : dimensions, event: event }); }; var prerender = function(proxyPrerenderWin, _ref9) { var context = _ref9.context; return prerenderOverride ? prerenderOverride(proxyPrerenderWin, { context: context }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc }); if (el) { if (el.ownerDocument !== doc) throw new Error("Expected prerender template to have been created with document from child window"); !function(win, el) { var tag = el.tagName.toLowerCase(); if ("html" !== tag) throw new Error("Expected element to be html, got " + tag); var documentElement = win.document.documentElement; for (var _i6 = 0, _arrayFrom2 = arrayFrom(documentElement.children); _i6 < _arrayFrom2.length; _i6++) documentElement.removeChild(_arrayFrom2[_i6]); for (var _i8 = 0, _arrayFrom4 = arrayFrom(el.children); _i8 < _arrayFrom4.length; _i8++) documentElement.appendChild(_arrayFrom4[_i8]); }(prerenderWindow, el); var _autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, element = void 0 === _autoResize$element ? "body" : _autoResize$element; if ((element = getElementSafe(element, doc)) && (width || height)) { var prerenderResizeListener = onResize(element, (function(_ref10) { resize({ width: width ? _ref10.width : void 0, height: height ? _ref10.height : void 0 }); }), { width: width, height: height, win: prerenderWindow }); event.on(EVENT.RENDERED, prerenderResizeListener.cancel); } } } } })); }; var renderContainer = function(proxyContainer, _ref11) { var proxyFrame = _ref11.proxyFrame, proxyPrerenderFrame = _ref11.proxyPrerenderFrame, context = _ref11.context, rerender = _ref11.rerender; return renderContainerOverride ? renderContainerOverride(proxyContainer, { proxyFrame: proxyFrame, proxyPrerenderFrame: proxyPrerenderFrame, context: context, rerender: rerender }) : promise_ZalgoPromise.hash({ container: proxyContainer.get(), frame: proxyFrame ? proxyFrame.get() : null, prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null, internalState: getInternalState() }).then((function(_ref12) { var container = _ref12.container, visible = _ref12.internalState.visible; var innerContainer = renderTemplate(containerTemplate, { context: context, container: container, frame: _ref12.frame, prerenderFrame: _ref12.prerenderFrame, doc: document }); if (innerContainer) { visible || hideElement(innerContainer); appendChild(container, innerContainer); var containerWatcher = function(element, handler) { handler = once(handler); var cancelled = !1; var mutationObservers = []; var interval; var sacrificialFrame; var sacrificialFrameWin; var cancel = function() { cancelled = !0; for (var _i18 = 0; _i18 < mutationObservers.length; _i18++) mutationObservers[_i18].disconnect(); interval && interval.cancel(); sacrificialFrameWin && sacrificialFrameWin.removeEventListener("unload", elementClosed); sacrificialFrame && destroyElement(sacrificialFrame); }; var elementClosed = function() { if (!cancelled) { handler(); cancel(); } }; if (isElementClosed(element)) { elementClosed(); return { cancel: cancel }; } if (window.MutationObserver) { var mutationElement = element.parentElement; for (;mutationElement; ) { var mutationObserver = new window.MutationObserver((function() { isElementClosed(element) && elementClosed(); })); mutationObserver.observe(mutationElement, { childList: !0 }); mutationObservers.push(mutationObserver); mutationElement = mutationElement.parentElement; } } (sacrificialFrame = document.createElement("iframe")).setAttribute("name", "__detect_close_" + uniqueID() + "__"); sacrificialFrame.style.display = "none"; awaitFrameWindow(sacrificialFrame).then((function(frameWin) { (sacrificialFrameWin = assertSameDomain(frameWin)).addEventListener("unload", elementClosed); })); element.appendChild(sacrificialFrame); interval = safeInterval((function() { isElementClosed(element) && elementClosed(); }), 1e3); return { cancel: cancel }; }(innerContainer, (function() { var removeError = new Error("Detected container element removed from DOM"); return promise_ZalgoPromise.delay(1).then((function() { if (!isElementClosed(innerContainer)) { clean.all(removeError); return rerender().then(resolveInitPromise, rejectInitPromise); } close(removeError); })); })); clean.register((function() { return containerWatcher.cancel(); })); clean.register((function() { return destroyElement(innerContainer); })); return currentProxyContainer = getProxyObject(innerContainer); } })); }; var getHelpers = function() { return { state: state, event: event, close: close, focus: focus, resize: resize, onError: onError, updateProps: updateProps, show: show, hide: hide }; }; var setProps = function(newInputProps) { void 0 === newInputProps && (newInputProps = {}); var container = currentContainer; var helpers = getHelpers(); extend(inputProps, newInputProps); !function(propsDef, existingProps, inputProps, helpers, container) { var state = helpers.state, close = helpers.close, focus = helpers.focus, event = helpers.event, onError = helpers.onError; eachProp(inputProps, propsDef, (function(key, propDef, val) { var valueDetermined = !1; var value = val; Object.defineProperty(existingProps, key, { configurable: !0, enumerable: !0, get: function() { if (valueDetermined) return value; valueDetermined = !0; return function() { if (!propDef) return value; var alias = propDef.alias; alias && !isDefined(val) && isDefined(inputProps[alias]) && (value = inputProps[alias]); propDef.value && (value = propDef.value({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); !propDef.default || isDefined(value) || isDefined(inputProps[key]) || (value = propDef.default({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); if (isDefined(value)) { if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : typeof value !== propDef.type) throw new TypeError("Prop is not of type " + propDef.type + ": " + key); } else if (!1 !== propDef.required && !isDefined(inputProps[key])) throw new Error('Expected prop "' + key + '" to be defined'); isDefined(value) && propDef.decorate && (value = propDef.decorate({ value: value, props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); return value; }(); } }); })); eachProp(existingProps, propsDef, src_util_noop); }(propsDef, props, inputProps, helpers, container); }; var updateProps = function(newProps) { setProps(newProps); return initPromise.then((function() { var child = childComponent; var proxyWin = currentProxyWin; if (child && proxyWin && currentChildDomain) return getPropsForChild(currentChildDomain).then((function(childProps) { return child.updateProps(childProps).catch((function(err) { return checkWindowClose(proxyWin).then((function(closed) { if (!closed) throw err; })); })); })); })); }; var getProxyContainer = function(container) { return getProxyContainerOverride ? getProxyContainerOverride(container) : promise_ZalgoPromise.try((function() { return elementReady(container); })).then((function(containerElement) { isShadowElement(containerElement) && (containerElement = function insertShadowSlot(element) { var shadowHost = function(element) { var shadowRoot = function(element) { for (;element.parentNode; ) element = element.parentNode; if (isShadowElement(element)) return element; }(element); if (shadowRoot && shadowRoot.host) return shadowRoot.host; }(element); if (!shadowHost) throw new Error("Element is not in shadow dom"); var slotName = "shadow-slot-" + uniqueID(); var slot = document.createElement("slot"); slot.setAttribute("name", slotName); element.appendChild(slot); var slotProvider = document.createElement("div"); slotProvider.setAttribute("slot", slotName); shadowHost.appendChild(slotProvider); return isShadowElement(shadowHost) ? insertShadowSlot(slotProvider) : slotProvider; }(containerElement)); currentContainer = containerElement; return getProxyObject(containerElement); })); }; return { init: function() { !function() { event.on(EVENT.RENDER, (function() { return props.onRender(); })); event.on(EVENT.DISPLAY, (function() { return props.onDisplay(); })); event.on(EVENT.RENDERED, (function() { return props.onRendered(); })); event.on(EVENT.CLOSE, (function() { return props.onClose(); })); event.on(EVENT.DESTROY, (function() { return props.onDestroy(); })); event.on(EVENT.RESIZE, (function() { return props.onResize(); })); event.on(EVENT.FOCUS, (function() { return props.onFocus(); })); event.on(EVENT.PROPS, (function(newProps) { return props.onProps(newProps); })); event.on(EVENT.ERROR, (function(err) { return props && props.onError ? props.onError(err) : rejectInitPromise(err).then((function() { setTimeout((function() { throw err; }), 1); })); })); clean.register(event.reset); }(); }, render: function(_ref14) { var target = _ref14.target, container = _ref14.container, context = _ref14.context, rerender = _ref14.rerender; return promise_ZalgoPromise.try((function() { var initialChildDomain = getInitialChildDomain(); var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { if (!function(win1, win2) { var top1 = utils_getTop(win1) || win1; var top2 = utils_getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = utils_getAllFramesInWindow(win1); var allFrames2 = utils_getAllFramesInWindow(win2); if (utils_anyMatch(allFrames1, allFrames2)) return !0; var opener1 = utils_getOpener(top1); var opener2 = utils_getOpener(top2); return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), !1; }(window, target)) throw new Error("Can only renderTo an adjacent frame"); var origin = utils_getDomain(); if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); var delegatePromise = promise_ZalgoPromise.try((function() { if (target !== window) return function(context, target) { var delegateProps = {}; for (var _i4 = 0, _Object$keys4 = Object.keys(props); _i4 < _Object$keys4.length; _i4++) { var propName = _Object$keys4[_i4]; var propDef = propsDef[propName]; propDef && propDef.allowDelegate && (delegateProps[propName] = props[propName]); } var childOverridesPromise = send_send(target, "zoid_delegate_" + name, { uid: uid, overrides: { props: delegateProps, event: event, close: close, onError: onError, getInternalState: getInternalState, setInternalState: setInternalState, resolveInitPromise: resolveInitPromise, rejectInitPromise: rejectInitPromise } }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { if (!utils_isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { throw new Error("Unable to delegate rendering. Possibly the component is not loaded in the target window.\n\n" + stringifyError(err)); })); getProxyContainerOverride = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyContainer.apply(childOverrides, args); })); }; renderContainerOverride = function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.renderContainer.apply(childOverrides, args); })); }; showOverride = function() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) args[_key3] = arguments[_key3]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.show.apply(childOverrides, args); })); }; hideOverride = function() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) args[_key4] = arguments[_key4]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.hide.apply(childOverrides, args); })); }; watchForUnloadOverride = function() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) args[_key5] = arguments[_key5]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.watchForUnload.apply(childOverrides, args); })); }; if (context === CONTEXT.IFRAME) { getProxyWindowOverride = function() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) args[_key6] = arguments[_key6]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyWindow.apply(childOverrides, args); })); }; openFrameOverride = function() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) args[_key7] = arguments[_key7]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openFrame.apply(childOverrides, args); })); }; openPrerenderFrameOverride = function() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) args[_key8] = arguments[_key8]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerenderFrame.apply(childOverrides, args); })); }; prerenderOverride = function() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) args[_key9] = arguments[_key9]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.prerender.apply(childOverrides, args); })); }; openOverride = function() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) args[_key10] = arguments[_key10]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.open.apply(childOverrides, args); })); }; openPrerenderOverride = function() { for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) args[_key11] = arguments[_key11]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerender.apply(childOverrides, args); })); }; } return childOverridesPromise; }(context, target); })); var windowProp = props.window; var watchForUnloadPromise = watchForUnload(); var buildBodyPromise = serializeProps(propsDef, props, "post"); var onRenderPromise = event.trigger(EVENT.RENDER); var getProxyContainerPromise = getProxyContainer(container); var getProxyWindowPromise = getProxyWindow(); var finalSetPropsPromise = getProxyContainerPromise.then((function() { return setProps(); })); var buildUrlPromise = finalSetPropsPromise.then((function() { return serializeProps(propsDef, props, "get").then((function(query) { return function(url, options) { var query = options.query || {}; var hash = options.hash || {}; var originalUrl; var originalHash; var _url$split = url.split("#"); originalHash = _url$split[1]; var _originalUrl$split = (originalUrl = _url$split[0]).split("?"); originalUrl = _originalUrl$split[0]; var queryString = extendQuery(_originalUrl$split[1], query); var hashString = extendQuery(originalHash, hash); queryString && (originalUrl = originalUrl + "?" + queryString); hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; }(function(url) { if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); }(getUrl()), { query: query }); })); })); var buildWindowNamePromise = getProxyWindowPromise.then((function(proxyWin) { return function(_temp2) { var _ref6 = void 0 === _temp2 ? {} : _temp2, proxyWin = _ref6.proxyWin, initialChildDomain = _ref6.initialChildDomain, childDomainMatch = _ref6.childDomainMatch, _ref6$target = _ref6.target, target = void 0 === _ref6$target ? window : _ref6$target, context = _ref6.context; return function(_temp) { var _ref5 = void 0 === _temp ? {} : _temp, proxyWin = _ref5.proxyWin, childDomainMatch = _ref5.childDomainMatch, context = _ref5.context; return getPropsForChild(_ref5.initialChildDomain).then((function(childProps) { return { uid: uid, context: context, tag: tag, childDomainMatch: childDomainMatch, version: "9_0_87", props: childProps, exports: (win = proxyWin, { init: function(childExports) { return initChild(this.origin, childExports); }, close: close, checkClose: function() { return checkWindowClose(win); }, resize: resize, onError: onError, show: show, hide: hide, export: xport }) }; var win; })); }({ proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, context: context }).then((function(childPayload) { var _crossDomainSerialize = crossDomainSerialize({ data: childPayload, metaData: { windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { domain: utils_getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, passByReference: initialChildDomain === utils_getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; })); }({ proxyWin: (_ref7 = { proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, target: target, context: context }).proxyWin, initialChildDomain: _ref7.initialChildDomain, childDomainMatch: _ref7.childDomainMatch, target: _ref7.target, context: _ref7.context }).then((function(serializedPayload) { return buildChildWindowName({ name: name, serializedPayload: serializedPayload }); })); var _ref7; })); var openFramePromise = buildWindowNamePromise.then((function(windowName) { return openFrame(context, { windowName: windowName }); })); var openPrerenderFramePromise = openPrerenderFrame(context); var renderContainerPromise = promise_ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref15) { return renderContainer(_ref15.proxyContainer, { context: context, proxyFrame: _ref15.proxyFrame, proxyPrerenderFrame: _ref15.proxyPrerenderFrame, rerender: rerender }); })).then((function(proxyContainer) { return proxyContainer; })); var openPromise = promise_ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then((function(_ref16) { var proxyWin = _ref16.proxyWin; return windowProp ? proxyWin : open(context, { windowName: _ref16.windowName, proxyWin: proxyWin, proxyFrame: _ref16.proxyFrame }); })); var openPrerenderPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref17) { return openPrerender(context, _ref17.proxyWin, _ref17.proxyPrerenderFrame); })); var setStatePromise = openPromise.then((function(proxyWin) { currentProxyWin = proxyWin; return setProxyWin(proxyWin); })); var prerenderPromise = promise_ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then((function(_ref18) { return prerender(_ref18.proxyPrerenderWin, { context: context }); })); var setWindowNamePromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then((function(_ref19) { if (windowProp) return _ref19.proxyWin.setName(_ref19.windowName); })); var getMethodPromise = promise_ZalgoPromise.hash({ body: buildBodyPromise }).then((function(_ref20) { return options.method ? options.method : Object.keys(_ref20.body).length ? "post" : "get"; })); var loadUrlPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then((function(_ref21) { return _ref21.proxyWin.setLocation(_ref21.windowUrl, { method: _ref21.method, body: _ref21.body }); })); var watchForClosePromise = openPromise.then((function(proxyWin) { !function watchForClose(proxyWin, context) { var cancelled = !1; clean.register((function() { cancelled = !0; })); return promise_ZalgoPromise.delay(2e3).then((function() { return proxyWin.isClosed(); })).then((function(isClosed) { if (!cancelled) return isClosed ? close(new Error("Detected " + context + " close")) : watchForClose(proxyWin, context); })); }(proxyWin, context); })); var onDisplayPromise = promise_ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then((function() { return event.trigger(EVENT.DISPLAY); })); var openBridgePromise = openPromise.then((function(proxyWin) {})); var runTimeoutPromise = loadUrlPromise.then((function() { return promise_ZalgoPromise.try((function() { var timeout = props.timeout; if (timeout) return initPromise.timeout(timeout, new Error("Loading component timed out after " + timeout + " milliseconds")); })); })); var onRenderedPromise = initPromise.then((function() { return event.trigger(EVENT.RENDERED); })); return promise_ZalgoPromise.hash({ initPromise: initPromise, buildUrlPromise: buildUrlPromise, onRenderPromise: onRenderPromise, getProxyContainerPromise: getProxyContainerPromise, openFramePromise: openFramePromise, openPrerenderFramePromise: openPrerenderFramePromise, renderContainerPromise: renderContainerPromise, openPromise: openPromise, openPrerenderPromise: openPrerenderPromise, setStatePromise: setStatePromise, prerenderPromise: prerenderPromise, loadUrlPromise: loadUrlPromise, buildWindowNamePromise: buildWindowNamePromise, setWindowNamePromise: setWindowNamePromise, watchForClosePromise: watchForClosePromise, onDisplayPromise: onDisplayPromise, openBridgePromise: openBridgePromise, runTimeoutPromise: runTimeoutPromise, onRenderedPromise: onRenderedPromise, delegatePromise: delegatePromise, watchForUnloadPromise: watchForUnloadPromise, finalSetPropsPromise: finalSetPropsPromise }); })).catch((function(err) { return promise_ZalgoPromise.all([ onError(err), destroy(err) ]).then((function() { throw err; }), (function() { throw err; })); })).then(src_util_noop); }, destroy: destroy, getProps: function() { return props; }, setProps: setProps, export: xport, getHelpers: getHelpers, getDelegateOverrides: function() { return promise_ZalgoPromise.try((function() { return { getProxyContainer: getProxyContainer, show: show, hide: hide, renderContainer: renderContainer, getProxyWindow: getProxyWindow, watchForUnload: watchForUnload, openFrame: openFrame, openPrerenderFrame: openPrerenderFrame, prerender: prerender, open: open, openPrerender: openPrerender, setProxyWin: setProxyWin }; })); }, getExports: function() { return xports({ getExports: function() { return exportsPromise; } }); } }; } function defaultContainerTemplate(_ref) { var uid = _ref.uid, frame = _ref.frame, prerenderFrame = _ref.prerenderFrame, doc = _ref.doc, props = _ref.props, event = _ref.event, dimensions = _ref.dimensions; var width = dimensions.width, height = dimensions.height; if (frame && prerenderFrame) { var div = doc.createElement("div"); div.setAttribute("id", uid); var style = doc.createElement("style"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); style.appendChild(doc.createTextNode("\n #" + uid + " {\n display: inline-block;\n position: relative;\n width: " + width + ";\n height: " + height + ";\n }\n\n #" + uid + " > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #" + uid + " > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #" + uid + " > iframe.zoid-visible {\n opacity: 1;\n }\n ")); div.appendChild(frame); div.appendChild(prerenderFrame); div.appendChild(style); prerenderFrame.classList.add("zoid-visible"); frame.classList.add("zoid-invisible"); event.on(EVENT.RENDERED, (function() { prerenderFrame.classList.remove("zoid-visible"); prerenderFrame.classList.add("zoid-invisible"); frame.classList.remove("zoid-invisible"); frame.classList.add("zoid-visible"); setTimeout((function() { destroyElement(prerenderFrame); }), 1); })); event.on(EVENT.RESIZE, (function(_ref2) { var newWidth = _ref2.width, newHeight = _ref2.height; "number" == typeof newWidth && (div.style.width = toCSS(newWidth)); "number" == typeof newHeight && (div.style.height = toCSS(newHeight)); })); return div; } } var cleanInstances = cleanup(); var cleanZoid = cleanup(); function component(opts) { var options = function(options) { var tag = options.tag, url = options.url, domain = options.domain, bridgeUrl = options.bridgeUrl, _options$props = options.props, props = void 0 === _options$props ? {} : _options$props, _options$dimensions = options.dimensions, dimensions = void 0 === _options$dimensions ? {} : _options$dimensions, _options$autoResize = options.autoResize, autoResize = void 0 === _options$autoResize ? {} : _options$autoResize, _options$allowedParen = options.allowedParentDomains, allowedParentDomains = void 0 === _options$allowedParen ? "*" : _options$allowedParen, _options$attributes = options.attributes, attributes = void 0 === _options$attributes ? {} : _options$attributes, _options$defaultConte = options.defaultContext, defaultContext = void 0 === _options$defaultConte ? CONTEXT.IFRAME : _options$defaultConte, _options$containerTem = options.containerTemplate, containerTemplate = void 0 === _options$containerTem ? defaultContainerTemplate : _options$containerTem, _options$prerenderTem = options.prerenderTemplate, prerenderTemplate = void 0 === _options$prerenderTem ? null : _options$prerenderTem, validate = options.validate, _options$eligible = options.eligible, eligible = void 0 === _options$eligible ? function() { return { eligible: !0 }; } : _options$eligible, _options$logger = options.logger, logger = void 0 === _options$logger ? { info: src_util_noop } : _options$logger, _options$exports = options.exports, xportsDefinition = void 0 === _options$exports ? src_util_noop : _options$exports, method = options.method, _options$children = options.children, children = void 0 === _options$children ? function() { return {}; } : _options$children; var name = tag.replace(/-/g, "_"); var propsDef = _extends({}, { window: { type: PROP_TYPE.OBJECT, sendToChild: !1, required: !1, allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); if (utils_isWindow(value)) { if (utils_isWindowClosed(value)) throw new Error("Window is closed"); if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { return setup_toProxyWindow(_ref3.value); } }, timeout: { type: PROP_TYPE.NUMBER, required: !1, sendToChild: !1 }, cspNonce: { type: PROP_TYPE.STRING, required: !1 }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onRendered: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onRender: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onClose: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onDestroy: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onResize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, onFocus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, close: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref4) { return _ref4.close; } }, focus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref5) { return _ref5.focus; } }, resize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref6) { return _ref6.resize; } }, uid: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref7) { return _ref7.uid; } }, tag: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref8) { return _ref8.tag; } }, getParent: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref9) { return _ref9.getParent; } }, getParentDomain: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref10) { return _ref10.getParentDomain; } }, show: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref11) { return _ref11.show; } }, hide: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref12) { return _ref12.hide; } }, export: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref13) { return _ref13.export; } }, onError: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref14) { return _ref14.onError; } }, onProps: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref15) { return _ref15.onProps; } }, getSiblings: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref16) { return _ref16.getSiblings; } } }, props); if (!containerTemplate) throw new Error("Container template required"); return { name: name, tag: tag, url: url, domain: domain, bridgeUrl: bridgeUrl, method: method, propsDef: propsDef, dimensions: dimensions, autoResize: autoResize, allowedParentDomains: allowedParentDomains, attributes: attributes, defaultContext: defaultContext, containerTemplate: containerTemplate, prerenderTemplate: prerenderTemplate, validate: validate, logger: logger, eligible: eligible, children: children, exports: "function" == typeof xportsDefinition ? xportsDefinition : function(_ref) { var getExports = _ref.getExports; var result = {}; var _loop = function(_i2, _Object$keys2) { var key = _Object$keys2[_i2]; var type = xportsDefinition[key].type; var valuePromise = getExports().then((function(res) { return res[key]; })); result[key] = type === PROP_TYPE.FUNCTION ? function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return valuePromise.then((function(value) { return value.apply(void 0, args); })); } : valuePromise; }; for (var _i2 = 0, _Object$keys2 = Object.keys(xportsDefinition); _i2 < _Object$keys2.length; _i2++) _loop(_i2, _Object$keys2); return result; } }; }(opts); var name = options.name, tag = options.tag, defaultContext = options.defaultContext, eligible = options.eligible, children = options.children; var global = lib_global_getGlobal(window); var instances = []; var isChild = function() { if (function(name) { try { return parseWindowName(window.name).name === name; } catch (err) {} return !1; }(name)) { var _payload = getInitialParentPayload().payload; if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; } return !1; }; var registerChild = memoize((function() { if (isChild()) { if (window.xprops) { delete global.components[tag]; throw new Error("Can not register " + name + " as child - child already registered"); } var child = function(options) { var tag = options.tag, propsDef = options.propsDef, autoResize = options.autoResize, allowedParentDomains = options.allowedParentDomains; var onPropHandlers = []; var _getInitialParentPayl = getInitialParentPayload(), parent = _getInitialParentPayl.parent, payload = _getInitialParentPayl.payload; var parentComponentWindow = parent.win, parentDomain = parent.domain; var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; }; var getParentDomain = function() { return parentDomain; }; var onProps = function(handler) { onPropHandlers.push(handler); return { cancel: function() { onPropHandlers.splice(onPropHandlers.indexOf(handler), 1); } }; }; var resize = function(_ref) { return parentResize.fireAndForget({ width: _ref.width, height: _ref.height }); }; var xport = function(xports) { exportsPromise.resolve(xports); return parentExport(xports); }; var getSiblings = function(_temp) { var anyParent = (void 0 === _temp ? {} : _temp).anyParent; var result = []; var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(win)) { var xprops = utils_assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { var xports = tryGlobal(win, (function(global) { return global.exports; })); result.push({ props: xprops, exports: xports }); } } } } return result; }; var setProps = function(newProps, origin, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var normalizedProps = function(parentComponentWindow, propsDef, props, origin, helpers, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); } } if (!isUpdate) for (var _i4 = 0, _Object$keys4 = Object.keys(propsDef); _i4 < _Object$keys4.length; _i4++) { var _key = _Object$keys4[_i4]; props.hasOwnProperty(_key) || (result[_key] = normalizeChildProp(propsDef, 0, _key, void 0, helpers)); } return result; }(parentComponentWindow, propsDef, newProps, origin, { tag: tag, show: show, hide: hide, close: close, focus: child_focus, onError: onError, resize: resize, getSiblings: getSiblings, onProps: onProps, getParent: getParent, getParentDomain: getParentDomain, uid: uid, export: xport }, isUpdate); props ? extend(props, normalizedProps) : props = normalizedProps; for (var _i4 = 0; _i4 < onPropHandlers.length; _i4++) (0, onPropHandlers[_i4])(props); }; var updateProps = function(newProps) { return promise_ZalgoPromise.try((function() { return setProps(newProps, parentDomain, !0); })); }; return { init: function() { return promise_ZalgoPromise.try((function() { utils_isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, sender: { win: parentComponentWindow }, basic: !0 }), sender = _crossDomainDeseriali2.sender; if ("uid" === _crossDomainDeseriali2.reference.type || "global" === _crossDomainDeseriali2.metaData.windowRef.type) { var _crossDomainSerialize = crossDomainSerialize({ data: _crossDomainDeseriali2.data, metaData: { windowRef: window_getWindowRef(parentComponentWindow) }, sender: { domain: sender.domain }, receiver: { win: window, domain: utils_getDomain() }, basic: !0 }); window.name = buildChildWindowName({ name: componentName, serializedPayload: _crossDomainSerialize.serializedData }); } }({ componentName: options.name, parentComponentWindow: parentComponentWindow }); lib_global_getGlobal(window).exports = options.exports({ getExports: function() { return exportsPromise; } }); !function(allowedParentDomains, domain) { if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { window.addEventListener("beforeunload", (function() { checkClose.fireAndForget(); })); window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); utils_onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); return parentInit({ updateProps: updateProps, close: child_destroy }); })).then((function() { return (_autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, elementReady(void 0 === _autoResize$element ? "body" : _autoResize$element).catch(src_util_noop).then((function(element) { return { width: width, height: height, element: element }; }))).then((function(_ref3) { var width = _ref3.width, height = _ref3.height, element = _ref3.element; element && (width || height) && context !== CONTEXT.POPUP && onResize(element, (function(_ref4) { resize({ width: width ? _ref4.width : void 0, height: height ? _ref4.height : void 0 }); }), { width: width, height: height }); })); var _autoResize$width, width, _autoResize$height, height, _autoResize$element; })).catch((function(err) { onError(err); })); }, getProps: function() { if (props) return props; setProps(initialProps, parentDomain); return props; } }; }(options); child.init(); return child; } })); registerChild(); !function() { var allowDelegateListener = on_on("zoid_allow_delegate_" + name, (function() { return !0; })); var delegateListener = on_on("zoid_delegate_" + name, (function(_ref2) { var _ref2$data = _ref2.data; return { parent: parentComponent({ uid: _ref2$data.uid, options: options, overrides: _ref2$data.overrides, parentWin: _ref2.source }) }; })); cleanZoid.register(allowDelegateListener.cancel); cleanZoid.register(delegateListener.cancel); }(); global.components = global.components || {}; if (global.components[tag]) throw new Error("Can not register multiple components with the same tag: " + tag); global.components[tag] = !0; return { init: function init(inputProps) { var instance; var uid = "zoid-" + tag + "-" + uniqueID(); var props = inputProps || {}; var _eligible = eligible({ props: props }), eligibility = _eligible.eligible, reason = _eligible.reason; var onDestroy = props.onDestroy; props.onDestroy = function() { instance && eligibility && instances.splice(instances.indexOf(instance), 1); if (onDestroy) return onDestroy.apply(void 0, arguments); }; var parent = parentComponent({ uid: uid, options: options }); parent.init(); eligibility ? parent.setProps(props) : props.onDestroy && props.onDestroy(); cleanInstances.register((function(err) { return parent.destroy(err || new Error("zoid destroyed all components")); })); var clone = function(_temp) { var _ref4$decorate = (void 0 === _temp ? {} : _temp).decorate; return init((void 0 === _ref4$decorate ? identity : _ref4$decorate)(props)); }; var _render = function(target, container, context) { return promise_ZalgoPromise.try((function() { if (!eligibility) { var err = new Error(reason || name + " component is not eligible"); return parent.destroy(err).then((function() { throw err; })); } if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); if (context) { if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) throw new Error("Unrecognized context: " + context); return context; } return defaultContext; })); }(props, context); })).then((function(finalContext) { container = function(context, container) { if (container) { if ("string" != typeof container && !isElement(container)) throw new TypeError("Expected string or element selector to be passed"); return container; } if (context === CONTEXT.POPUP) return "body"; throw new Error("Expected element to be passed to render iframe"); }(finalContext, container); if (target !== window && "string" != typeof container) throw new Error("Must pass string element when rendering to another window"); return parent.render({ target: target, container: container, context: finalContext, rerender: function() { var newInstance = clone(); extend(instance, newInstance); return newInstance.renderTo(target, container, context); } }); })).catch((function(err) { return parent.destroy(err).then((function() { throw err; })); })); }; instance = _extends({}, parent.getExports(), parent.getHelpers(), function() { var childComponents = children(); var result = {}; var _loop2 = function(_i4, _Object$keys4) { var childName = _Object$keys4[_i4]; var Child = childComponents[childName]; result[childName] = function(childInputProps) { var parentProps = parent.getProps(); var childProps = _extends({}, childInputProps, { parent: { uid: uid, props: parentProps, export: parent.export } }); return Child(childProps); }; }; for (var _i4 = 0, _Object$keys4 = Object.keys(childComponents); _i4 < _Object$keys4.length; _i4++) _loop2(_i4, _Object$keys4); return result; }(), { isEligible: function() { return eligibility; }, clone: clone, render: function(container, context) { return _render(window, container, context); }, renderTo: function(target, container, context) { return _render(target, container, context); } }); eligibility && instances.push(instance); return instance; }, instances: instances, driver: function(driverName, dep) { throw new Error("Driver support not enabled"); }, isChild: isChild, canRenderTo: function(win) { return send_send(win, "zoid_allow_delegate_" + name).then((function(_ref3) { return _ref3.data; })).catch((function() { return !1; })); }, registerChild: registerChild }; } var component_create = function(options) { !function() { if (!global_getGlobal().initialized) { global_getGlobal().initialized = !0; on = (_ref3 = { on: on_on, send: send_send }).on, send = _ref3.send, (global = global_getGlobal()).receiveMessage = global.receiveMessage || function(message) { return receive_receiveMessage(message, { on: on, send: send }); }; !function(_ref5) { var on = _ref5.on, send = _ref5.send; globalStore().getOrSet("postMessageListener", (function() { return addEventListener(window, "message", (function(event) { !function(event, _ref4) { var on = _ref4.on, send = _ref4.send; promise_ZalgoPromise.try((function() { var source = event.source || event.sourceElement; var origin = event.origin || event.originalEvent && event.originalEvent.origin; var data = event.data; "null" === origin && (origin = "file://"); if (source) { if (!origin) throw new Error("Post message did not have origin domain"); receive_receiveMessage({ source: source, origin: origin, data: data }, { on: on, send: send }); } })); }(event, { on: on, send: send }); })); })); }({ on: on_on, send: send_send }); !function(_ref8) { var on = _ref8.on, send = _ref8.send; globalStore("builtinListeners").getOrSet("helloListener", (function() { var listener = on("postrobot_hello", { domain: "*" }, (function(_ref3) { resolveHelloPromise(_ref3.source, { domain: _ref3.origin }); return { instanceID: getInstanceID() }; })); var parent = getAncestor(); parent && sayHello(parent, { send: send }).catch((function(err) {})); return listener; })); }({ on: on_on, send: send_send }); } var _ref3, on, send, global; }(); var comp = component(options); var init = function(props) { return comp.init(props); }; init.driver = function(name, dep) { return comp.driver(name, dep); }; init.isChild = function() { return comp.isChild(); }; init.canRenderTo = function(win) { return comp.canRenderTo(win); }; init.instances = comp.instances; var child = comp.registerChild(); child && (window.xprops = init.xprops = child.getProps()); return init; }; function destroyComponents(err) { var destroyPromise = cleanInstances.all(err); cleanInstances = cleanup(); return destroyPromise; } var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); delete window.__zoid_9_0_87__; !function() { !function() { var responseListeners = globalStore("responseListeners"); for (var _i2 = 0, _responseListeners$ke2 = responseListeners.keys(); _i2 < _responseListeners$ke2.length; _i2++) { var hash = _responseListeners$ke2[_i2]; var listener = responseListeners.get(hash); listener && (listener.cancelled = !0); responseListeners.del(hash); } }(); (listener = globalStore().get("postMessageListener")) && listener.cancel(); var listener; delete window.__post_robot_10_0_46__; }(); return cleanZoid.all(err); } } ]); })); ================================================ FILE: dist/zoid.frameworks.frame.js ================================================ !function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define("zoid", [], factory) : "object" == typeof exports ? exports.zoid = factory() : root.zoid = factory(); }("undefined" != typeof self ? self : this, (function() { return function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module = installedModules[moduleId] = { i: moduleId, l: !1, exports: {} }; modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); module.l = !0; return module.exports; } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d = function(exports, name, getter) { __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, { enumerable: !0, get: getter }); }; __webpack_require__.r = function(exports) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); Object.defineProperty(exports, "__esModule", { value: !0 }); }; __webpack_require__.t = function(value, mode) { 1 & mode && (value = __webpack_require__(value)); if (8 & mode) return value; if (4 & mode && "object" == typeof value && value && value.__esModule) return value; var ns = Object.create(null); __webpack_require__.r(ns); Object.defineProperty(ns, "default", { enumerable: !0, value: value }); if (2 & mode && "string" != typeof value) for (var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); return ns; }; __webpack_require__.n = function(module) { var getter = module && module.__esModule ? function() { return module.default; } : function() { return module; }; __webpack_require__.d(getter, "a", getter); return getter; }; __webpack_require__.o = function(object, property) { return {}.hasOwnProperty.call(object, property); }; __webpack_require__.p = ""; return __webpack_require__(__webpack_require__.s = 0); }([ function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, "PopupOpenError", (function() { return dom_PopupOpenError; })); __webpack_require__.d(__webpack_exports__, "create", (function() { return component_create; })); __webpack_require__.d(__webpack_exports__, "destroy", (function() { return component_destroy; })); __webpack_require__.d(__webpack_exports__, "destroyComponents", (function() { return destroyComponents; })); __webpack_require__.d(__webpack_exports__, "destroyAll", (function() { return destroyAll; })); __webpack_require__.d(__webpack_exports__, "PROP_TYPE", (function() { return PROP_TYPE; })); __webpack_require__.d(__webpack_exports__, "PROP_SERIALIZATION", (function() { return PROP_SERIALIZATION; })); __webpack_require__.d(__webpack_exports__, "CONTEXT", (function() { return CONTEXT; })); __webpack_require__.d(__webpack_exports__, "EVENT", (function() { return EVENT; })); function _setPrototypeOf(o, p) { return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) { o.__proto__ = p; return o; })(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _extends() { return (_extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) ({}).hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }).apply(this, arguments); } function utils_isPromise(item) { try { if (!item) return !1; if ("undefined" != typeof Promise && item instanceof Promise) return !0; if ("undefined" != typeof window && "function" == typeof window.Window && item instanceof window.Window) return !1; if ("undefined" != typeof window && "function" == typeof window.constructor && item instanceof window.constructor) return !1; var _toString = {}.toString; if (_toString) { var name = _toString.call(item); if ("[object Window]" === name || "[object global]" === name || "[object DOMWindow]" === name) return !1; } if ("function" == typeof item.then) return !0; } catch (err) { return !1; } return !1; } var dispatchedErrors = []; var possiblyUnhandledPromiseHandlers = []; var activeCount = 0; var flushPromise; function flushActive() { if (!activeCount && flushPromise) { var promise = flushPromise; flushPromise = null; promise.resolve(); } } function startActive() { activeCount += 1; } function endActive() { activeCount -= 1; flushActive(); } var promise_ZalgoPromise = function() { function ZalgoPromise(handler) { var _this = this; this.resolved = void 0; this.rejected = void 0; this.errorHandled = void 0; this.value = void 0; this.error = void 0; this.handlers = void 0; this.dispatching = void 0; this.stack = void 0; this.resolved = !1; this.rejected = !1; this.errorHandled = !1; this.handlers = []; if (handler) { var _result; var _error; var resolved = !1; var rejected = !1; var isAsync = !1; startActive(); try { handler((function(res) { if (isAsync) _this.resolve(res); else { resolved = !0; _result = res; } }), (function(err) { if (isAsync) _this.reject(err); else { rejected = !0; _error = err; } })); } catch (err) { endActive(); this.reject(err); return; } endActive(); isAsync = !0; resolved ? this.resolve(_result) : rejected && this.reject(_error); } } var _proto = ZalgoPromise.prototype; _proto.resolve = function(result) { if (this.resolved || this.rejected) return this; if (utils_isPromise(result)) throw new Error("Can not resolve promise with another promise"); this.resolved = !0; this.value = result; this.dispatch(); return this; }; _proto.reject = function(error) { var _this2 = this; if (this.resolved || this.rejected) return this; if (utils_isPromise(error)) throw new Error("Can not reject promise with another promise"); if (!error) { var _err = error && "function" == typeof error.toString ? error.toString() : {}.toString.call(error); error = new Error("Expected reject to be called with Error, got " + _err); } this.rejected = !0; this.error = error; this.errorHandled || setTimeout((function() { _this2.errorHandled || function(err, promise) { if (-1 === dispatchedErrors.indexOf(err)) { dispatchedErrors.push(err); setTimeout((function() { throw err; }), 1); for (var j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) possiblyUnhandledPromiseHandlers[j](err, promise); } }(error, _this2); }), 1); this.dispatch(); return this; }; _proto.asyncReject = function(error) { this.errorHandled = !0; this.reject(error); return this; }; _proto.dispatch = function() { var resolved = this.resolved, rejected = this.rejected, handlers = this.handlers; if (!this.dispatching && (resolved || rejected)) { this.dispatching = !0; startActive(); var chain = function(firstPromise, secondPromise) { return firstPromise.then((function(res) { secondPromise.resolve(res); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < handlers.length; i++) { var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise; var _result2 = void 0; if (resolved) try { _result2 = onSuccess ? onSuccess(this.value) : this.value; } catch (err) { promise.reject(err); continue; } else if (rejected) { if (!onError) { promise.reject(this.error); continue; } try { _result2 = onError(this.error); } catch (err) { promise.reject(err); continue; } } if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) { var promiseResult = _result2; promiseResult.resolved ? promise.resolve(promiseResult.value) : promise.reject(promiseResult.error); promiseResult.errorHandled = !0; } else utils_isPromise(_result2) ? _result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected) ? _result2.resolved ? promise.resolve(_result2.value) : promise.reject(_result2.error) : chain(_result2, promise) : promise.resolve(_result2); } handlers.length = 0; this.dispatching = !1; endActive(); } }; _proto.then = function(onSuccess, onError) { if (onSuccess && "function" != typeof onSuccess && !onSuccess.call) throw new Error("Promise.then expected a function for success handler"); if (onError && "function" != typeof onError && !onError.call) throw new Error("Promise.then expected a function for error handler"); var promise = new ZalgoPromise; this.handlers.push({ promise: promise, onSuccess: onSuccess, onError: onError }); this.errorHandled = !0; this.dispatch(); return promise; }; _proto.catch = function(onError) { return this.then(void 0, onError); }; _proto.finally = function(onFinally) { if (onFinally && "function" != typeof onFinally && !onFinally.call) throw new Error("Promise.finally expected a function"); return this.then((function(result) { return ZalgoPromise.try(onFinally).then((function() { return result; })); }), (function(err) { return ZalgoPromise.try(onFinally).then((function() { throw err; })); })); }; _proto.timeout = function(time, err) { var _this3 = this; if (this.resolved || this.rejected) return this; var timeout = setTimeout((function() { _this3.resolved || _this3.rejected || _this3.reject(err || new Error("Promise timed out after " + time + "ms")); }), time); return this.then((function(result) { clearTimeout(timeout); return result; })); }; _proto.toPromise = function() { if ("undefined" == typeof Promise) throw new TypeError("Could not find Promise"); return Promise.resolve(this); }; _proto.lazy = function() { this.errorHandled = !0; return this; }; ZalgoPromise.resolve = function(value) { return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise((function(resolve, reject) { return value.then(resolve, reject); })) : (new ZalgoPromise).resolve(value); }; ZalgoPromise.reject = function(error) { return (new ZalgoPromise).reject(error); }; ZalgoPromise.asyncReject = function(error) { return (new ZalgoPromise).asyncReject(error); }; ZalgoPromise.all = function(promises) { var promise = new ZalgoPromise; var count = promises.length; var results = [].slice(); if (!count) { promise.resolve(results); return promise; } var chain = function(i, firstPromise, secondPromise) { return firstPromise.then((function(res) { results[i] = res; 0 == (count -= 1) && promise.resolve(results); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < promises.length; i++) { var prom = promises[i]; if (prom instanceof ZalgoPromise) { if (prom.resolved) { results[i] = prom.value; count -= 1; continue; } } else if (!utils_isPromise(prom)) { results[i] = prom; count -= 1; continue; } chain(i, ZalgoPromise.resolve(prom), promise); } 0 === count && promise.resolve(results); return promise; }; ZalgoPromise.hash = function(promises) { var result = {}; var awaitPromises = []; var _loop = function(key) { if (promises.hasOwnProperty(key)) { var value = promises[key]; utils_isPromise(value) ? awaitPromises.push(value.then((function(res) { result[key] = res; }))) : result[key] = value; } }; for (var key in promises) _loop(key); return ZalgoPromise.all(awaitPromises).then((function() { return result; })); }; ZalgoPromise.map = function(items, method) { return ZalgoPromise.all(items.map(method)); }; ZalgoPromise.onPossiblyUnhandledException = function(handler) { return function(handler) { possiblyUnhandledPromiseHandlers.push(handler); return { cancel: function() { possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1); } }; }(handler); }; ZalgoPromise.try = function(method, context, args) { if (method && "function" != typeof method && !method.call) throw new Error("Promise.try expected a function"); var result; startActive(); try { result = method.apply(context, args || []); } catch (err) { endActive(); return ZalgoPromise.reject(err); } endActive(); return ZalgoPromise.resolve(result); }; ZalgoPromise.delay = function(_delay) { return new ZalgoPromise((function(resolve) { setTimeout(resolve, _delay); })); }; ZalgoPromise.isPromise = function(value) { return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value); }; ZalgoPromise.flush = function() { return function(Zalgo) { var promise = flushPromise = flushPromise || new Zalgo; flushActive(); return promise; }(ZalgoPromise); }; return ZalgoPromise; }(); function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return getActualProtocol(win); } function isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === getProtocol(win); } function utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function getOpener(win) { void 0 === win && (win = window); if (win && !utils_getParent(win)) try { return win.opener; } catch (err) {} } function canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = utils_getParent(win); return parent && canReadFromWindow() ? getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function getDomain(win) { void 0 === win && (win = window); var domain = getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (isAboutProtocol(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === getProtocol(win); }(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (getActualDomain(win) === getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (isAboutProtocol(win) && canReadFromWindow()) return !0; if (getDomain(window) === getDomain(win)) return !0; } catch (err) {} return !1; } function assertSameDomain(win) { if (!isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (utils_getParent(win) === win) return win; try { if (isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (utils_getParent(frame) === frame) return frame; } } function getAllFramesInWindow(win) { var top = getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], getAllChildFrames(win))); return result; } var iframeWindows = []; var iframeFrames = []; function isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || err.message !== IE_WIN_ACCESS_ERROR; } if (allowMock && isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(iframeWindows, win); if (-1 !== iframeIndex) { var frame = iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function getAncestor(win) { void 0 === win && (win = window); return getOpener(win = win || window) || utils_getParent(win) || void 0; } function anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some((function(subpattern) { return matchDomain(subpattern, origin); }))); } function isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function getFrameForWindow(win) { if (isSameDomain(win)) return assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { var frame = _document$querySelect2[_i21]; if (frame && frame.contentWindow && frame.contentWindow === win) return frame; } } function closeWindow(win) { if (function(win) { void 0 === win && (win = window); return Boolean(utils_getParent(win)); }(win)) { var frame = getFrameForWindow(win); if (frame && frame.parentElement) { frame.parentElement.removeChild(frame); return; } } try { win.close(); } catch (err) {} } function util_safeIndexOf(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; } var weakmap_CrossDomainSafeWeakMap = function() { function CrossDomainSafeWeakMap() { this.name = void 0; this.weakmap = void 0; this.keys = void 0; this.values = void 0; this.name = "__weakmap_" + (1e9 * Math.random() >>> 0) + "__"; if (function() { if ("undefined" == typeof WeakMap) return !1; if (void 0 === Object.freeze) return !1; try { var testWeakMap = new WeakMap; var testKey = {}; Object.freeze(testKey); testWeakMap.set(testKey, "__testvalue__"); return "__testvalue__" === testWeakMap.get(testKey); } catch (err) { return !1; } }()) try { this.weakmap = new WeakMap; } catch (err) {} this.keys = []; this.values = []; } var _proto = CrossDomainSafeWeakMap.prototype; _proto._cleanupClosedWindows = function() { var weakmap = this.weakmap; var keys = this.keys; for (var i = 0; i < keys.length; i++) { var value = keys[i]; if (isWindow(value) && isWindowClosed(value)) { if (weakmap) try { weakmap.delete(value); } catch (err) {} keys.splice(i, 1); this.values.splice(i, 1); i -= 1; } } }; _proto.isSafeToReadWrite = function(key) { return !isWindow(key); }; _proto.set = function(key, value) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.set(key, value); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var name = this.name; var entry = key[name]; entry && entry[0] === key ? entry[1] = value : Object.defineProperty(key, name, { value: [ key, value ], writable: !0 }); return; } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var values = this.values; var index = util_safeIndexOf(keys, key); if (-1 === index) { keys.push(key); values.push(value); } else values[index] = value; }; _proto.get = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return weakmap.get(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return entry && entry[0] === key ? entry[1] : void 0; } catch (err) {} this._cleanupClosedWindows(); var index = util_safeIndexOf(this.keys, key); if (-1 !== index) return this.values[index]; }; _proto.delete = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.delete(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; entry && entry[0] === key && (entry[0] = entry[1] = void 0); } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var index = util_safeIndexOf(keys, key); if (-1 !== index) { keys.splice(index, 1); this.values.splice(index, 1); } }; _proto.has = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return !0; } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return !(!entry || entry[0] !== key); } catch (err) {} this._cleanupClosedWindows(); return -1 !== util_safeIndexOf(this.keys, key); }; _proto.getOrSet = function(key, getter) { if (this.has(key)) return this.get(key); var value = getter(); this.set(key, value); return value; }; return CrossDomainSafeWeakMap; }(); function _getPrototypeOf(o) { return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) { return o.__proto__ || Object.getPrototypeOf(o); })(o); } function _isNativeReflectConstruct() { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { Date.prototype.toString.call(Reflect.construct(Date, [], (function() {}))); return !0; } catch (e) { return !1; } } function construct_construct(Parent, args, Class) { return (construct_construct = _isNativeReflectConstruct() ? Reflect.construct : function(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var instance = new (Function.bind.apply(Parent, a)); Class && _setPrototypeOf(instance, Class.prototype); return instance; }).apply(null, arguments); } function wrapNativeSuper_wrapNativeSuper(Class) { var _cache = "function" == typeof Map ? new Map : void 0; return (wrapNativeSuper_wrapNativeSuper = function(Class) { if (null === Class || !(fn = Class, -1 !== Function.toString.call(fn).indexOf("[native code]"))) return Class; var fn; if ("function" != typeof Class) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== _cache) { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct_construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }); return _setPrototypeOf(Wrapper, Class); })(Class); } function isElement(element) { var passed = !1; try { (element instanceof window.Element || null !== element && "object" == typeof element && 1 === element.nodeType && "object" == typeof element.style && "object" == typeof element.ownerDocument) && (passed = !0); } catch (_) {} return passed; } function getFunctionName(fn) { return fn.name || fn.__name__ || fn.displayName || "anonymous"; } function setFunctionName(fn, name) { try { delete fn.name; fn.name = name; } catch (err) {} fn.__name__ = fn.displayName = name; return fn; } function base64encode(str) { if ("function" == typeof btoa) return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (function(m, p1) { return String.fromCharCode(parseInt(p1, 16)); }))).replace(/[=]/g, ""); if ("undefined" != typeof Buffer) return Buffer.from(str, "utf8").toString("base64").replace(/[=]/g, ""); throw new Error("Can not find window.btoa or Buffer"); } function uniqueID() { var chars = "0123456789abcdef"; return "uid_" + "xxxxxxxxxx".replace(/./g, (function() { return chars.charAt(Math.floor(Math.random() * chars.length)); })) + "_" + base64encode((new Date).toISOString().slice(11, 19).replace("T", ".")).replace(/[^a-zA-Z0-9]/g, "").toLowerCase(); } var objectIDs; function serializeArgs(args) { try { return JSON.stringify([].slice.call(args), (function(subkey, val) { return "function" == typeof val ? "memoize[" + function(obj) { objectIDs = objectIDs || new weakmap_CrossDomainSafeWeakMap; if (null == obj || "object" != typeof obj && "function" != typeof obj) throw new Error("Invalid object"); var uid = objectIDs.get(obj); if (!uid) { uid = typeof obj + ":" + uniqueID(); objectIDs.set(obj, uid); } return uid; }(val) + "]" : isElement(val) ? {} : val; })); } catch (err) { throw new Error("Arguments not serializable -- can not be used to memoize"); } } function getEmptyObject() { return {}; } var memoizeGlobalIndex = 0; var memoizeGlobalIndexValidFrom = 0; function memoize(method, options) { void 0 === options && (options = {}); var _options$thisNamespac = options.thisNamespace, thisNamespace = void 0 !== _options$thisNamespac && _options$thisNamespac, cacheTime = options.time; var simpleCache; var thisCache; var memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; var memoizedFunction = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; if (memoizeIndex < memoizeGlobalIndexValidFrom) { simpleCache = null; thisCache = null; memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; } var cache; cache = thisNamespace ? (thisCache = thisCache || new weakmap_CrossDomainSafeWeakMap).getOrSet(this, getEmptyObject) : simpleCache = simpleCache || {}; var cacheKey; try { cacheKey = serializeArgs(args); } catch (_unused) { return method.apply(this, arguments); } var cacheResult = cache[cacheKey]; if (cacheResult && cacheTime && Date.now() - cacheResult.time < cacheTime) { delete cache[cacheKey]; cacheResult = null; } if (cacheResult) return cacheResult.value; var time = Date.now(); var value = method.apply(this, arguments); cache[cacheKey] = { time: time, value: value }; return value; }; memoizedFunction.reset = function() { simpleCache = null; thisCache = null; }; return setFunctionName(memoizedFunction, (options.name || getFunctionName(method)) + "::memoized"); } memoize.clear = function() { memoizeGlobalIndexValidFrom = memoizeGlobalIndex; }; function memoizePromise(method) { var cache = {}; function memoizedPromiseFunction() { var _arguments = arguments, _this = this; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; var key = serializeArgs(args); if (cache.hasOwnProperty(key)) return cache[key]; cache[key] = promise_ZalgoPromise.try((function() { return method.apply(_this, _arguments); })).finally((function() { delete cache[key]; })); return cache[key]; } memoizedPromiseFunction.reset = function() { cache = {}; }; return setFunctionName(memoizedPromiseFunction, getFunctionName(method) + "::promiseMemoized"); } function src_util_noop() {} function once(method) { var called = !1; return setFunctionName((function() { if (!called) { called = !0; return method.apply(this, arguments); } }), getFunctionName(method) + "::once"); } function stringifyError(err, level) { void 0 === level && (level = 1); if (level >= 3) return "stringifyError stack overflow"; try { if (!err) return ""; if ("string" == typeof err) return err; if (err instanceof Error) { var stack = err && err.stack; var message = err && err.message; if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + "\n" + stack; if (stack) return stack; if (message) return message; } return err && err.toString && "function" == typeof err.toString ? err.toString() : {}.toString.call(err); } catch (newErr) { return "Error while stringifying error: " + stringifyError(newErr, level + 1); } } function stringify(item) { return "string" == typeof item ? item : item && item.toString && "function" == typeof item.toString ? item.toString() : {}.toString.call(item); } function extend(obj, source) { if (!source) return obj; if (Object.assign) return Object.assign(obj, source); for (var key in source) source.hasOwnProperty(key) && (obj[key] = source[key]); return obj; } memoize((function(obj) { if (Object.values) return Object.values(obj); var result = []; for (var key in obj) obj.hasOwnProperty(key) && result.push(obj[key]); return result; })); function identity(item) { return item; } function safeInterval(method, time) { var timeout; !function loop() { timeout = setTimeout((function() { method(); loop(); }), time); }(); return { cancel: function() { clearTimeout(timeout); } }; } function dasherizeToCamel(string) { return string.replace(/-([a-z])/g, (function(g) { return g[1].toUpperCase(); })); } function defineLazyProp(obj, key, getter) { if (Array.isArray(obj)) { if ("number" != typeof key) throw new TypeError("Array key must be number"); } else if ("object" == typeof obj && null !== obj && "string" != typeof key) throw new TypeError("Object key must be string"); Object.defineProperty(obj, key, { configurable: !0, enumerable: !0, get: function() { delete obj[key]; var value = getter(); obj[key] = value; return value; }, set: function(value) { delete obj[key]; obj[key] = value; } }); } function arrayFrom(item) { return [].slice.call(item); } function isObjectObject(obj) { return "object" == typeof (item = obj) && null !== item && "[object Object]" === {}.toString.call(obj); var item; } function isPlainObject(obj) { if (!isObjectObject(obj)) return !1; var constructor = obj.constructor; if ("function" != typeof constructor) return !1; var prototype = constructor.prototype; return !!isObjectObject(prototype) && !!prototype.hasOwnProperty("isPrototypeOf"); } function replaceObject(item, replacer, fullKey) { void 0 === fullKey && (fullKey = ""); if (Array.isArray(item)) { var length = item.length; var result = []; var _loop2 = function(i) { defineLazyProp(result, i, (function() { var itemKey = fullKey ? fullKey + "." + i : "" + i; var child = replacer(item[i], i, itemKey); (isPlainObject(child) || Array.isArray(child)) && (child = replaceObject(child, replacer, itemKey)); return child; })); }; for (var i = 0; i < length; i++) _loop2(i); return result; } if (isPlainObject(item)) { var _result = {}; var _loop3 = function(key) { if (!item.hasOwnProperty(key)) return "continue"; defineLazyProp(_result, key, (function() { var itemKey = fullKey ? fullKey + "." + key : "" + key; var child = replacer(item[key], key, itemKey); (isPlainObject(child) || Array.isArray(child)) && (child = replaceObject(child, replacer, itemKey)); return child; })); }; for (var key in item) _loop3(key); return _result; } throw new Error("Pass an object or array"); } function isDefined(value) { return null != value; } function util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function util_getOrSet(obj, key, getter) { if (obj.hasOwnProperty(key)) return obj[key]; var val = getter(); obj[key] = val; return val; } function cleanup(obj) { var tasks = []; var cleaned = !1; var cleanErr; var cleaner = { set: function(name, item) { if (!cleaned) { obj[name] = item; cleaner.register((function() { delete obj[name]; })); } return item; }, register: function(method) { var task = once((function() { return method(cleanErr); })); cleaned ? method(cleanErr) : tasks.push(task); return { cancel: function() { var index = tasks.indexOf(task); -1 !== index && tasks.splice(index, 1); } }; }, all: function(err) { cleanErr = err; var results = []; cleaned = !0; for (;tasks.length; ) { var task = tasks.shift(); results.push(task()); } return promise_ZalgoPromise.all(results).then(src_util_noop); } }; return cleaner; } function assertExists(name, thing) { if (null == thing) throw new Error("Expected " + name + " to be present"); return thing; } var util_ExtendableError = function(_Error) { _inheritsLoose(ExtendableError, _Error); function ExtendableError(message) { var _this6; (_this6 = _Error.call(this, message) || this).name = _this6.constructor.name; "function" == typeof Error.captureStackTrace ? Error.captureStackTrace(function(self) { if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; }(_this6), _this6.constructor) : _this6.stack = new Error(message).stack; return _this6; } return ExtendableError; }(wrapNativeSuper_wrapNativeSuper(Error)); function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); return body; } function isDocumentReady() { return Boolean(document.body) && "complete" === document.readyState; } function isDocumentInteractive() { return Boolean(document.body) && "interactive" === document.readyState; } function urlEncode(str) { return encodeURIComponent(str); } memoize((function() { return new promise_ZalgoPromise((function(resolve) { if (isDocumentReady() || isDocumentInteractive()) return resolve(); var interval = setInterval((function() { if (isDocumentReady() || isDocumentInteractive()) { clearInterval(interval); return resolve(); } }), 10); })); })); function parseQuery(queryString) { return function(method, logic, args) { void 0 === args && (args = []); var cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {}; var key = serializeArgs(args); return cache.hasOwnProperty(key) ? cache[key] : cache[key] = function() { var params = {}; if (!queryString) return params; if (-1 === queryString.indexOf("=")) return params; for (var _i2 = 0, _queryString$split2 = queryString.split("&"); _i2 < _queryString$split2.length; _i2++) { var pair = _queryString$split2[_i2]; (pair = pair.split("="))[0] && pair[1] && (params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1])); } return params; }.apply(void 0, args); }(parseQuery, 0, [ queryString ]); } function extendQuery(originalQuery, props) { void 0 === props && (props = {}); return props && Object.keys(props).length ? function(obj) { void 0 === obj && (obj = {}); return Object.keys(obj).filter((function(key) { return "string" == typeof obj[key] || "boolean" == typeof obj[key]; })).map((function(key) { var val = obj[key]; if ("string" != typeof val && "boolean" != typeof val) throw new TypeError("Invalid type for query"); return urlEncode(key) + "=" + urlEncode(val.toString()); })).join("&"); }(_extends({}, parseQuery(originalQuery), props)) : originalQuery; } function appendChild(container, child) { container.appendChild(child); } function getElementSafe(id, doc) { void 0 === doc && (doc = document); return isElement(id) ? id : "string" == typeof id ? doc.querySelector(id) : void 0; } function elementReady(id) { return new promise_ZalgoPromise((function(resolve, reject) { var name = stringify(id); var el = getElementSafe(id); if (el) return resolve(el); if (isDocumentReady()) return reject(new Error("Document is ready and element " + name + " does not exist")); var interval = setInterval((function() { if (el = getElementSafe(id)) { resolve(el); clearInterval(interval); } else if (isDocumentReady()) { clearInterval(interval); return reject(new Error("Document is ready and element " + name + " does not exist")); } }), 10); })); } var dom_PopupOpenError = function(_ExtendableError) { _inheritsLoose(PopupOpenError, _ExtendableError); function PopupOpenError() { return _ExtendableError.apply(this, arguments) || this; } return PopupOpenError; }(util_ExtendableError); var awaitFrameLoadPromises; function awaitFrameLoad(frame) { if ((awaitFrameLoadPromises = awaitFrameLoadPromises || new weakmap_CrossDomainSafeWeakMap).has(frame)) { var _promise = awaitFrameLoadPromises.get(frame); if (_promise) return _promise; } var promise = new promise_ZalgoPromise((function(resolve, reject) { frame.addEventListener("load", (function() { !function(frame) { !function() { for (var i = 0; i < iframeWindows.length; i++) { var closed = !1; try { closed = iframeWindows[i].closed; } catch (err) {} if (closed) { iframeFrames.splice(i, 1); iframeWindows.splice(i, 1); } } }(); if (frame && frame.contentWindow) try { iframeWindows.push(frame.contentWindow); iframeFrames.push(frame); } catch (err) {} }(frame); resolve(frame); })); frame.addEventListener("error", (function(err) { frame.contentWindow ? resolve(frame) : reject(err); })); })); awaitFrameLoadPromises.set(frame, promise); return promise; } function awaitFrameWindow(frame) { return awaitFrameLoad(frame).then((function(loadedFrame) { if (!loadedFrame.contentWindow) throw new Error("Could not find window in iframe"); return loadedFrame.contentWindow; })); } function dom_iframe(options, container) { void 0 === options && (options = {}); var style = options.style || {}; var frame = function(tag, options, container) { void 0 === tag && (tag = "div"); void 0 === options && (options = {}); tag = tag.toLowerCase(); var element = document.createElement(tag); options.style && extend(element.style, options.style); options.class && (element.className = options.class.join(" ")); options.id && element.setAttribute("id", options.id); if (options.attributes) for (var _i10 = 0, _Object$keys2 = Object.keys(options.attributes); _i10 < _Object$keys2.length; _i10++) { var key = _Object$keys2[_i10]; element.setAttribute(key, options.attributes[key]); } options.styleSheet && function(el, styleText, doc) { void 0 === doc && (doc = window.document); el.styleSheet ? el.styleSheet.cssText = styleText : el.appendChild(doc.createTextNode(styleText)); }(element, options.styleSheet); if (options.html) { if ("iframe" === tag) throw new Error("Iframe html can not be written unless container provided and iframe in DOM"); element.innerHTML = options.html; } return element; }("iframe", { attributes: _extends({ allowTransparency: "true" }, options.attributes || {}), style: _extends({ backgroundColor: "transparent", border: "none" }, style), html: options.html, class: options.class }); var isIE = window.navigator.userAgent.match(/MSIE|Edge/i); frame.hasAttribute("id") || frame.setAttribute("id", uniqueID()); awaitFrameLoad(frame); container && function(id, doc) { void 0 === doc && (doc = document); var element = getElementSafe(id, doc); if (element) return element; throw new Error("Can not find element: " + stringify(id)); }(container).appendChild(frame); (options.url || isIE) && frame.setAttribute("src", options.url || "about:blank"); return frame; } function addEventListener(obj, event, handler) { obj.addEventListener(event, handler); return { cancel: function() { obj.removeEventListener(event, handler); } }; } function showElement(element) { element.style.setProperty("display", ""); } function hideElement(element) { element.style.setProperty("display", "none", "important"); } function destroyElement(element) { element && element.parentNode && element.parentNode.removeChild(element); } function isElementClosed(el) { return !(el && el.parentNode && el.ownerDocument && el.ownerDocument.documentElement && el.ownerDocument.documentElement.contains(el)); } function onResize(el, handler, _temp) { var _ref2 = void 0 === _temp ? {} : _temp, _ref2$width = _ref2.width, width = void 0 === _ref2$width || _ref2$width, _ref2$height = _ref2.height, height = void 0 === _ref2$height || _ref2$height, _ref2$interval = _ref2.interval, interval = void 0 === _ref2$interval ? 100 : _ref2$interval, _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win; var currentWidth = el.offsetWidth; var currentHeight = el.offsetHeight; var canceled = !1; handler({ width: currentWidth, height: currentHeight }); var check = function() { if (!canceled && function(el) { return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length); }(el)) { var newWidth = el.offsetWidth; var newHeight = el.offsetHeight; (width && newWidth !== currentWidth || height && newHeight !== currentHeight) && handler({ width: newWidth, height: newHeight }); currentWidth = newWidth; currentHeight = newHeight; } }; var observer; var timeout; win.addEventListener("resize", check); if (void 0 !== win.ResizeObserver) { (observer = new win.ResizeObserver(check)).observe(el); timeout = safeInterval(check, 10 * interval); } else if (void 0 !== win.MutationObserver) { (observer = new win.MutationObserver(check)).observe(el, { attributes: !0, childList: !0, subtree: !0, characterData: !1 }); timeout = safeInterval(check, 10 * interval); } else timeout = safeInterval(check, interval); return { cancel: function() { canceled = !0; observer.disconnect(); window.removeEventListener("resize", check); timeout.cancel(); } }; } function isShadowElement(element) { for (;element.parentNode; ) element = element.parentNode; return "[object ShadowRoot]" === element.toString(); } var currentScript = "undefined" != typeof document ? document.currentScript : null; var getCurrentScript = memoize((function() { if (currentScript) return currentScript; if (currentScript = function() { try { var stack = function() { try { throw new Error("_"); } catch (err) { return err.stack || ""; } }(); var stackDetails = /.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(stack); var scriptLocation = stackDetails && stackDetails[1]; if (!scriptLocation) return; for (var _i22 = 0, _Array$prototype$slic2 = [].slice.call(document.getElementsByTagName("script")).reverse(); _i22 < _Array$prototype$slic2.length; _i22++) { var script = _Array$prototype$slic2[_i22]; if (script.src && script.src === scriptLocation) return script; } } catch (err) {} }()) return currentScript; throw new Error("Can not determine current script"); })); var currentUID = uniqueID(); memoize((function() { var script; try { script = getCurrentScript(); } catch (err) { return currentUID; } var uid = script.getAttribute("data-uid"); if (uid && "string" == typeof uid) return uid; if ((uid = script.getAttribute("data-uid-auto")) && "string" == typeof uid) return uid; if (script.src) { var hashedString = function(str) { var hash = ""; for (var i = 0; i < str.length; i++) { var total = str[i].charCodeAt(0) * i; str[i + 1] && (total += str[i + 1].charCodeAt(0) * (i - 1)); hash += String.fromCharCode(97 + Math.abs(total) % 26); } return hash; }(JSON.stringify({ src: script.src, dataset: script.dataset })); uid = "uid_" + hashedString.slice(hashedString.length - 30); } else uid = uniqueID(); script.setAttribute("data-uid-auto", uid); return uid; })); function toPx(val) { return function(val) { if ("number" == typeof val) return val; var match = val.match(/^([0-9]+)(px|%)$/); if (!match) throw new Error("Could not match css value from " + val); return parseInt(match[1], 10); }(val) + "px"; } function toCSS(val) { return "number" == typeof val ? toPx(val) : "string" == typeof (str = val) && /^[0-9]+%$/.test(str) ? val : toPx(val); var str; } function global_getGlobal(win) { void 0 === win && (win = window); var globalKey = "__post_robot_10_0_46__"; return win !== window ? win[globalKey] : win[globalKey] = win[globalKey] || {}; } var getObj = function() { return {}; }; function globalStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return util_getOrSet(global_getGlobal(), key, (function() { var store = defStore(); return { has: function(storeKey) { return store.hasOwnProperty(storeKey); }, get: function(storeKey, defVal) { return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal; }, set: function(storeKey, val) { store[storeKey] = val; return val; }, del: function(storeKey) { delete store[storeKey]; }, getOrSet: function(storeKey, getter) { return util_getOrSet(store, storeKey, getter); }, reset: function() { store = defStore(); }, keys: function() { return Object.keys(store); } }; })); } var WildCard = function() {}; function getWildcard() { var global = global_getGlobal(); global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard; return global.WINDOW_WILDCARD; } function windowStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return globalStore("windowStore").getOrSet(key, (function() { var winStore = new weakmap_CrossDomainSafeWeakMap; var getStore = function(win) { return winStore.getOrSet(win, defStore); }; return { has: function(win) { return getStore(win).hasOwnProperty(key); }, get: function(win, defVal) { var store = getStore(win); return store.hasOwnProperty(key) ? store[key] : defVal; }, set: function(win, val) { getStore(win)[key] = val; return val; }, del: function(win) { delete getStore(win)[key]; }, getOrSet: function(win, getter) { return util_getOrSet(getStore(win), key, getter); } }; })); } function getInstanceID() { return globalStore("instance").getOrSet("instanceID", uniqueID); } function resolveHelloPromise(win, _ref) { var domain = _ref.domain; var helloPromises = windowStore("helloPromises"); var existingPromise = helloPromises.get(win); existingPromise && existingPromise.resolve({ domain: domain }); var newPromise = promise_ZalgoPromise.resolve({ domain: domain }); helloPromises.set(win, newPromise); return newPromise; } function sayHello(win, _ref4) { return (0, _ref4.send)(win, "postrobot_hello", { instanceID: getInstanceID() }, { domain: "*", timeout: -1 }).then((function(_ref5) { var origin = _ref5.origin, instanceID = _ref5.data.instanceID; resolveHelloPromise(win, { domain: origin }); return { win: win, domain: origin, instanceID: instanceID }; })); } function getWindowInstanceID(win, _ref6) { var send = _ref6.send; return windowStore("windowInstanceIDPromises").getOrSet(win, (function() { return sayHello(win, { send: send }).then((function(_ref7) { return _ref7.instanceID; })); })); } function markWindowKnown(win) { windowStore("knownWindows").set(win, !0); } function isSerializedType(item) { return "object" == typeof item && null !== item && "string" == typeof item.__type__; } function determineType(val) { return void 0 === val ? "undefined" : null === val ? "null" : Array.isArray(val) ? "array" : "function" == typeof val ? "function" : "object" == typeof val ? val instanceof Error ? "error" : "function" == typeof val.then ? "promise" : "[object RegExp]" === {}.toString.call(val) ? "regex" : "[object Date]" === {}.toString.call(val) ? "date" : "object" : "string" == typeof val ? "string" : "number" == typeof val ? "number" : "boolean" == typeof val ? "boolean" : void 0; } function serializeType(type, val) { return { __type__: type, __val__: val }; } var _SERIALIZER; var SERIALIZER = ((_SERIALIZER = {}).function = function() {}, _SERIALIZER.error = function(_ref) { return serializeType("error", { message: _ref.message, stack: _ref.stack, code: _ref.code, data: _ref.data }); }, _SERIALIZER.promise = function() {}, _SERIALIZER.regex = function(val) { return serializeType("regex", val.source); }, _SERIALIZER.date = function(val) { return serializeType("date", val.toJSON()); }, _SERIALIZER.array = function(val) { return val; }, _SERIALIZER.object = function(val) { return val; }, _SERIALIZER.string = function(val) { return val; }, _SERIALIZER.number = function(val) { return val; }, _SERIALIZER.boolean = function(val) { return val; }, _SERIALIZER.null = function(val) { return val; }, _SERIALIZER[void 0] = function(val) { return serializeType("undefined", val); }, _SERIALIZER); var defaultSerializers = {}; var _DESERIALIZER; var DESERIALIZER = ((_DESERIALIZER = {}).function = function() { throw new Error("Function serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.error = function(_ref2) { var stack = _ref2.stack, code = _ref2.code, data = _ref2.data; var error = new Error(_ref2.message); error.code = code; data && (error.data = data); error.stack = stack + "\n\n" + error.stack; return error; }, _DESERIALIZER.promise = function() { throw new Error("Promise serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.regex = function(val) { return new RegExp(val); }, _DESERIALIZER.date = function(val) { return new Date(val); }, _DESERIALIZER.array = function(val) { return val; }, _DESERIALIZER.object = function(val) { return val; }, _DESERIALIZER.string = function(val) { return val; }, _DESERIALIZER.number = function(val) { return val; }, _DESERIALIZER.boolean = function(val) { return val; }, _DESERIALIZER.null = function(val) { return val; }, _DESERIALIZER[void 0] = function() {}, _DESERIALIZER); var defaultDeserializers = {}; new promise_ZalgoPromise((function(resolve) { if (window.document && window.document.body) return resolve(window.document.body); var interval = setInterval((function() { if (window.document && window.document.body) { clearInterval(interval); return resolve(window.document.body); } }), 10); })); function cleanupProxyWindows() { var idToProxyWindow = globalStore("idToProxyWindow"); for (var _i2 = 0, _idToProxyWindow$keys2 = idToProxyWindow.keys(); _i2 < _idToProxyWindow$keys2.length; _i2++) { var id = _idToProxyWindow$keys2[_i2]; idToProxyWindow.get(id).shouldClean() && idToProxyWindow.del(id); } } function getSerializedWindow(winPromise, _ref) { var send = _ref.send, _ref$id = _ref.id, id = void 0 === _ref$id ? uniqueID() : _ref$id; var windowNamePromise = winPromise.then((function(win) { if (isSameDomain(win)) return assertSameDomain(win).name; })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); return getOpener(window) ? "popup" : "iframe"; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); var getName = function() { return winPromise.then((function(win) { if (!isWindowClosed(win)) return isSameDomain(win) ? assertSameDomain(win).name : windowNamePromise; })); }; return { id: id, getType: function() { return windowTypePromise; }, getInstanceID: memoizePromise((function() { return winPromise.then((function(win) { return getWindowInstanceID(win, { send: send }); })); })), close: function() { return winPromise.then(closeWindow); }, getName: getName, focus: function() { return winPromise.then((function(win) { win.focus(); })); }, isClosed: function() { return winPromise.then((function(win) { return isWindowClosed(win); })); }, setLocation: function(href, opts) { void 0 === opts && (opts = {}); return winPromise.then((function(win) { var domain = window.location.protocol + "//" + window.location.host; var _opts$method = opts.method, method = void 0 === _opts$method ? "get" : _opts$method, body = opts.body; if (0 === href.indexOf("/")) href = "" + domain + href; else if (!href.match(/^https?:\/\//) && 0 !== href.indexOf(domain)) throw new Error("Expected url to be http or https url, or absolute path, got " + JSON.stringify(href)); if ("post" === method) return getName().then((function(name) { if (!name) throw new Error("Can not post to window without target name"); !function(_ref3) { var url = _ref3.url, target = _ref3.target, body = _ref3.body, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "post" : _ref3$method; var form = document.createElement("form"); form.setAttribute("target", target); form.setAttribute("method", method); form.setAttribute("action", url); form.style.display = "none"; if (body) for (var _i24 = 0, _Object$keys4 = Object.keys(body); _i24 < _Object$keys4.length; _i24++) { var _body$key; var key = _Object$keys4[_i24]; var input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", null == (_body$key = body[key]) ? void 0 : _body$key.toString()); form.appendChild(input); } getBody().appendChild(form); form.submit(); getBody().removeChild(form); }({ url: href, target: name, method: method, body: body }); })); if ("get" !== method) throw new Error("Unsupported method: " + method); if (isSameDomain(win)) try { if (win.location && "function" == typeof win.location.replace) { win.location.replace(href); return; } } catch (err) {} win.location = href; })); }, setName: function(name) { return winPromise.then((function(win) { var sameDomain = isSameDomain(win); var frame = getFrameForWindow(win); if (!sameDomain) throw new Error("Can not set name for cross-domain window: " + name); assertSameDomain(win).name = name; frame && frame.setAttribute("name", name); windowNamePromise = promise_ZalgoPromise.resolve(name); })); } }; } var window_ProxyWindow = function() { function ProxyWindow(_ref2) { var send = _ref2.send, win = _ref2.win, serializedWindow = _ref2.serializedWindow; this.id = void 0; this.isProxyWindow = !0; this.serializedWindow = void 0; this.actualWindow = void 0; this.actualWindowPromise = void 0; this.send = void 0; this.name = void 0; this.actualWindowPromise = new promise_ZalgoPromise; this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send: send }); globalStore("idToProxyWindow").set(this.getID(), this); win && this.setWindow(win, { send: send }); } var _proto = ProxyWindow.prototype; _proto.getID = function() { return this.serializedWindow.id; }; _proto.getType = function() { return this.serializedWindow.getType(); }; _proto.isPopup = function() { return this.getType().then((function(type) { return "popup" === type; })); }; _proto.setLocation = function(href, opts) { var _this = this; return this.serializedWindow.setLocation(href, opts).then((function() { return _this; })); }; _proto.getName = function() { return this.serializedWindow.getName(); }; _proto.setName = function(name) { var _this2 = this; return this.serializedWindow.setName(name).then((function() { return _this2; })); }; _proto.close = function() { var _this3 = this; return this.serializedWindow.close().then((function() { return _this3; })); }; _proto.focus = function() { var _this4 = this; var isPopupPromise = this.isPopup(); var getNamePromise = this.getName(); var reopenPromise = promise_ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then((function(_ref3) { var name = _ref3.name; _ref3.isPopup && name && window.open("", name, "noopener"); })); var focusPromise = this.serializedWindow.focus(); return promise_ZalgoPromise.all([ reopenPromise, focusPromise ]).then((function() { return _this4; })); }; _proto.isClosed = function() { return this.serializedWindow.isClosed(); }; _proto.getWindow = function() { return this.actualWindow; }; _proto.setWindow = function(win, _ref4) { var send = _ref4.send; this.actualWindow = win; this.actualWindowPromise.resolve(this.actualWindow); this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send: send, id: this.getID() }); windowStore("winToProxyWindow").set(win, this); }; _proto.awaitWindow = function() { return this.actualWindowPromise; }; _proto.matchWindow = function(win, _ref5) { var _this5 = this; var send = _ref5.send; return promise_ZalgoPromise.try((function() { return _this5.actualWindow ? win === _this5.actualWindow : promise_ZalgoPromise.hash({ proxyInstanceID: _this5.getInstanceID(), knownWindowInstanceID: getWindowInstanceID(win, { send: send }) }).then((function(_ref6) { var match = _ref6.proxyInstanceID === _ref6.knownWindowInstanceID; match && _this5.setWindow(win, { send: send }); return match; })); })); }; _proto.unwrap = function() { return this.actualWindow || this; }; _proto.getInstanceID = function() { return this.serializedWindow.getInstanceID(); }; _proto.shouldClean = function() { return Boolean(this.actualWindow && isWindowClosed(this.actualWindow)); }; _proto.serialize = function() { return this.serializedWindow; }; ProxyWindow.unwrap = function(win) { return ProxyWindow.isProxyWindow(win) ? win.unwrap() : win; }; ProxyWindow.serialize = function(win, _ref7) { var send = _ref7.send; cleanupProxyWindows(); return ProxyWindow.toProxyWindow(win, { send: send }).serialize(); }; ProxyWindow.deserialize = function(serializedWindow, _ref8) { var send = _ref8.send; cleanupProxyWindows(); return globalStore("idToProxyWindow").get(serializedWindow.id) || new ProxyWindow({ serializedWindow: serializedWindow, send: send }); }; ProxyWindow.isProxyWindow = function(obj) { return Boolean(obj && !isWindow(obj) && obj.isProxyWindow); }; ProxyWindow.toProxyWindow = function(win, _ref9) { var send = _ref9.send; cleanupProxyWindows(); if (ProxyWindow.isProxyWindow(win)) return win; var actualWindow = win; return windowStore("winToProxyWindow").get(actualWindow) || new ProxyWindow({ win: actualWindow, send: send }); }; return ProxyWindow; }(); function addMethod(id, val, name, source, domain) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); if (window_ProxyWindow.isProxyWindow(source)) proxyWindowMethods.set(id, { val: val, name: name, domain: domain, source: source }); else { proxyWindowMethods.del(id); methodStore.getOrSet(source, (function() { return {}; }))[id] = { domain: domain, name: name, val: val, source: source }; } } function lookupMethod(source, id) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); return methodStore.getOrSet(source, (function() { return {}; }))[id] || proxyWindowMethods.get(id); } function function_serializeFunction(destination, domain, val, key, _ref3) { on = (_ref = { on: _ref3.on, send: _ref3.send }).on, send = _ref.send, globalStore("builtinListeners").getOrSet("functionCalls", (function() { return on("postrobot_method", { domain: "*" }, (function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; var id = data.id, name = data.name; var meth = lookupMethod(source, id); if (!meth) throw new Error("Could not find method '" + name + "' with id: " + data.id + " in " + getDomain(window)); var methodSource = meth.source, domain = meth.domain, val = meth.val; return promise_ZalgoPromise.try((function() { if (!matchDomain(domain, origin)) throw new Error("Method '" + data.name + "' domain " + JSON.stringify(util_isRegex(meth.domain) ? meth.domain.source : meth.domain) + " does not match origin " + origin + " in " + getDomain(window)); if (window_ProxyWindow.isProxyWindow(methodSource)) return methodSource.matchWindow(source, { send: send }).then((function(match) { if (!match) throw new Error("Method call '" + data.name + "' failed - proxy window does not match source in " + getDomain(window)); })); })).then((function() { return val.apply({ source: source, origin: origin }, data.args); }), (function(err) { return promise_ZalgoPromise.try((function() { if (val.onError) return val.onError(err); })).then((function() { err.stack && (err.stack = "Remote call to " + name + "(" + function(args) { void 0 === args && (args = []); return arrayFrom(args).map((function(arg) { return "string" == typeof arg ? "'" + arg + "'" : void 0 === arg ? "undefined" : null === arg ? "null" : "boolean" == typeof arg ? arg.toString() : Array.isArray(arg) ? "[ ... ]" : "object" == typeof arg ? "{ ... }" : "function" == typeof arg ? "() => { ... }" : "<" + typeof arg + ">"; })).join(", "); }(data.args) + ") failed\n\n" + err.stack); throw err; })); })).then((function(result) { return { result: result, id: id, name: name }; })); })); })); var _ref, on, send; var id = val.__id__ || uniqueID(); destination = window_ProxyWindow.unwrap(destination); var name = val.__name__ || val.name || key; "string" == typeof name && "function" == typeof name.indexOf && 0 === name.indexOf("anonymous::") && (name = name.replace("anonymous::", key + "::")); if (window_ProxyWindow.isProxyWindow(destination)) { addMethod(id, val, name, destination, domain); destination.awaitWindow().then((function(win) { addMethod(id, val, name, win, domain); })); } else addMethod(id, val, name, destination, domain); return serializeType("cross_domain_function", { id: id, name: name }); } function serializeMessage(destination, domain, obj, _ref) { var _serialize; var on = _ref.on, send = _ref.send; return function(obj, serializers) { void 0 === serializers && (serializers = defaultSerializers); var result = JSON.stringify(obj, (function(key) { var val = this[key]; if (isSerializedType(this)) return val; var type = determineType(val); if (!type) return val; var serializer = serializers[type] || SERIALIZER[type]; return serializer ? serializer(val, key) : val; })); return void 0 === result ? "undefined" : result; }(obj, ((_serialize = {}).promise = function(val, key) { return function(destination, domain, val, key, _ref) { return serializeType("cross_domain_zalgo_promise", { then: function_serializeFunction(destination, domain, (function(resolve, reject) { return val.then(resolve, reject); }), key, { on: _ref.on, send: _ref.send }) }); }(destination, domain, val, key, { on: on, send: send }); }, _serialize.function = function(val, key) { return function_serializeFunction(destination, domain, val, key, { on: on, send: send }); }, _serialize.object = function(val) { return isWindow(val) || window_ProxyWindow.isProxyWindow(val) ? serializeType("cross_domain_window", window_ProxyWindow.serialize(val, { send: send })) : val; }, _serialize)); } function deserializeMessage(source, origin, message, _ref2) { var _deserialize; var send = _ref2.send; return function(str, deserializers) { void 0 === deserializers && (deserializers = defaultDeserializers); if ("undefined" !== str) return JSON.parse(str, (function(key, val) { if (isSerializedType(this)) return val; var type; var value; if (isSerializedType(val)) { type = val.__type__; value = val.__val__; } else { type = determineType(val); value = val; } if (!type) return value; var deserializer = deserializers[type] || DESERIALIZER[type]; return deserializer ? deserializer(value, key) : value; })); }(message, ((_deserialize = {}).cross_domain_zalgo_promise = function(serializedPromise) { return function(source, origin, _ref2) { return new promise_ZalgoPromise(_ref2.then); }(0, 0, serializedPromise); }, _deserialize.cross_domain_function = function(serializedFunction) { return function(source, origin, _ref4, _ref5) { var id = _ref4.id, name = _ref4.name; var send = _ref5.send; var getDeserializedFunction = function(opts) { void 0 === opts && (opts = {}); function crossDomainFunctionWrapper() { var _arguments = arguments; return window_ProxyWindow.toProxyWindow(source, { send: send }).awaitWindow().then((function(win) { var meth = lookupMethod(win, id); if (meth && meth.val !== crossDomainFunctionWrapper) return meth.val.apply({ source: window, origin: getDomain() }, _arguments); var _args = [].slice.call(_arguments); return opts.fireAndForget ? send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !0 }) : send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !1 }).then((function(res) { return res.data.result; })); })).catch((function(err) { throw err; })); } crossDomainFunctionWrapper.__name__ = name; crossDomainFunctionWrapper.__origin__ = origin; crossDomainFunctionWrapper.__source__ = source; crossDomainFunctionWrapper.__id__ = id; crossDomainFunctionWrapper.origin = origin; return crossDomainFunctionWrapper; }; var crossDomainFunctionWrapper = getDeserializedFunction(); crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: !0 }); return crossDomainFunctionWrapper; }(source, origin, serializedFunction, { send: send }); }, _deserialize.cross_domain_window = function(serializedWindow) { return window_ProxyWindow.deserialize(serializedWindow, { send: send }); }, _deserialize)); } var SEND_MESSAGE_STRATEGIES = {}; SEND_MESSAGE_STRATEGIES.postrobot_post_message = function(win, serializedMessage, domain) { 0 === domain.indexOf("file:") && (domain = "*"); win.postMessage(serializedMessage, domain); }; SEND_MESSAGE_STRATEGIES.postrobot_global = function(win, serializedMessage) { if (!function(win) { return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent; }(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser"); if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows"); if (!1 !== function(win1, win2) { var top1 = getTop(win1) || win1; var top2 = getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = getAllFramesInWindow(win1); var allFrames2 = getAllFramesInWindow(win2); if (anyMatch(allFrames1, allFrames2)) return !0; var opener1 = getOpener(top1); var opener2 = getOpener(top2); return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), !1; }(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); var foreignGlobal = global_getGlobal(win); if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window"); foreignGlobal.receiveMessage({ source: window, origin: getDomain(), data: serializedMessage }); }; function send_sendMessage(win, domain, message, _ref2) { var on = _ref2.on, send = _ref2.send; return promise_ZalgoPromise.try((function() { var domainBuffer = windowStore().getOrSet(win, (function() { return {}; })); domainBuffer.buffer = domainBuffer.buffer || []; domainBuffer.buffer.push(message); domainBuffer.flush = domainBuffer.flush || promise_ZalgoPromise.flush().then((function() { if (isWindowClosed(win)) throw new Error("Window is closed"); var serializedMessage = serializeMessage(win, domain, ((_ref = {}).__post_robot_10_0_46__ = domainBuffer.buffer || [], _ref), { on: on, send: send }); var _ref; delete domainBuffer.buffer; var strategies = Object.keys(SEND_MESSAGE_STRATEGIES); var errors = []; for (var _i2 = 0; _i2 < strategies.length; _i2++) { var strategyName = strategies[_i2]; try { SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain); } catch (err) { errors.push(err); } } if (errors.length === strategies.length) throw new Error("All post-robot messaging strategies failed:\n\n" + errors.map((function(err, i) { return i + ". " + stringifyError(err); })).join("\n\n")); })); return domainBuffer.flush.then((function() { delete domainBuffer.flush; })); })).then(src_util_noop); } function getResponseListener(hash) { return globalStore("responseListeners").get(hash); } function deleteResponseListener(hash) { globalStore("responseListeners").del(hash); } function isResponseListenerErrored(hash) { return globalStore("erroredResponseListeners").has(hash); } function getRequestListener(_ref) { var name = _ref.name, win = _ref.win, domain = _ref.domain; var requestListeners = windowStore("requestListeners"); "*" === win && (win = null); "*" === domain && (domain = null); if (!name) throw new Error("Name required to get request listener"); for (var _i4 = 0, _ref3 = [ win, getWildcard() ]; _i4 < _ref3.length; _i4++) { var winQualifier = _ref3[_i4]; if (winQualifier) { var nameListeners = requestListeners.get(winQualifier); if (nameListeners) { var domainListeners = nameListeners[name]; if (domainListeners) { if (domain && "string" == typeof domain) { if (domainListeners[domain]) return domainListeners[domain]; if (domainListeners.__domain_regex__) for (var _i6 = 0, _domainListeners$__DO2 = domainListeners.__domain_regex__; _i6 < _domainListeners$__DO2.length; _i6++) { var _domainListeners$__DO3 = _domainListeners$__DO2[_i6], listener = _domainListeners$__DO3.listener; if (matchDomain(_domainListeners$__DO3.regex, domain)) return listener; } } if (domainListeners["*"]) return domainListeners["*"]; } } } } } function handleRequest(source, origin, message, _ref) { var on = _ref.on, send = _ref.send; var options = getRequestListener({ name: message.name, win: source, domain: origin }); var logName = "postrobot_method" === message.name && message.data && "string" == typeof message.data.name ? message.data.name + "()" : message.name; function sendResponse(ack, data, error) { return promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_response", hash: message.hash, name: message.name, ack: ack, data: data, error: error }, { on: on, send: send }); } catch (err) { throw new Error("Send response message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })); } return promise_ZalgoPromise.all([ promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_ack", hash: message.hash, name: message.name }, { on: on, send: send }); } catch (err) { throw new Error("Send ack message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })), promise_ZalgoPromise.try((function() { if (!options) throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); return options.handler({ source: source, origin: origin, data: message.data }); })).then((function(data) { return sendResponse("success", data); }), (function(error) { return sendResponse("error", null, error); })) ]).then(src_util_noop).catch((function(err) { if (options && options.handleError) return options.handleError(err); throw err; })); } function handleAck(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); try { if (!matchDomain(options.domain, origin)) throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString()); if (source !== options.win) throw new Error("Ack source does not match registered window"); } catch (err) { options.promise.reject(err); } options.ack = !0; } } function handleResponse(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); if (!matchDomain(options.domain, origin)) throw new Error("Response origin " + origin + " does not match domain " + (pattern = options.domain, Array.isArray(pattern) ? "(" + pattern.join(" | ") + ")" : isRegex(pattern) ? "RegExp(" + pattern.toString() + ")" : pattern.toString())); var pattern; if (source !== options.win) throw new Error("Response source does not match registered window"); deleteResponseListener(message.hash); "error" === message.ack ? options.promise.reject(message.error) : "success" === message.ack && options.promise.resolve({ source: source, origin: origin, data: message.data }); } } function receive_receiveMessage(event, _ref2) { var on = _ref2.on, send = _ref2.send; var receivedMessages = globalStore("receivedMessages"); try { if (!window || window.closed || !event.source) return; } catch (err) { return; } var source = event.source, origin = event.origin; var messages = function(message, source, origin, _ref) { var on = _ref.on, send = _ref.send; var parsedMessage; try { parsedMessage = deserializeMessage(source, origin, message, { on: on, send: send }); } catch (err) { return; } if (parsedMessage && "object" == typeof parsedMessage && null !== parsedMessage) { var parseMessages = parsedMessage.__post_robot_10_0_46__; if (Array.isArray(parseMessages)) return parseMessages; } }(event.data, source, origin, { on: on, send: send }); if (messages) { markWindowKnown(source); for (var _i2 = 0; _i2 < messages.length; _i2++) { var message = messages[_i2]; if (receivedMessages.has(message.id)) return; receivedMessages.set(message.id, !0); if (isWindowClosed(source) && !message.fireAndForget) return; 0 === message.origin.indexOf("file:") && (origin = "file://"); try { "postrobot_message_request" === message.type ? handleRequest(source, origin, message, { on: on, send: send }) : "postrobot_message_response" === message.type ? handleResponse(source, origin, message) : "postrobot_message_ack" === message.type && handleAck(source, origin, message); } catch (err) { setTimeout((function() { throw err; }), 0); } } } } function on_on(name, options, handler) { if (!name) throw new Error("Expected name"); if ("function" == typeof (options = options || {})) { handler = options; options = {}; } if (!handler) throw new Error("Expected handler"); var requestListener = function addRequestListener(_ref4, listener) { var name = _ref4.name, winCandidate = _ref4.win, domain = _ref4.domain; var requestListeners = windowStore("requestListeners"); if (!name || "string" != typeof name) throw new Error("Name required to add request listener"); if (winCandidate && "*" !== winCandidate && window_ProxyWindow.isProxyWindow(winCandidate)) { var requestListenerPromise = winCandidate.awaitWindow().then((function(actualWin) { return addRequestListener({ name: name, win: actualWin, domain: domain }, listener); })); return { cancel: function() { requestListenerPromise.then((function(requestListener) { return requestListener.cancel(); }), src_util_noop); } }; } var win = winCandidate; if (Array.isArray(win)) { var listenersCollection = []; for (var _i8 = 0, _win2 = win; _i8 < _win2.length; _i8++) listenersCollection.push(addRequestListener({ name: name, domain: domain, win: _win2[_i8] }, listener)); return { cancel: function() { for (var _i10 = 0; _i10 < listenersCollection.length; _i10++) listenersCollection[_i10].cancel(); } }; } if (Array.isArray(domain)) { var _listenersCollection = []; for (var _i12 = 0, _domain2 = domain; _i12 < _domain2.length; _i12++) _listenersCollection.push(addRequestListener({ name: name, win: win, domain: _domain2[_i12] }, listener)); return { cancel: function() { for (var _i14 = 0; _i14 < _listenersCollection.length; _i14++) _listenersCollection[_i14].cancel(); } }; } var existingListener = getRequestListener({ name: name, win: win, domain: domain }); win && "*" !== win || (win = getWildcard()); var strDomain = (domain = domain || "*").toString(); if (existingListener) throw win && domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : win ? new Error("Request listener already exists for " + name + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString()) : new Error("Request listener already exists for " + name); var winNameListeners = requestListeners.getOrSet(win, (function() { return {}; })); var winNameDomainListeners = util_getOrSet(winNameListeners, name, (function() { return {}; })); var winNameDomainRegexListeners; var winNameDomainRegexListener; util_isRegex(domain) ? (winNameDomainRegexListeners = util_getOrSet(winNameDomainListeners, "__domain_regex__", (function() { return []; }))).push(winNameDomainRegexListener = { regex: domain, listener: listener }) : winNameDomainListeners[strDomain] = listener; return { cancel: function() { delete winNameDomainListeners[strDomain]; if (winNameDomainRegexListener) { winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1)); winNameDomainRegexListeners.length || delete winNameDomainListeners.__domain_regex__; } Object.keys(winNameDomainListeners).length || delete winNameListeners[name]; win && !Object.keys(winNameListeners).length && requestListeners.del(win); } }; }({ name: name, win: options.window, domain: options.domain || "*" }, { handler: handler || options.handler, handleError: options.errorHandler || function(err) { throw err; } }); return { cancel: function() { requestListener.cancel(); } }; } var send_send = function send(winOrProxyWin, name, data, options) { var domainMatcher = (options = options || {}).domain || "*"; var responseTimeout = options.timeout || -1; var childTimeout = options.timeout || 5e3; var fireAndForget = options.fireAndForget || !1; return window_ProxyWindow.toProxyWindow(winOrProxyWin, { send: send }).awaitWindow().then((function(win) { return promise_ZalgoPromise.try((function() { !function(name, win, domain) { if (!name) throw new Error("Expected name"); if (domain && "string" != typeof domain && !Array.isArray(domain) && !util_isRegex(domain)) throw new TypeError("Can not send " + name + ". Expected domain " + JSON.stringify(domain) + " to be a string, array, or regex"); if (isWindowClosed(win)) throw new Error("Can not send " + name + ". Target window is closed"); }(name, win, domainMatcher); if (function(parent, child) { var actualParent = getAncestor(child); if (actualParent) return actualParent === parent; if (child === parent) return !1; if (getTop(child) === child) return !1; for (var _i15 = 0, _getFrames8 = getFrames(parent); _i15 < _getFrames8.length; _i15++) if (_getFrames8[_i15] === child) return !0; return !1; }(window, win)) return function(win, timeout, name) { void 0 === timeout && (timeout = 5e3); void 0 === name && (name = "Window"); var promise = function(win) { return windowStore("helloPromises").getOrSet(win, (function() { return new promise_ZalgoPromise; })); }(win); -1 !== timeout && (promise = promise.timeout(timeout, new Error(name + " did not load after " + timeout + "ms"))); return promise; }(win, childTimeout); })).then((function(_temp) { return function(win, targetDomain, actualDomain, _ref) { var send = _ref.send; return promise_ZalgoPromise.try((function() { return "string" == typeof targetDomain ? targetDomain : promise_ZalgoPromise.try((function() { return actualDomain || sayHello(win, { send: send }).then((function(_ref2) { return _ref2.domain; })); })).then((function(normalizedDomain) { if (!matchDomain(targetDomain, targetDomain)) throw new Error("Domain " + stringify(targetDomain) + " does not match " + stringify(targetDomain)); return normalizedDomain; })); })); }(win, domainMatcher, (void 0 === _temp ? {} : _temp).domain, { send: send }); })).then((function(targetDomain) { var domain = targetDomain; var logName = "postrobot_method" === name && data && "string" == typeof data.name ? data.name + "()" : name; var promise = new promise_ZalgoPromise; var hash = name + "_" + uniqueID(); if (!fireAndForget) { var responseListener = { name: name, win: win, domain: domain, promise: promise }; !function(hash, listener) { globalStore("responseListeners").set(hash, listener); }(hash, responseListener); var reqPromises = windowStore("requestPromises").getOrSet(win, (function() { return []; })); reqPromises.push(promise); promise.catch((function() { !function(hash) { globalStore("erroredResponseListeners").set(hash, !0); }(hash); deleteResponseListener(hash); })); var totalAckTimeout = function(win) { return windowStore("knownWindows").get(win, !1); }(win) ? 1e4 : 2e3; var totalResTimeout = responseTimeout; var ackTimeout = totalAckTimeout; var resTimeout = totalResTimeout; var interval = safeInterval((function() { if (isWindowClosed(win)) return promise.reject(new Error("Window closed for " + name + " before " + (responseListener.ack ? "response" : "ack"))); if (responseListener.cancelled) return promise.reject(new Error("Response listener was cancelled for " + name)); ackTimeout = Math.max(ackTimeout - 500, 0); -1 !== resTimeout && (resTimeout = Math.max(resTimeout - 500, 0)); return responseListener.ack || 0 !== ackTimeout ? 0 === resTimeout ? promise.reject(new Error("No response for postMessage " + logName + " in " + getDomain() + " in " + totalResTimeout + "ms")) : void 0 : promise.reject(new Error("No ack for postMessage " + logName + " in " + getDomain() + " in " + totalAckTimeout + "ms")); }), 500); promise.finally((function() { interval.cancel(); reqPromises.splice(reqPromises.indexOf(promise, 1)); })).catch(src_util_noop); } return send_sendMessage(win, domain, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_request", hash: hash, name: name, data: data, fireAndForget: fireAndForget }, { on: on_on, send: send }).then((function() { return fireAndForget ? promise.resolve() : promise; }), (function(err) { throw new Error("Send request message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); })); })); })); }; function setup_toProxyWindow(win) { return window_ProxyWindow.toProxyWindow(win, { send: send_send }); } function src_util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function utils_getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function utils_getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return utils_getActualProtocol(win); } function utils_isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === utils_getProtocol(win); } function src_utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function utils_getOpener(win) { void 0 === win && (win = window); if (win && !src_utils_getParent(win)) try { return win.opener; } catch (err) {} } function utils_canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function utils_getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = utils_getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = src_utils_getParent(win); return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function utils_getDomain(win) { void 0 === win && (win = window); var domain = utils_getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function utils_isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === utils_getProtocol(win); }(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; if (utils_getDomain(window) === utils_getDomain(win)) return !0; } catch (err) {} return !1; } function utils_assertSameDomain(win) { if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function utils_isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = src_utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function utils_getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function utils_getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function utils_getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (src_utils_getParent(win) === win) return win; try { if (utils_isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (utils_isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (src_utils_getParent(frame) === frame) return frame; } } function utils_getAllFramesInWindow(win) { var top = utils_getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(utils_getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); return result; } var utils_iframeWindows = []; var utils_iframeFrames = []; function utils_isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || "Call was rejected by callee.\r\n" !== err.message; } if (allowMock && utils_isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(utils_iframeWindows, win); if (-1 !== iframeIndex) { var frame = utils_iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function utils_getFrameByName(win, name) { var winFrames = utils_getFrames(win); for (var _i9 = 0; _i9 < winFrames.length; _i9++) { var childFrame = winFrames[_i9]; try { if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; } catch (err) {} } try { if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; } catch (err) {} try { if (-1 !== winFrames.indexOf(win[name])) return win[name]; } catch (err) {} } function utils_getAncestor(win) { void 0 === win && (win = window); return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; } function utils_anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function utils_getDistanceFromTop(win) { void 0 === win && (win = window); var distance = 0; var parent = win; for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); return distance; } function utils_matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (src_util_isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return src_util_isRegex(pattern) ? src_util_isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { return utils_matchDomain(subpattern, origin); }))); } function utils_getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); } function utils_onCloseWindow(win, callback, delay, maxtime) { void 0 === delay && (delay = 1e3); void 0 === maxtime && (maxtime = 1 / 0); var timeout; !function check() { if (utils_isWindowClosed(win)) { timeout && clearTimeout(timeout); return callback(); } if (maxtime <= 0) clearTimeout(timeout); else { maxtime -= delay; timeout = setTimeout(check, delay); } }(); return { cancel: function() { timeout && clearTimeout(timeout); } }; } function utils_isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function lib_global_getGlobal(win) { if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); return win.__zoid_9_0_87__; } function tryGlobal(win, handler) { try { return handler(lib_global_getGlobal(win)); } catch (err) {} } function getProxyObject(obj) { return { get: function() { var _this = this; return promise_ZalgoPromise.try((function() { if (_this.source && _this.source !== window) throw new Error("Can not call get on proxy object from a remote window"); return obj; })); } }; } function basicSerialize(data) { return base64encode(JSON.stringify(data)); } function getUIDRefStore(win) { var global = lib_global_getGlobal(win); global.references = global.references || {}; return global.references; } function crossDomainSerialize(_ref) { var data = _ref.data, metaData = _ref.metaData, sender = _ref.sender, receiver = _ref.receiver, _ref$passByReference = _ref.passByReference, passByReference = void 0 !== _ref$passByReference && _ref$passByReference, _ref$basic = _ref.basic, basic = void 0 !== _ref$basic && _ref$basic; var proxyWin = setup_toProxyWindow(receiver.win); var serializedMessage = basic ? JSON.stringify(data) : serializeMessage(proxyWin, receiver.domain, data, { on: on_on, send: send_send }); var reference = passByReference ? function(val) { var uid = uniqueID(); getUIDRefStore(window)[uid] = val; return { type: "uid", uid: uid }; }(serializedMessage) : { type: "raw", val: serializedMessage }; return { serializedData: basicSerialize({ sender: { domain: sender.domain }, metaData: metaData, reference: reference }), cleanReference: function() { win = window, "uid" === (ref = reference).type && delete getUIDRefStore(win)[ref.uid]; var win, ref; } }; } function crossDomainDeserialize(_ref2) { var sender = _ref2.sender, _ref2$basic = _ref2.basic, basic = void 0 !== _ref2$basic && _ref2$basic; var message = function(serializedData) { return JSON.parse(function(str) { if ("function" == typeof atob) return decodeURIComponent([].map.call(atob(str), (function(c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); })).join("")); if ("undefined" != typeof Buffer) return Buffer.from(str, "base64").toString("utf8"); throw new Error("Can not find window.atob or Buffer"); }(serializedData)); }(_ref2.data); var reference = message.reference, metaData = message.metaData; var win; win = "function" == typeof sender.win ? sender.win({ metaData: metaData }) : sender.win; var domain; domain = "function" == typeof sender.domain ? sender.domain({ metaData: metaData }) : "string" == typeof sender.domain ? sender.domain : message.sender.domain; var serializedData = function(win, ref) { if ("raw" === ref.type) return ref.val; if ("uid" === ref.type) return getUIDRefStore(win)[ref.uid]; throw new Error("Unsupported ref type: " + ref.type); }(win, reference); return { data: basic ? JSON.parse(serializedData) : function(source, origin, message) { return deserializeMessage(source, origin, message, { on: on_on, send: send_send }); }(win, domain, serializedData), metaData: metaData, sender: { win: win, domain: domain }, reference: reference }; } var PROP_TYPE = { STRING: "string", OBJECT: "object", FUNCTION: "function", BOOLEAN: "boolean", NUMBER: "number", ARRAY: "array" }; var PROP_SERIALIZATION = { JSON: "json", DOTIFY: "dotify", BASE64: "base64" }; var CONTEXT = { IFRAME: "iframe", POPUP: "popup" }; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", DISPLAY: "zoid-display", ERROR: "zoid-error", CLOSE: "zoid-close", DESTROY: "zoid-destroy", PROPS: "zoid-props", RESIZE: "zoid-resize", FOCUS: "zoid-focus" }; function buildChildWindowName(_ref) { return "__zoid__" + _ref.name + "__" + _ref.serializedPayload + "__"; } function parseWindowName(windowName) { if (!windowName) throw new Error("No window name"); var _windowName$split = windowName.split("__"), zoidcomp = _windowName$split[1], name = _windowName$split[2], serializedInitialPayload = _windowName$split[3]; if ("zoid" !== zoidcomp) throw new Error("Window not rendered by zoid - got " + zoidcomp); if (!name) throw new Error("Expected component name"); if (!serializedInitialPayload) throw new Error("Expected serialized payload ref"); return { name: name, serializedInitialPayload: serializedInitialPayload }; } var parseInitialParentPayload = memoize((function(windowName) { var _crossDomainDeseriali = crossDomainDeserialize({ data: parseWindowName(windowName).serializedInitialPayload, sender: { win: function(_ref2) { return function(windowRef) { if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { void 0 === n && (n = 1); var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; parent = src_utils_getParent(parent); } return parent; }(win, utils_getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; var ancestor = utils_getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); if (win) return { v: win }; } } }(); if ("object" == typeof _ret) return _ret.v; } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { var frame = utils_getFrameByName(win, name); if (frame) return frame; for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } }(utils_getTop(win) || win, name); }(assertExists("ancestor", utils_getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); } } }); return { parent: _crossDomainDeseriali.sender, payload: _crossDomainDeseriali.data, reference: _crossDomainDeseriali.reference }; })); function getInitialParentPayload() { return parseInitialParentPayload(window.name); } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); if (targetWindow === src_utils_getParent(currentWindow)) return { type: "parent", distance: utils_getDistanceFromTop(targetWindow) }; if (targetWindow === utils_getOpener(currentWindow)) return { type: "opener" }; if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { var windowName = utils_assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName }; } var win; } function normalizeChildProp(propsDef, props, key, value, helpers) { if (!propsDef.hasOwnProperty(key)) return value; var prop = propsDef[key]; return "function" == typeof prop.childDecorate ? prop.childDecorate({ value: value, uid: helpers.uid, tag: helpers.tag, close: helpers.close, focus: helpers.focus, onError: helpers.onError, onProps: helpers.onProps, resize: helpers.resize, getParent: helpers.getParent, getParentDomain: helpers.getParentDomain, show: helpers.show, hide: helpers.hide, export: helpers.export, getSiblings: helpers.getSiblings }) : value; } function child_focus() { return promise_ZalgoPromise.try((function() { window.focus(); })); } function child_destroy() { return promise_ZalgoPromise.try((function() { window.close(); })); } var props_defaultNoop = function() { return src_util_noop; }; var props_decorateOnce = function(_ref) { return once(_ref.value); }; function eachProp(props, propsDef, handler) { for (var _i2 = 0, _Object$keys2 = Object.keys(_extends({}, props, propsDef)); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; handler(key, propsDef[key], props[key]); } } function serializeProps(propsDef, props, method) { var params = {}; return promise_ZalgoPromise.all(function(props, propsDef, handler) { var results = []; eachProp(props, propsDef, (function(key, propDef, value) { var result = function(key, propDef, value) { return promise_ZalgoPromise.resolve().then((function() { var _METHOD$GET$METHOD$PO, _METHOD$GET$METHOD$PO2; if (null != value && propDef) { var getParam = (_METHOD$GET$METHOD$PO = {}, _METHOD$GET$METHOD$PO.get = propDef.queryParam, _METHOD$GET$METHOD$PO.post = propDef.bodyParam, _METHOD$GET$METHOD$PO)[method]; var getValue = (_METHOD$GET$METHOD$PO2 = {}, _METHOD$GET$METHOD$PO2.get = propDef.queryValue, _METHOD$GET$METHOD$PO2.post = propDef.bodyValue, _METHOD$GET$METHOD$PO2)[method]; if (getParam) return promise_ZalgoPromise.hash({ finalParam: promise_ZalgoPromise.try((function() { return "function" == typeof getParam ? getParam({ value: value }) : "string" == typeof getParam ? getParam : key; })), finalValue: promise_ZalgoPromise.try((function() { return "function" == typeof getValue && isDefined(value) ? getValue({ value: value }) : value; })) }).then((function(_ref) { var finalParam = _ref.finalParam, finalValue = _ref.finalValue; var result; if ("boolean" == typeof finalValue) result = finalValue.toString(); else if ("string" == typeof finalValue) result = finalValue.toString(); else if ("object" == typeof finalValue && null !== finalValue) { if (propDef.serialization === PROP_SERIALIZATION.JSON) result = JSON.stringify(finalValue); else if (propDef.serialization === PROP_SERIALIZATION.BASE64) result = base64encode(JSON.stringify(finalValue)); else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) { result = function dotify(obj, prefix, newobj) { void 0 === prefix && (prefix = ""); void 0 === newobj && (newobj = {}); prefix = prefix ? prefix + "." : prefix; for (var key in obj) obj.hasOwnProperty(key) && null != obj[key] && "function" != typeof obj[key] && (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every((function(val) { return "object" != typeof val; })) ? newobj["" + prefix + key + "[]"] = obj[key].join(",") : obj[key] && "object" == typeof obj[key] ? newobj = dotify(obj[key], "" + prefix + key, newobj) : newobj["" + prefix + key] = obj[key].toString()); return newobj; }(finalValue, key); for (var _i2 = 0, _Object$keys2 = Object.keys(result); _i2 < _Object$keys2.length; _i2++) { var dotkey = _Object$keys2[_i2]; params[dotkey] = result[dotkey]; } return; } } else "number" == typeof finalValue && (result = finalValue.toString()); params[finalParam] = result; })); } })); }(key, propDef, value); results.push(result); })); return results; }(props, propsDef)).then((function() { return params; })); } function parentComponent(_ref) { var uid = _ref.uid, options = _ref.options, _ref$overrides = _ref.overrides, overrides = void 0 === _ref$overrides ? {} : _ref$overrides, _ref$parentWin = _ref.parentWin, parentWin = void 0 === _ref$parentWin ? window : _ref$parentWin; var propsDef = options.propsDef, containerTemplate = options.containerTemplate, prerenderTemplate = options.prerenderTemplate, tag = options.tag, name = options.name, attributes = options.attributes, dimensions = options.dimensions, autoResize = options.autoResize, url = options.url, domainMatch = options.domain, xports = options.exports; var initPromise = new promise_ZalgoPromise; var handledErrors = []; var clean = cleanup(); var state = {}; var inputProps = {}; var internalState = { visible: !0 }; var event = overrides.event ? overrides.event : (triggered = {}, handlers = {}, emitter = { on: function(eventName, handler) { var handlerList = handlers[eventName] = handlers[eventName] || []; handlerList.push(handler); var cancelled = !1; return { cancel: function() { if (!cancelled) { cancelled = !0; handlerList.splice(handlerList.indexOf(handler), 1); } } }; }, once: function(eventName, handler) { var listener = emitter.on(eventName, (function() { listener.cancel(); handler(); })); return listener; }, trigger: function(eventName) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3]; var handlerList = handlers[eventName]; var promises = []; if (handlerList) { var _loop = function(_i2) { var handler = handlerList[_i2]; promises.push(promise_ZalgoPromise.try((function() { return handler.apply(void 0, args); }))); }; for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(_i2); } return promise_ZalgoPromise.all(promises).then(src_util_noop); }, triggerOnce: function(eventName) { if (triggered[eventName]) return promise_ZalgoPromise.resolve(); triggered[eventName] = !0; for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) args[_key4 - 1] = arguments[_key4]; return emitter.trigger.apply(emitter, [ eventName ].concat(args)); }, reset: function() { handlers = {}; } }); var triggered, handlers, emitter; var props = overrides.props ? overrides.props : {}; var currentProxyWin; var currentProxyContainer; var childComponent; var currentChildDomain; var currentContainer; var onErrorOverride = overrides.onError; var getProxyContainerOverride = overrides.getProxyContainer; var showOverride = overrides.show; var hideOverride = overrides.hide; var closeOverride = overrides.close; var renderContainerOverride = overrides.renderContainer; var getProxyWindowOverride = overrides.getProxyWindow; var setProxyWinOverride = overrides.setProxyWin; var openFrameOverride = overrides.openFrame; var openPrerenderFrameOverride = overrides.openPrerenderFrame; var prerenderOverride = overrides.prerender; var openOverride = overrides.open; var openPrerenderOverride = overrides.openPrerender; var watchForUnloadOverride = overrides.watchForUnload; var getInternalStateOverride = overrides.getInternalState; var setInternalStateOverride = overrides.setInternalState; var resolveInitPromise = function() { return promise_ZalgoPromise.try((function() { return overrides.resolveInitPromise ? overrides.resolveInitPromise() : initPromise.resolve(); })); }; var rejectInitPromise = function(err) { return promise_ZalgoPromise.try((function() { return overrides.rejectInitPromise ? overrides.rejectInitPromise(err) : initPromise.reject(err); })); }; var getPropsForChild = function(initialChildDomain) { var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; var getInternalState = function() { return promise_ZalgoPromise.try((function() { return getInternalStateOverride ? getInternalStateOverride() : internalState; })); }; var setInternalState = function(newInternalState) { return promise_ZalgoPromise.try((function() { return setInternalStateOverride ? setInternalStateOverride(newInternalState) : internalState = _extends({}, internalState, newInternalState); })); }; var getProxyWindow = function() { return getProxyWindowOverride ? getProxyWindowOverride() : promise_ZalgoPromise.try((function() { var windowProp = props.window; if (windowProp) { var _proxyWin = setup_toProxyWindow(windowProp); clean.register((function() { return windowProp.close(); })); return _proxyWin; } return new window_ProxyWindow({ send: send_send }); })); }; var setProxyWin = function(proxyWin) { return setProxyWinOverride ? setProxyWinOverride(proxyWin) : promise_ZalgoPromise.try((function() { currentProxyWin = proxyWin; })); }; var show = function() { return showOverride ? showOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !0 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null }).then(src_util_noop); }; var hide = function() { return hideOverride ? hideOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !1 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null }).then(src_util_noop); }; var getUrl = function() { return "function" == typeof url ? url({ props: props }) : url; }; var getAttributes = function() { return "function" == typeof attributes ? attributes({ props: props }) : attributes; }; var getInitialChildDomain = function() { return utils_getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; return openFrameOverride ? openFrameOverride(context, { windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: windowName, title: name }, getAttributes().iframe) })); })); }; var openPrerenderFrame = function(context) { return openPrerenderFrameOverride ? openPrerenderFrameOverride(context) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: "__zoid_prerender_frame__" + name + "_" + uniqueID() + "__", title: "prerender__" + name }, getAttributes().iframe) })); })); }; var openPrerender = function(context, proxyWin, proxyPrerenderFrame) { return openPrerenderOverride ? openPrerenderOverride(context, proxyWin, proxyPrerenderFrame) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyPrerenderFrame) throw new Error("Expected proxy frame to be passed"); return proxyPrerenderFrame.get().then((function(prerenderFrame) { clean.register((function() { return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { return utils_assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); })); } throw new Error("No render context available for " + context); })); }; var focus = function() { return promise_ZalgoPromise.try((function() { if (currentProxyWin) return promise_ZalgoPromise.all([ event.trigger(EVENT.FOCUS), currentProxyWin.focus() ]).then(src_util_noop); })); }; var getCurrentWindowReferenceUID = function() { var global = lib_global_getGlobal(window); global.windows = global.windows || {}; global.windows[uid] = window; clean.register((function() { delete global.windows[uid]; })); return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { if (initialChildDomain === utils_getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; if (target !== window) throw new Error("Can not construct cross-domain window reference for different target window"); if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", distance: utils_getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; var initChild = function(childDomain, childExports) { return promise_ZalgoPromise.try((function() { currentChildDomain = childDomain; childComponent = childExports; resolveInitPromise(); clean.register((function() { return childExports.close.fireAndForget().catch(src_util_noop); })); })); }; var resize = function(_ref3) { var width = _ref3.width, height = _ref3.height; return promise_ZalgoPromise.try((function() { event.trigger(EVENT.RESIZE, { width: width, height: height }); })); }; var destroy = function(err) { return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.DESTROY); })).catch(src_util_noop).then((function() { return clean.all(err); })).then((function() { initPromise.asyncReject(err || new Error("Component destroyed")); })); }; var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { if (utils_isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.CLOSE); })).then((function() { return destroy(err || new Error("Component closed")); })); })); })); var open = function(context, _ref4) { var proxyWin = _ref4.proxyWin, proxyFrame = _ref4.proxyFrame, windowName = _ref4.windowName; return openOverride ? openOverride(context, { proxyWin: proxyWin, proxyFrame: proxyFrame, windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyFrame) throw new Error("Expected proxy frame to be passed"); return proxyFrame.get().then((function(frame) { return awaitFrameWindow(frame).then((function(win) { clean.register((function() { return destroyElement(frame); })); clean.register((function() { return function(win) { for (var _i2 = 0, _requestPromises$get2 = windowStore("requestPromises").get(win, []); _i2 < _requestPromises$get2.length; _i2++) _requestPromises$get2[_i2].reject(new Error("Window " + (isWindowClosed(win) ? "closed" : "cleaned up") + " before response")).catch(src_util_noop); }(win); })); return win; })); })); } throw new Error("No render context available for " + context); })).then((function(win) { proxyWin.setWindow(win, { send: send_send }); return proxyWin.setName(windowName).then((function() { return proxyWin; })); })); }; var watchForUnload = function() { return promise_ZalgoPromise.try((function() { var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); })); }; var checkWindowClose = function(proxyWin) { var closed = !1; return proxyWin.isClosed().then((function(isClosed) { if (isClosed) { closed = !0; return close(new Error("Detected component window close")); } return promise_ZalgoPromise.delay(200).then((function() { return proxyWin.isClosed(); })).then((function(secondIsClosed) { if (secondIsClosed) { closed = !0; return close(new Error("Detected component window close")); } })); })).then((function() { return closed; })); }; var onError = function(err) { return onErrorOverride ? onErrorOverride(err) : promise_ZalgoPromise.try((function() { if (-1 === handledErrors.indexOf(err)) { handledErrors.push(err); initPromise.asyncReject(err); return event.trigger(EVENT.ERROR, err); } })); }; var exportsPromise = new promise_ZalgoPromise; var xport = function(actualExports) { return promise_ZalgoPromise.try((function() { exportsPromise.resolve(actualExports); })); }; initChild.onError = onError; var renderTemplate = function(renderer, _ref8) { return renderer({ uid: uid, container: _ref8.container, context: _ref8.context, doc: _ref8.doc, frame: _ref8.frame, prerenderFrame: _ref8.prerenderFrame, focus: focus, close: close, state: state, props: props, tag: tag, dimensions: "function" == typeof dimensions ? dimensions({ props: props }) : dimensions, event: event }); }; var prerender = function(proxyPrerenderWin, _ref9) { var context = _ref9.context; return prerenderOverride ? prerenderOverride(proxyPrerenderWin, { context: context }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc }); if (el) { if (el.ownerDocument !== doc) throw new Error("Expected prerender template to have been created with document from child window"); !function(win, el) { var tag = el.tagName.toLowerCase(); if ("html" !== tag) throw new Error("Expected element to be html, got " + tag); var documentElement = win.document.documentElement; for (var _i6 = 0, _arrayFrom2 = arrayFrom(documentElement.children); _i6 < _arrayFrom2.length; _i6++) documentElement.removeChild(_arrayFrom2[_i6]); for (var _i8 = 0, _arrayFrom4 = arrayFrom(el.children); _i8 < _arrayFrom4.length; _i8++) documentElement.appendChild(_arrayFrom4[_i8]); }(prerenderWindow, el); var _autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, element = void 0 === _autoResize$element ? "body" : _autoResize$element; if ((element = getElementSafe(element, doc)) && (width || height)) { var prerenderResizeListener = onResize(element, (function(_ref10) { resize({ width: width ? _ref10.width : void 0, height: height ? _ref10.height : void 0 }); }), { width: width, height: height, win: prerenderWindow }); event.on(EVENT.RENDERED, prerenderResizeListener.cancel); } } } } })); }; var renderContainer = function(proxyContainer, _ref11) { var proxyFrame = _ref11.proxyFrame, proxyPrerenderFrame = _ref11.proxyPrerenderFrame, context = _ref11.context, rerender = _ref11.rerender; return renderContainerOverride ? renderContainerOverride(proxyContainer, { proxyFrame: proxyFrame, proxyPrerenderFrame: proxyPrerenderFrame, context: context, rerender: rerender }) : promise_ZalgoPromise.hash({ container: proxyContainer.get(), frame: proxyFrame ? proxyFrame.get() : null, prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null, internalState: getInternalState() }).then((function(_ref12) { var container = _ref12.container, visible = _ref12.internalState.visible; var innerContainer = renderTemplate(containerTemplate, { context: context, container: container, frame: _ref12.frame, prerenderFrame: _ref12.prerenderFrame, doc: document }); if (innerContainer) { visible || hideElement(innerContainer); appendChild(container, innerContainer); var containerWatcher = function(element, handler) { handler = once(handler); var cancelled = !1; var mutationObservers = []; var interval; var sacrificialFrame; var sacrificialFrameWin; var cancel = function() { cancelled = !0; for (var _i18 = 0; _i18 < mutationObservers.length; _i18++) mutationObservers[_i18].disconnect(); interval && interval.cancel(); sacrificialFrameWin && sacrificialFrameWin.removeEventListener("unload", elementClosed); sacrificialFrame && destroyElement(sacrificialFrame); }; var elementClosed = function() { if (!cancelled) { handler(); cancel(); } }; if (isElementClosed(element)) { elementClosed(); return { cancel: cancel }; } if (window.MutationObserver) { var mutationElement = element.parentElement; for (;mutationElement; ) { var mutationObserver = new window.MutationObserver((function() { isElementClosed(element) && elementClosed(); })); mutationObserver.observe(mutationElement, { childList: !0 }); mutationObservers.push(mutationObserver); mutationElement = mutationElement.parentElement; } } (sacrificialFrame = document.createElement("iframe")).setAttribute("name", "__detect_close_" + uniqueID() + "__"); sacrificialFrame.style.display = "none"; awaitFrameWindow(sacrificialFrame).then((function(frameWin) { (sacrificialFrameWin = assertSameDomain(frameWin)).addEventListener("unload", elementClosed); })); element.appendChild(sacrificialFrame); interval = safeInterval((function() { isElementClosed(element) && elementClosed(); }), 1e3); return { cancel: cancel }; }(innerContainer, (function() { var removeError = new Error("Detected container element removed from DOM"); return promise_ZalgoPromise.delay(1).then((function() { if (!isElementClosed(innerContainer)) { clean.all(removeError); return rerender().then(resolveInitPromise, rejectInitPromise); } close(removeError); })); })); clean.register((function() { return containerWatcher.cancel(); })); clean.register((function() { return destroyElement(innerContainer); })); return currentProxyContainer = getProxyObject(innerContainer); } })); }; var getHelpers = function() { return { state: state, event: event, close: close, focus: focus, resize: resize, onError: onError, updateProps: updateProps, show: show, hide: hide }; }; var setProps = function(newInputProps) { void 0 === newInputProps && (newInputProps = {}); var container = currentContainer; var helpers = getHelpers(); extend(inputProps, newInputProps); !function(propsDef, existingProps, inputProps, helpers, container) { var state = helpers.state, close = helpers.close, focus = helpers.focus, event = helpers.event, onError = helpers.onError; eachProp(inputProps, propsDef, (function(key, propDef, val) { var valueDetermined = !1; var value = val; Object.defineProperty(existingProps, key, { configurable: !0, enumerable: !0, get: function() { if (valueDetermined) return value; valueDetermined = !0; return function() { if (!propDef) return value; var alias = propDef.alias; alias && !isDefined(val) && isDefined(inputProps[alias]) && (value = inputProps[alias]); propDef.value && (value = propDef.value({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); !propDef.default || isDefined(value) || isDefined(inputProps[key]) || (value = propDef.default({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); if (isDefined(value)) { if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : typeof value !== propDef.type) throw new TypeError("Prop is not of type " + propDef.type + ": " + key); } else if (!1 !== propDef.required && !isDefined(inputProps[key])) throw new Error('Expected prop "' + key + '" to be defined'); isDefined(value) && propDef.decorate && (value = propDef.decorate({ value: value, props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); return value; }(); } }); })); eachProp(existingProps, propsDef, src_util_noop); }(propsDef, props, inputProps, helpers, container); }; var updateProps = function(newProps) { setProps(newProps); return initPromise.then((function() { var child = childComponent; var proxyWin = currentProxyWin; if (child && proxyWin && currentChildDomain) return getPropsForChild(currentChildDomain).then((function(childProps) { return child.updateProps(childProps).catch((function(err) { return checkWindowClose(proxyWin).then((function(closed) { if (!closed) throw err; })); })); })); })); }; var getProxyContainer = function(container) { return getProxyContainerOverride ? getProxyContainerOverride(container) : promise_ZalgoPromise.try((function() { return elementReady(container); })).then((function(containerElement) { isShadowElement(containerElement) && (containerElement = function insertShadowSlot(element) { var shadowHost = function(element) { var shadowRoot = function(element) { for (;element.parentNode; ) element = element.parentNode; if (isShadowElement(element)) return element; }(element); if (shadowRoot && shadowRoot.host) return shadowRoot.host; }(element); if (!shadowHost) throw new Error("Element is not in shadow dom"); var slotName = "shadow-slot-" + uniqueID(); var slot = document.createElement("slot"); slot.setAttribute("name", slotName); element.appendChild(slot); var slotProvider = document.createElement("div"); slotProvider.setAttribute("slot", slotName); shadowHost.appendChild(slotProvider); return isShadowElement(shadowHost) ? insertShadowSlot(slotProvider) : slotProvider; }(containerElement)); currentContainer = containerElement; return getProxyObject(containerElement); })); }; return { init: function() { !function() { event.on(EVENT.RENDER, (function() { return props.onRender(); })); event.on(EVENT.DISPLAY, (function() { return props.onDisplay(); })); event.on(EVENT.RENDERED, (function() { return props.onRendered(); })); event.on(EVENT.CLOSE, (function() { return props.onClose(); })); event.on(EVENT.DESTROY, (function() { return props.onDestroy(); })); event.on(EVENT.RESIZE, (function() { return props.onResize(); })); event.on(EVENT.FOCUS, (function() { return props.onFocus(); })); event.on(EVENT.PROPS, (function(newProps) { return props.onProps(newProps); })); event.on(EVENT.ERROR, (function(err) { return props && props.onError ? props.onError(err) : rejectInitPromise(err).then((function() { setTimeout((function() { throw err; }), 1); })); })); clean.register(event.reset); }(); }, render: function(_ref14) { var target = _ref14.target, container = _ref14.container, context = _ref14.context, rerender = _ref14.rerender; return promise_ZalgoPromise.try((function() { var initialChildDomain = getInitialChildDomain(); var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { if (!function(win1, win2) { var top1 = utils_getTop(win1) || win1; var top2 = utils_getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = utils_getAllFramesInWindow(win1); var allFrames2 = utils_getAllFramesInWindow(win2); if (utils_anyMatch(allFrames1, allFrames2)) return !0; var opener1 = utils_getOpener(top1); var opener2 = utils_getOpener(top2); return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), !1; }(window, target)) throw new Error("Can only renderTo an adjacent frame"); var origin = utils_getDomain(); if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); var delegatePromise = promise_ZalgoPromise.try((function() { if (target !== window) return function(context, target) { var delegateProps = {}; for (var _i4 = 0, _Object$keys4 = Object.keys(props); _i4 < _Object$keys4.length; _i4++) { var propName = _Object$keys4[_i4]; var propDef = propsDef[propName]; propDef && propDef.allowDelegate && (delegateProps[propName] = props[propName]); } var childOverridesPromise = send_send(target, "zoid_delegate_" + name, { uid: uid, overrides: { props: delegateProps, event: event, close: close, onError: onError, getInternalState: getInternalState, setInternalState: setInternalState, resolveInitPromise: resolveInitPromise, rejectInitPromise: rejectInitPromise } }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { if (!utils_isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { throw new Error("Unable to delegate rendering. Possibly the component is not loaded in the target window.\n\n" + stringifyError(err)); })); getProxyContainerOverride = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyContainer.apply(childOverrides, args); })); }; renderContainerOverride = function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.renderContainer.apply(childOverrides, args); })); }; showOverride = function() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) args[_key3] = arguments[_key3]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.show.apply(childOverrides, args); })); }; hideOverride = function() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) args[_key4] = arguments[_key4]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.hide.apply(childOverrides, args); })); }; watchForUnloadOverride = function() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) args[_key5] = arguments[_key5]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.watchForUnload.apply(childOverrides, args); })); }; if (context === CONTEXT.IFRAME) { getProxyWindowOverride = function() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) args[_key6] = arguments[_key6]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyWindow.apply(childOverrides, args); })); }; openFrameOverride = function() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) args[_key7] = arguments[_key7]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openFrame.apply(childOverrides, args); })); }; openPrerenderFrameOverride = function() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) args[_key8] = arguments[_key8]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerenderFrame.apply(childOverrides, args); })); }; prerenderOverride = function() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) args[_key9] = arguments[_key9]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.prerender.apply(childOverrides, args); })); }; openOverride = function() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) args[_key10] = arguments[_key10]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.open.apply(childOverrides, args); })); }; openPrerenderOverride = function() { for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) args[_key11] = arguments[_key11]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerender.apply(childOverrides, args); })); }; } return childOverridesPromise; }(context, target); })); var windowProp = props.window; var watchForUnloadPromise = watchForUnload(); var buildBodyPromise = serializeProps(propsDef, props, "post"); var onRenderPromise = event.trigger(EVENT.RENDER); var getProxyContainerPromise = getProxyContainer(container); var getProxyWindowPromise = getProxyWindow(); var finalSetPropsPromise = getProxyContainerPromise.then((function() { return setProps(); })); var buildUrlPromise = finalSetPropsPromise.then((function() { return serializeProps(propsDef, props, "get").then((function(query) { return function(url, options) { var query = options.query || {}; var hash = options.hash || {}; var originalUrl; var originalHash; var _url$split = url.split("#"); originalHash = _url$split[1]; var _originalUrl$split = (originalUrl = _url$split[0]).split("?"); originalUrl = _originalUrl$split[0]; var queryString = extendQuery(_originalUrl$split[1], query); var hashString = extendQuery(originalHash, hash); queryString && (originalUrl = originalUrl + "?" + queryString); hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; }(function(url) { if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); }(getUrl()), { query: query }); })); })); var buildWindowNamePromise = getProxyWindowPromise.then((function(proxyWin) { return function(_temp2) { var _ref6 = void 0 === _temp2 ? {} : _temp2, proxyWin = _ref6.proxyWin, initialChildDomain = _ref6.initialChildDomain, childDomainMatch = _ref6.childDomainMatch, _ref6$target = _ref6.target, target = void 0 === _ref6$target ? window : _ref6$target, context = _ref6.context; return function(_temp) { var _ref5 = void 0 === _temp ? {} : _temp, proxyWin = _ref5.proxyWin, childDomainMatch = _ref5.childDomainMatch, context = _ref5.context; return getPropsForChild(_ref5.initialChildDomain).then((function(childProps) { return { uid: uid, context: context, tag: tag, childDomainMatch: childDomainMatch, version: "9_0_87", props: childProps, exports: (win = proxyWin, { init: function(childExports) { return initChild(this.origin, childExports); }, close: close, checkClose: function() { return checkWindowClose(win); }, resize: resize, onError: onError, show: show, hide: hide, export: xport }) }; var win; })); }({ proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, context: context }).then((function(childPayload) { var _crossDomainSerialize = crossDomainSerialize({ data: childPayload, metaData: { windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { domain: utils_getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, passByReference: initialChildDomain === utils_getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; })); }({ proxyWin: (_ref7 = { proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, target: target, context: context }).proxyWin, initialChildDomain: _ref7.initialChildDomain, childDomainMatch: _ref7.childDomainMatch, target: _ref7.target, context: _ref7.context }).then((function(serializedPayload) { return buildChildWindowName({ name: name, serializedPayload: serializedPayload }); })); var _ref7; })); var openFramePromise = buildWindowNamePromise.then((function(windowName) { return openFrame(context, { windowName: windowName }); })); var openPrerenderFramePromise = openPrerenderFrame(context); var renderContainerPromise = promise_ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref15) { return renderContainer(_ref15.proxyContainer, { context: context, proxyFrame: _ref15.proxyFrame, proxyPrerenderFrame: _ref15.proxyPrerenderFrame, rerender: rerender }); })).then((function(proxyContainer) { return proxyContainer; })); var openPromise = promise_ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then((function(_ref16) { var proxyWin = _ref16.proxyWin; return windowProp ? proxyWin : open(context, { windowName: _ref16.windowName, proxyWin: proxyWin, proxyFrame: _ref16.proxyFrame }); })); var openPrerenderPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref17) { return openPrerender(context, _ref17.proxyWin, _ref17.proxyPrerenderFrame); })); var setStatePromise = openPromise.then((function(proxyWin) { currentProxyWin = proxyWin; return setProxyWin(proxyWin); })); var prerenderPromise = promise_ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then((function(_ref18) { return prerender(_ref18.proxyPrerenderWin, { context: context }); })); var setWindowNamePromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then((function(_ref19) { if (windowProp) return _ref19.proxyWin.setName(_ref19.windowName); })); var getMethodPromise = promise_ZalgoPromise.hash({ body: buildBodyPromise }).then((function(_ref20) { return options.method ? options.method : Object.keys(_ref20.body).length ? "post" : "get"; })); var loadUrlPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then((function(_ref21) { return _ref21.proxyWin.setLocation(_ref21.windowUrl, { method: _ref21.method, body: _ref21.body }); })); var watchForClosePromise = openPromise.then((function(proxyWin) { !function watchForClose(proxyWin, context) { var cancelled = !1; clean.register((function() { cancelled = !0; })); return promise_ZalgoPromise.delay(2e3).then((function() { return proxyWin.isClosed(); })).then((function(isClosed) { if (!cancelled) return isClosed ? close(new Error("Detected " + context + " close")) : watchForClose(proxyWin, context); })); }(proxyWin, context); })); var onDisplayPromise = promise_ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then((function() { return event.trigger(EVENT.DISPLAY); })); var openBridgePromise = openPromise.then((function(proxyWin) {})); var runTimeoutPromise = loadUrlPromise.then((function() { return promise_ZalgoPromise.try((function() { var timeout = props.timeout; if (timeout) return initPromise.timeout(timeout, new Error("Loading component timed out after " + timeout + " milliseconds")); })); })); var onRenderedPromise = initPromise.then((function() { return event.trigger(EVENT.RENDERED); })); return promise_ZalgoPromise.hash({ initPromise: initPromise, buildUrlPromise: buildUrlPromise, onRenderPromise: onRenderPromise, getProxyContainerPromise: getProxyContainerPromise, openFramePromise: openFramePromise, openPrerenderFramePromise: openPrerenderFramePromise, renderContainerPromise: renderContainerPromise, openPromise: openPromise, openPrerenderPromise: openPrerenderPromise, setStatePromise: setStatePromise, prerenderPromise: prerenderPromise, loadUrlPromise: loadUrlPromise, buildWindowNamePromise: buildWindowNamePromise, setWindowNamePromise: setWindowNamePromise, watchForClosePromise: watchForClosePromise, onDisplayPromise: onDisplayPromise, openBridgePromise: openBridgePromise, runTimeoutPromise: runTimeoutPromise, onRenderedPromise: onRenderedPromise, delegatePromise: delegatePromise, watchForUnloadPromise: watchForUnloadPromise, finalSetPropsPromise: finalSetPropsPromise }); })).catch((function(err) { return promise_ZalgoPromise.all([ onError(err), destroy(err) ]).then((function() { throw err; }), (function() { throw err; })); })).then(src_util_noop); }, destroy: destroy, getProps: function() { return props; }, setProps: setProps, export: xport, getHelpers: getHelpers, getDelegateOverrides: function() { return promise_ZalgoPromise.try((function() { return { getProxyContainer: getProxyContainer, show: show, hide: hide, renderContainer: renderContainer, getProxyWindow: getProxyWindow, watchForUnload: watchForUnload, openFrame: openFrame, openPrerenderFrame: openPrerenderFrame, prerender: prerender, open: open, openPrerender: openPrerender, setProxyWin: setProxyWin }; })); }, getExports: function() { return xports({ getExports: function() { return exportsPromise; } }); } }; } var react = { register: function(tag, propsDef, init, _ref) { var React = _ref.React, ReactDOM = _ref.ReactDOM; return function(_React$Component) { _inheritsLoose(_class, _React$Component); function _class() { return _React$Component.apply(this, arguments) || this; } var _proto = _class.prototype; _proto.render = function() { return React.createElement("div", null); }; _proto.componentDidMount = function() { var el = ReactDOM.findDOMNode(this); var parent = init(extend({}, this.props)); parent.render(el, CONTEXT.IFRAME); this.setState({ parent: parent }); }; _proto.componentDidUpdate = function() { this.state && this.state.parent && this.state.parent.updateProps(extend({}, this.props)).catch(src_util_noop); }; return _class; }(React.Component); } }; var vue = { register: function(tag, propsDef, init, Vue) { return Vue.component(tag, { render: function(createElement) { return createElement("div"); }, inheritAttrs: !1, mounted: function() { var el = this.$el; this.parent = init(_extends({}, (props = this.$attrs, Object.keys(props).reduce((function(acc, key) { var value = props[key]; if ("style-object" === key || "styleObject" === key) { acc.style = value; acc.styleObject = value; } else key.includes("-") ? acc[dasherizeToCamel(key)] = value : acc[key] = value; return acc; }), {})))); var props; this.parent.render(el, CONTEXT.IFRAME); }, watch: { $attrs: { handler: function() { this.parent && this.$attrs && this.parent.updateProps(_extends({}, this.$attrs)).catch(src_util_noop); }, deep: !0 } } }); } }; var vue3 = { register: function(tag, propsDef, init) { return { template: "
", inheritAttrs: !1, mounted: function() { var el = this.$el; this.parent = init(_extends({}, (props = this.$attrs, Object.keys(props).reduce((function(acc, key) { var value = props[key]; if ("style-object" === key || "styleObject" === key) { acc.style = value; acc.styleObject = value; } else key.includes("-") ? acc[dasherizeToCamel(key)] = value : acc[key] = value; return acc; }), {})))); var props; this.parent.render(el, CONTEXT.IFRAME); }, watch: { $attrs: { handler: function() { this.parent && this.$attrs && this.parent.updateProps(_extends({}, this.$attrs)).catch(src_util_noop); }, deep: !0 } } }; } }; var angular = { register: function(tag, propsDef, init, ng) { return ng.module(tag, []).directive(dasherizeToCamel(tag), (function() { var scope = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(propsDef); _i2 < _Object$keys2.length; _i2++) scope[_Object$keys2[_i2]] = "="; scope.props = "="; return { scope: scope, restrict: "E", controller: [ "$scope", "$element", function($scope, $element) { function safeApply() { if ("$apply" !== $scope.$root.$$phase && "$digest" !== $scope.$root.$$phase) try { $scope.$apply(); } catch (err) {} } var getProps = function() { return replaceObject($scope.props, (function(item) { return "function" == typeof item ? function() { var result = item.apply(this, arguments); safeApply(); return result; } : item; })); }; var instance = init(getProps()); instance.render($element[0], CONTEXT.IFRAME); $scope.$watch((function() { instance.updateProps(getProps()).catch(src_util_noop); })); } ] }; })); } }; var angular2 = { register: function(tag, propsDef, init, _ref) { var AngularComponent = _ref.Component, NgModule = _ref.NgModule, ElementRef = _ref.ElementRef, NgZone = _ref.NgZone, Inject = _ref.Inject; var ComponentInstance = function() { function ComponentInstance(elementRef, zone) { this.elementRef = void 0; this.internalProps = void 0; this.parent = void 0; this.props = void 0; this.zone = void 0; this._props = void 0; this._props = {}; this.elementRef = elementRef; this.zone = zone; } var _proto = ComponentInstance.prototype; _proto.getProps = function() { var _this = this; return replaceObject(_extends({}, this.internalProps, this.props), (function(item) { if ("function" == typeof item) { var zone = _this.zone; return function() { var _arguments = arguments, _this2 = this; return zone.run((function() { return item.apply(_this2, _arguments); })); }; } return item; })); }; _proto.ngOnInit = function() { var targetElement = this.elementRef.nativeElement; this.parent = init(this.getProps()); this.parent.render(targetElement, CONTEXT.IFRAME); }; _proto.ngDoCheck = function() { if (this.parent && !function(obj1, obj2) { var checked = {}; for (var key in obj1) if (obj1.hasOwnProperty(key)) { checked[key] = !0; if (obj1[key] !== obj2[key]) return !1; } for (var _key in obj2) if (!checked[_key]) return !1; return !0; }(this._props, this.props)) { this._props = _extends({}, this.props); this.parent.updateProps(this.getProps()); } }; return ComponentInstance; }(); ComponentInstance.annotations = void 0; ComponentInstance.parameters = void 0; ComponentInstance.parameters = [ [ new Inject(ElementRef) ], [ new Inject(NgZone) ] ]; ComponentInstance.annotations = [ new AngularComponent({ selector: tag, template: "
", inputs: [ "props" ] }) ]; var ModuleInstance = function() {}; ModuleInstance.annotations = void 0; ModuleInstance.annotations = [ new NgModule({ declarations: [ ComponentInstance ], exports: [ ComponentInstance ] }) ]; return ModuleInstance; } }; function defaultContainerTemplate(_ref) { var uid = _ref.uid, frame = _ref.frame, prerenderFrame = _ref.prerenderFrame, doc = _ref.doc, props = _ref.props, event = _ref.event, dimensions = _ref.dimensions; var width = dimensions.width, height = dimensions.height; if (frame && prerenderFrame) { var div = doc.createElement("div"); div.setAttribute("id", uid); var style = doc.createElement("style"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); style.appendChild(doc.createTextNode("\n #" + uid + " {\n display: inline-block;\n position: relative;\n width: " + width + ";\n height: " + height + ";\n }\n\n #" + uid + " > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #" + uid + " > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #" + uid + " > iframe.zoid-visible {\n opacity: 1;\n }\n ")); div.appendChild(frame); div.appendChild(prerenderFrame); div.appendChild(style); prerenderFrame.classList.add("zoid-visible"); frame.classList.add("zoid-invisible"); event.on(EVENT.RENDERED, (function() { prerenderFrame.classList.remove("zoid-visible"); prerenderFrame.classList.add("zoid-invisible"); frame.classList.remove("zoid-invisible"); frame.classList.add("zoid-visible"); setTimeout((function() { destroyElement(prerenderFrame); }), 1); })); event.on(EVENT.RESIZE, (function(_ref2) { var newWidth = _ref2.width, newHeight = _ref2.height; "number" == typeof newWidth && (div.style.width = toCSS(newWidth)); "number" == typeof newHeight && (div.style.height = toCSS(newHeight)); })); return div; } } function defaultPrerenderTemplate(_ref) { var doc = _ref.doc, props = _ref.props; var html = doc.createElement("html"); var body = doc.createElement("body"); var style = doc.createElement("style"); var spinner = doc.createElement("div"); spinner.classList.add("spinner"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); html.appendChild(body); body.appendChild(spinner); body.appendChild(style); style.appendChild(doc.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")); return html; } var cleanInstances = cleanup(); var cleanZoid = cleanup(); function component(opts) { var options = function(options) { var tag = options.tag, url = options.url, domain = options.domain, bridgeUrl = options.bridgeUrl, _options$props = options.props, props = void 0 === _options$props ? {} : _options$props, _options$dimensions = options.dimensions, dimensions = void 0 === _options$dimensions ? {} : _options$dimensions, _options$autoResize = options.autoResize, autoResize = void 0 === _options$autoResize ? {} : _options$autoResize, _options$allowedParen = options.allowedParentDomains, allowedParentDomains = void 0 === _options$allowedParen ? "*" : _options$allowedParen, _options$attributes = options.attributes, attributes = void 0 === _options$attributes ? {} : _options$attributes, _options$defaultConte = options.defaultContext, defaultContext = void 0 === _options$defaultConte ? CONTEXT.IFRAME : _options$defaultConte, _options$containerTem = options.containerTemplate, containerTemplate = void 0 === _options$containerTem ? defaultContainerTemplate : _options$containerTem, _options$prerenderTem = options.prerenderTemplate, prerenderTemplate = void 0 === _options$prerenderTem ? defaultPrerenderTemplate : _options$prerenderTem, validate = options.validate, _options$eligible = options.eligible, eligible = void 0 === _options$eligible ? function() { return { eligible: !0 }; } : _options$eligible, _options$logger = options.logger, logger = void 0 === _options$logger ? { info: src_util_noop } : _options$logger, _options$exports = options.exports, xportsDefinition = void 0 === _options$exports ? src_util_noop : _options$exports, method = options.method, _options$children = options.children, children = void 0 === _options$children ? function() { return {}; } : _options$children; var name = tag.replace(/-/g, "_"); var propsDef = _extends({}, { window: { type: PROP_TYPE.OBJECT, sendToChild: !1, required: !1, allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); if (utils_isWindow(value)) { if (utils_isWindowClosed(value)) throw new Error("Window is closed"); if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { return setup_toProxyWindow(_ref3.value); } }, timeout: { type: PROP_TYPE.NUMBER, required: !1, sendToChild: !1 }, cspNonce: { type: PROP_TYPE.STRING, required: !1 }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onRendered: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onRender: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onClose: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onDestroy: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onResize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, onFocus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, close: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref4) { return _ref4.close; } }, focus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref5) { return _ref5.focus; } }, resize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref6) { return _ref6.resize; } }, uid: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref7) { return _ref7.uid; } }, tag: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref8) { return _ref8.tag; } }, getParent: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref9) { return _ref9.getParent; } }, getParentDomain: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref10) { return _ref10.getParentDomain; } }, show: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref11) { return _ref11.show; } }, hide: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref12) { return _ref12.hide; } }, export: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref13) { return _ref13.export; } }, onError: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref14) { return _ref14.onError; } }, onProps: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref15) { return _ref15.onProps; } }, getSiblings: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref16) { return _ref16.getSiblings; } } }, props); if (!containerTemplate) throw new Error("Container template required"); return { name: name, tag: tag, url: url, domain: domain, bridgeUrl: bridgeUrl, method: method, propsDef: propsDef, dimensions: dimensions, autoResize: autoResize, allowedParentDomains: allowedParentDomains, attributes: attributes, defaultContext: defaultContext, containerTemplate: containerTemplate, prerenderTemplate: prerenderTemplate, validate: validate, logger: logger, eligible: eligible, children: children, exports: "function" == typeof xportsDefinition ? xportsDefinition : function(_ref) { var getExports = _ref.getExports; var result = {}; var _loop = function(_i2, _Object$keys2) { var key = _Object$keys2[_i2]; var type = xportsDefinition[key].type; var valuePromise = getExports().then((function(res) { return res[key]; })); result[key] = type === PROP_TYPE.FUNCTION ? function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return valuePromise.then((function(value) { return value.apply(void 0, args); })); } : valuePromise; }; for (var _i2 = 0, _Object$keys2 = Object.keys(xportsDefinition); _i2 < _Object$keys2.length; _i2++) _loop(_i2, _Object$keys2); return result; } }; }(opts); var name = options.name, tag = options.tag, defaultContext = options.defaultContext, propsDef = options.propsDef, eligible = options.eligible, children = options.children; var global = lib_global_getGlobal(window); var driverCache = {}; var instances = []; var isChild = function() { if (function(name) { try { return parseWindowName(window.name).name === name; } catch (err) {} return !1; }(name)) { var _payload = getInitialParentPayload().payload; if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; } return !1; }; var registerChild = memoize((function() { if (isChild()) { if (window.xprops) { delete global.components[tag]; throw new Error("Can not register " + name + " as child - child already registered"); } var child = function(options) { var tag = options.tag, propsDef = options.propsDef, autoResize = options.autoResize, allowedParentDomains = options.allowedParentDomains; var onPropHandlers = []; var _getInitialParentPayl = getInitialParentPayload(), parent = _getInitialParentPayl.parent, payload = _getInitialParentPayl.payload; var parentComponentWindow = parent.win, parentDomain = parent.domain; var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; }; var getParentDomain = function() { return parentDomain; }; var onProps = function(handler) { onPropHandlers.push(handler); return { cancel: function() { onPropHandlers.splice(onPropHandlers.indexOf(handler), 1); } }; }; var resize = function(_ref) { return parentResize.fireAndForget({ width: _ref.width, height: _ref.height }); }; var xport = function(xports) { exportsPromise.resolve(xports); return parentExport(xports); }; var getSiblings = function(_temp) { var anyParent = (void 0 === _temp ? {} : _temp).anyParent; var result = []; var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(win)) { var xprops = utils_assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { var xports = tryGlobal(win, (function(global) { return global.exports; })); result.push({ props: xprops, exports: xports }); } } } } return result; }; var setProps = function(newProps, origin, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var normalizedProps = function(parentComponentWindow, propsDef, props, origin, helpers, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); } } if (!isUpdate) for (var _i4 = 0, _Object$keys4 = Object.keys(propsDef); _i4 < _Object$keys4.length; _i4++) { var _key = _Object$keys4[_i4]; props.hasOwnProperty(_key) || (result[_key] = normalizeChildProp(propsDef, 0, _key, void 0, helpers)); } return result; }(parentComponentWindow, propsDef, newProps, origin, { tag: tag, show: show, hide: hide, close: close, focus: child_focus, onError: onError, resize: resize, getSiblings: getSiblings, onProps: onProps, getParent: getParent, getParentDomain: getParentDomain, uid: uid, export: xport }, isUpdate); props ? extend(props, normalizedProps) : props = normalizedProps; for (var _i4 = 0; _i4 < onPropHandlers.length; _i4++) (0, onPropHandlers[_i4])(props); }; var updateProps = function(newProps) { return promise_ZalgoPromise.try((function() { return setProps(newProps, parentDomain, !0); })); }; return { init: function() { return promise_ZalgoPromise.try((function() { utils_isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, sender: { win: parentComponentWindow }, basic: !0 }), sender = _crossDomainDeseriali2.sender; if ("uid" === _crossDomainDeseriali2.reference.type || "global" === _crossDomainDeseriali2.metaData.windowRef.type) { var _crossDomainSerialize = crossDomainSerialize({ data: _crossDomainDeseriali2.data, metaData: { windowRef: window_getWindowRef(parentComponentWindow) }, sender: { domain: sender.domain }, receiver: { win: window, domain: utils_getDomain() }, basic: !0 }); window.name = buildChildWindowName({ name: componentName, serializedPayload: _crossDomainSerialize.serializedData }); } }({ componentName: options.name, parentComponentWindow: parentComponentWindow }); lib_global_getGlobal(window).exports = options.exports({ getExports: function() { return exportsPromise; } }); !function(allowedParentDomains, domain) { if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { window.addEventListener("beforeunload", (function() { checkClose.fireAndForget(); })); window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); utils_onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); return parentInit({ updateProps: updateProps, close: child_destroy }); })).then((function() { return (_autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, elementReady(void 0 === _autoResize$element ? "body" : _autoResize$element).catch(src_util_noop).then((function(element) { return { width: width, height: height, element: element }; }))).then((function(_ref3) { var width = _ref3.width, height = _ref3.height, element = _ref3.element; element && (width || height) && context !== CONTEXT.POPUP && onResize(element, (function(_ref4) { resize({ width: width ? _ref4.width : void 0, height: height ? _ref4.height : void 0 }); }), { width: width, height: height }); })); var _autoResize$width, width, _autoResize$height, height, _autoResize$element; })).catch((function(err) { onError(err); })); }, getProps: function() { if (props) return props; setProps(initialProps, parentDomain); return props; } }; }(options); child.init(); return child; } })); var init = function init(inputProps) { var instance; var uid = "zoid-" + tag + "-" + uniqueID(); var props = inputProps || {}; var _eligible = eligible({ props: props }), eligibility = _eligible.eligible, reason = _eligible.reason; var onDestroy = props.onDestroy; props.onDestroy = function() { instance && eligibility && instances.splice(instances.indexOf(instance), 1); if (onDestroy) return onDestroy.apply(void 0, arguments); }; var parent = parentComponent({ uid: uid, options: options }); parent.init(); eligibility ? parent.setProps(props) : props.onDestroy && props.onDestroy(); cleanInstances.register((function(err) { return parent.destroy(err || new Error("zoid destroyed all components")); })); var clone = function(_temp) { var _ref4$decorate = (void 0 === _temp ? {} : _temp).decorate; return init((void 0 === _ref4$decorate ? identity : _ref4$decorate)(props)); }; var _render = function(target, container, context) { return promise_ZalgoPromise.try((function() { if (!eligibility) { var err = new Error(reason || name + " component is not eligible"); return parent.destroy(err).then((function() { throw err; })); } if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); if (context) { if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) throw new Error("Unrecognized context: " + context); return context; } return defaultContext; })); }(props, context); })).then((function(finalContext) { container = function(context, container) { if (container) { if ("string" != typeof container && !isElement(container)) throw new TypeError("Expected string or element selector to be passed"); return container; } if (context === CONTEXT.POPUP) return "body"; throw new Error("Expected element to be passed to render iframe"); }(finalContext, container); if (target !== window && "string" != typeof container) throw new Error("Must pass string element when rendering to another window"); return parent.render({ target: target, container: container, context: finalContext, rerender: function() { var newInstance = clone(); extend(instance, newInstance); return newInstance.renderTo(target, container, context); } }); })).catch((function(err) { return parent.destroy(err).then((function() { throw err; })); })); }; instance = _extends({}, parent.getExports(), parent.getHelpers(), function() { var childComponents = children(); var result = {}; var _loop2 = function(_i4, _Object$keys4) { var childName = _Object$keys4[_i4]; var Child = childComponents[childName]; result[childName] = function(childInputProps) { var parentProps = parent.getProps(); var childProps = _extends({}, childInputProps, { parent: { uid: uid, props: parentProps, export: parent.export } }); return Child(childProps); }; }; for (var _i4 = 0, _Object$keys4 = Object.keys(childComponents); _i4 < _Object$keys4.length; _i4++) _loop2(_i4, _Object$keys4); return result; }(), { isEligible: function() { return eligibility; }, clone: clone, render: function(container, context) { return _render(window, container, context); }, renderTo: function(target, container, context) { return _render(target, container, context); } }); eligibility && instances.push(instance); return instance; }; registerChild(); !function() { var allowDelegateListener = on_on("zoid_allow_delegate_" + name, (function() { return !0; })); var delegateListener = on_on("zoid_delegate_" + name, (function(_ref2) { var _ref2$data = _ref2.data; return { parent: parentComponent({ uid: _ref2$data.uid, options: options, overrides: _ref2$data.overrides, parentWin: _ref2.source }) }; })); cleanZoid.register(allowDelegateListener.cancel); cleanZoid.register(delegateListener.cancel); }(); global.components = global.components || {}; if (global.components[tag]) throw new Error("Can not register multiple components with the same tag: " + tag); global.components[tag] = !0; return { init: init, instances: instances, driver: function(driverName, dep) { var drivers = { react: react, angular: angular, vue: vue, vue3: vue3, angular2: angular2 }; if (!drivers[driverName]) throw new Error("Could not find driver for framework: " + driverName); driverCache[driverName] || (driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep)); return driverCache[driverName]; }, isChild: isChild, canRenderTo: function(win) { return send_send(win, "zoid_allow_delegate_" + name).then((function(_ref3) { return _ref3.data; })).catch((function() { return !1; })); }, registerChild: registerChild }; } var component_create = function(options) { !function() { if (!global_getGlobal().initialized) { global_getGlobal().initialized = !0; on = (_ref3 = { on: on_on, send: send_send }).on, send = _ref3.send, (global = global_getGlobal()).receiveMessage = global.receiveMessage || function(message) { return receive_receiveMessage(message, { on: on, send: send }); }; !function(_ref5) { var on = _ref5.on, send = _ref5.send; globalStore().getOrSet("postMessageListener", (function() { return addEventListener(window, "message", (function(event) { !function(event, _ref4) { var on = _ref4.on, send = _ref4.send; promise_ZalgoPromise.try((function() { var source = event.source || event.sourceElement; var origin = event.origin || event.originalEvent && event.originalEvent.origin; var data = event.data; "null" === origin && (origin = "file://"); if (source) { if (!origin) throw new Error("Post message did not have origin domain"); receive_receiveMessage({ source: source, origin: origin, data: data }, { on: on, send: send }); } })); }(event, { on: on, send: send }); })); })); }({ on: on_on, send: send_send }); !function(_ref8) { var on = _ref8.on, send = _ref8.send; globalStore("builtinListeners").getOrSet("helloListener", (function() { var listener = on("postrobot_hello", { domain: "*" }, (function(_ref3) { resolveHelloPromise(_ref3.source, { domain: _ref3.origin }); return { instanceID: getInstanceID() }; })); var parent = getAncestor(); parent && sayHello(parent, { send: send }).catch((function(err) {})); return listener; })); }({ on: on_on, send: send_send }); } var _ref3, on, send, global; }(); var comp = component(options); var init = function(props) { return comp.init(props); }; init.driver = function(name, dep) { return comp.driver(name, dep); }; init.isChild = function() { return comp.isChild(); }; init.canRenderTo = function(win) { return comp.canRenderTo(win); }; init.instances = comp.instances; var child = comp.registerChild(); child && (window.xprops = init.xprops = child.getProps()); return init; }; function destroyComponents(err) { var destroyPromise = cleanInstances.all(err); cleanInstances = cleanup(); return destroyPromise; } var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); delete window.__zoid_9_0_87__; !function() { !function() { var responseListeners = globalStore("responseListeners"); for (var _i2 = 0, _responseListeners$ke2 = responseListeners.keys(); _i2 < _responseListeners$ke2.length; _i2++) { var hash = _responseListeners$ke2[_i2]; var listener = responseListeners.get(hash); listener && (listener.cancelled = !0); responseListeners.del(hash); } }(); (listener = globalStore().get("postMessageListener")) && listener.cancel(); var listener; delete window.__post_robot_10_0_46__; }(); return cleanZoid.all(err); } } ]); })); ================================================ FILE: dist/zoid.frameworks.js ================================================ !function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define("zoid", [], factory) : "object" == typeof exports ? exports.zoid = factory() : root.zoid = factory(); }("undefined" != typeof self ? self : this, (function() { return function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module = installedModules[moduleId] = { i: moduleId, l: !1, exports: {} }; modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); module.l = !0; return module.exports; } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d = function(exports, name, getter) { __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, { enumerable: !0, get: getter }); }; __webpack_require__.r = function(exports) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); Object.defineProperty(exports, "__esModule", { value: !0 }); }; __webpack_require__.t = function(value, mode) { 1 & mode && (value = __webpack_require__(value)); if (8 & mode) return value; if (4 & mode && "object" == typeof value && value && value.__esModule) return value; var ns = Object.create(null); __webpack_require__.r(ns); Object.defineProperty(ns, "default", { enumerable: !0, value: value }); if (2 & mode && "string" != typeof value) for (var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); return ns; }; __webpack_require__.n = function(module) { var getter = module && module.__esModule ? function() { return module.default; } : function() { return module; }; __webpack_require__.d(getter, "a", getter); return getter; }; __webpack_require__.o = function(object, property) { return {}.hasOwnProperty.call(object, property); }; __webpack_require__.p = ""; return __webpack_require__(__webpack_require__.s = 0); }([ function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, "PopupOpenError", (function() { return dom_PopupOpenError; })); __webpack_require__.d(__webpack_exports__, "create", (function() { return component_create; })); __webpack_require__.d(__webpack_exports__, "destroy", (function() { return component_destroy; })); __webpack_require__.d(__webpack_exports__, "destroyComponents", (function() { return destroyComponents; })); __webpack_require__.d(__webpack_exports__, "destroyAll", (function() { return destroyAll; })); __webpack_require__.d(__webpack_exports__, "PROP_TYPE", (function() { return PROP_TYPE; })); __webpack_require__.d(__webpack_exports__, "PROP_SERIALIZATION", (function() { return PROP_SERIALIZATION; })); __webpack_require__.d(__webpack_exports__, "CONTEXT", (function() { return CONTEXT; })); __webpack_require__.d(__webpack_exports__, "EVENT", (function() { return EVENT; })); function _setPrototypeOf(o, p) { return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) { o.__proto__ = p; return o; })(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _extends() { return (_extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) ({}).hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }).apply(this, arguments); } function utils_isPromise(item) { try { if (!item) return !1; if ("undefined" != typeof Promise && item instanceof Promise) return !0; if ("undefined" != typeof window && "function" == typeof window.Window && item instanceof window.Window) return !1; if ("undefined" != typeof window && "function" == typeof window.constructor && item instanceof window.constructor) return !1; var _toString = {}.toString; if (_toString) { var name = _toString.call(item); if ("[object Window]" === name || "[object global]" === name || "[object DOMWindow]" === name) return !1; } if ("function" == typeof item.then) return !0; } catch (err) { return !1; } return !1; } var dispatchedErrors = []; var possiblyUnhandledPromiseHandlers = []; var activeCount = 0; var flushPromise; function flushActive() { if (!activeCount && flushPromise) { var promise = flushPromise; flushPromise = null; promise.resolve(); } } function startActive() { activeCount += 1; } function endActive() { activeCount -= 1; flushActive(); } var promise_ZalgoPromise = function() { function ZalgoPromise(handler) { var _this = this; this.resolved = void 0; this.rejected = void 0; this.errorHandled = void 0; this.value = void 0; this.error = void 0; this.handlers = void 0; this.dispatching = void 0; this.stack = void 0; this.resolved = !1; this.rejected = !1; this.errorHandled = !1; this.handlers = []; if (handler) { var _result; var _error; var resolved = !1; var rejected = !1; var isAsync = !1; startActive(); try { handler((function(res) { if (isAsync) _this.resolve(res); else { resolved = !0; _result = res; } }), (function(err) { if (isAsync) _this.reject(err); else { rejected = !0; _error = err; } })); } catch (err) { endActive(); this.reject(err); return; } endActive(); isAsync = !0; resolved ? this.resolve(_result) : rejected && this.reject(_error); } } var _proto = ZalgoPromise.prototype; _proto.resolve = function(result) { if (this.resolved || this.rejected) return this; if (utils_isPromise(result)) throw new Error("Can not resolve promise with another promise"); this.resolved = !0; this.value = result; this.dispatch(); return this; }; _proto.reject = function(error) { var _this2 = this; if (this.resolved || this.rejected) return this; if (utils_isPromise(error)) throw new Error("Can not reject promise with another promise"); if (!error) { var _err = error && "function" == typeof error.toString ? error.toString() : {}.toString.call(error); error = new Error("Expected reject to be called with Error, got " + _err); } this.rejected = !0; this.error = error; this.errorHandled || setTimeout((function() { _this2.errorHandled || function(err, promise) { if (-1 === dispatchedErrors.indexOf(err)) { dispatchedErrors.push(err); setTimeout((function() { throw err; }), 1); for (var j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) possiblyUnhandledPromiseHandlers[j](err, promise); } }(error, _this2); }), 1); this.dispatch(); return this; }; _proto.asyncReject = function(error) { this.errorHandled = !0; this.reject(error); return this; }; _proto.dispatch = function() { var resolved = this.resolved, rejected = this.rejected, handlers = this.handlers; if (!this.dispatching && (resolved || rejected)) { this.dispatching = !0; startActive(); var chain = function(firstPromise, secondPromise) { return firstPromise.then((function(res) { secondPromise.resolve(res); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < handlers.length; i++) { var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise; var _result2 = void 0; if (resolved) try { _result2 = onSuccess ? onSuccess(this.value) : this.value; } catch (err) { promise.reject(err); continue; } else if (rejected) { if (!onError) { promise.reject(this.error); continue; } try { _result2 = onError(this.error); } catch (err) { promise.reject(err); continue; } } if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) { var promiseResult = _result2; promiseResult.resolved ? promise.resolve(promiseResult.value) : promise.reject(promiseResult.error); promiseResult.errorHandled = !0; } else utils_isPromise(_result2) ? _result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected) ? _result2.resolved ? promise.resolve(_result2.value) : promise.reject(_result2.error) : chain(_result2, promise) : promise.resolve(_result2); } handlers.length = 0; this.dispatching = !1; endActive(); } }; _proto.then = function(onSuccess, onError) { if (onSuccess && "function" != typeof onSuccess && !onSuccess.call) throw new Error("Promise.then expected a function for success handler"); if (onError && "function" != typeof onError && !onError.call) throw new Error("Promise.then expected a function for error handler"); var promise = new ZalgoPromise; this.handlers.push({ promise: promise, onSuccess: onSuccess, onError: onError }); this.errorHandled = !0; this.dispatch(); return promise; }; _proto.catch = function(onError) { return this.then(void 0, onError); }; _proto.finally = function(onFinally) { if (onFinally && "function" != typeof onFinally && !onFinally.call) throw new Error("Promise.finally expected a function"); return this.then((function(result) { return ZalgoPromise.try(onFinally).then((function() { return result; })); }), (function(err) { return ZalgoPromise.try(onFinally).then((function() { throw err; })); })); }; _proto.timeout = function(time, err) { var _this3 = this; if (this.resolved || this.rejected) return this; var timeout = setTimeout((function() { _this3.resolved || _this3.rejected || _this3.reject(err || new Error("Promise timed out after " + time + "ms")); }), time); return this.then((function(result) { clearTimeout(timeout); return result; })); }; _proto.toPromise = function() { if ("undefined" == typeof Promise) throw new TypeError("Could not find Promise"); return Promise.resolve(this); }; _proto.lazy = function() { this.errorHandled = !0; return this; }; ZalgoPromise.resolve = function(value) { return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise((function(resolve, reject) { return value.then(resolve, reject); })) : (new ZalgoPromise).resolve(value); }; ZalgoPromise.reject = function(error) { return (new ZalgoPromise).reject(error); }; ZalgoPromise.asyncReject = function(error) { return (new ZalgoPromise).asyncReject(error); }; ZalgoPromise.all = function(promises) { var promise = new ZalgoPromise; var count = promises.length; var results = [].slice(); if (!count) { promise.resolve(results); return promise; } var chain = function(i, firstPromise, secondPromise) { return firstPromise.then((function(res) { results[i] = res; 0 == (count -= 1) && promise.resolve(results); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < promises.length; i++) { var prom = promises[i]; if (prom instanceof ZalgoPromise) { if (prom.resolved) { results[i] = prom.value; count -= 1; continue; } } else if (!utils_isPromise(prom)) { results[i] = prom; count -= 1; continue; } chain(i, ZalgoPromise.resolve(prom), promise); } 0 === count && promise.resolve(results); return promise; }; ZalgoPromise.hash = function(promises) { var result = {}; var awaitPromises = []; var _loop = function(key) { if (promises.hasOwnProperty(key)) { var value = promises[key]; utils_isPromise(value) ? awaitPromises.push(value.then((function(res) { result[key] = res; }))) : result[key] = value; } }; for (var key in promises) _loop(key); return ZalgoPromise.all(awaitPromises).then((function() { return result; })); }; ZalgoPromise.map = function(items, method) { return ZalgoPromise.all(items.map(method)); }; ZalgoPromise.onPossiblyUnhandledException = function(handler) { return function(handler) { possiblyUnhandledPromiseHandlers.push(handler); return { cancel: function() { possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1); } }; }(handler); }; ZalgoPromise.try = function(method, context, args) { if (method && "function" != typeof method && !method.call) throw new Error("Promise.try expected a function"); var result; startActive(); try { result = method.apply(context, args || []); } catch (err) { endActive(); return ZalgoPromise.reject(err); } endActive(); return ZalgoPromise.resolve(result); }; ZalgoPromise.delay = function(_delay) { return new ZalgoPromise((function(resolve) { setTimeout(resolve, _delay); })); }; ZalgoPromise.isPromise = function(value) { return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value); }; ZalgoPromise.flush = function() { return function(Zalgo) { var promise = flushPromise = flushPromise || new Zalgo; flushActive(); return promise; }(ZalgoPromise); }; return ZalgoPromise; }(); function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return getActualProtocol(win); } function isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === getProtocol(win); } function utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function getOpener(win) { void 0 === win && (win = window); if (win && !utils_getParent(win)) try { return win.opener; } catch (err) {} } function canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = utils_getParent(win); return parent && canReadFromWindow() ? getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function getDomain(win) { void 0 === win && (win = window); var domain = getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (isAboutProtocol(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === getProtocol(win); }(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (getActualDomain(win) === getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (isAboutProtocol(win) && canReadFromWindow()) return !0; if (getDomain(window) === getDomain(win)) return !0; } catch (err) {} return !1; } function assertSameDomain(win) { if (!isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (utils_getParent(win) === win) return win; try { if (isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (utils_getParent(frame) === frame) return frame; } } function getAllFramesInWindow(win) { var top = getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], getAllChildFrames(win))); return result; } var iframeWindows = []; var iframeFrames = []; function isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || err.message !== IE_WIN_ACCESS_ERROR; } if (allowMock && isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(iframeWindows, win); if (-1 !== iframeIndex) { var frame = iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function utils_getUserAgent(win) { return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent; } function getFrameByName(win, name) { var winFrames = getFrames(win); for (var _i9 = 0; _i9 < winFrames.length; _i9++) { var childFrame = winFrames[_i9]; try { if (isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; } catch (err) {} } try { if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; } catch (err) {} try { if (-1 !== winFrames.indexOf(win[name])) return win[name]; } catch (err) {} } function isOpener(parent, child) { return parent === getOpener(child); } function getAncestor(win) { void 0 === win && (win = window); return getOpener(win = win || window) || utils_getParent(win) || void 0; } function anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function isSameTopWindow(win1, win2) { var top1 = getTop(win1) || win1; var top2 = getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = getAllFramesInWindow(win1); var allFrames2 = getAllFramesInWindow(win2); if (anyMatch(allFrames1, allFrames2)) return !0; var opener1 = getOpener(top1); var opener2 = getOpener(top2); return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), !1; } function matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some((function(subpattern) { return matchDomain(subpattern, origin); }))); } function getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain(); } function isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function getFrameForWindow(win) { if (isSameDomain(win)) return assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { var frame = _document$querySelect2[_i21]; if (frame && frame.contentWindow && frame.contentWindow === win) return frame; } } function closeWindow(win) { if (function(win) { void 0 === win && (win = window); return Boolean(utils_getParent(win)); }(win)) { var frame = getFrameForWindow(win); if (frame && frame.parentElement) { frame.parentElement.removeChild(frame); return; } } try { win.close(); } catch (err) {} } function util_safeIndexOf(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; } var weakmap_CrossDomainSafeWeakMap = function() { function CrossDomainSafeWeakMap() { this.name = void 0; this.weakmap = void 0; this.keys = void 0; this.values = void 0; this.name = "__weakmap_" + (1e9 * Math.random() >>> 0) + "__"; if (function() { if ("undefined" == typeof WeakMap) return !1; if (void 0 === Object.freeze) return !1; try { var testWeakMap = new WeakMap; var testKey = {}; Object.freeze(testKey); testWeakMap.set(testKey, "__testvalue__"); return "__testvalue__" === testWeakMap.get(testKey); } catch (err) { return !1; } }()) try { this.weakmap = new WeakMap; } catch (err) {} this.keys = []; this.values = []; } var _proto = CrossDomainSafeWeakMap.prototype; _proto._cleanupClosedWindows = function() { var weakmap = this.weakmap; var keys = this.keys; for (var i = 0; i < keys.length; i++) { var value = keys[i]; if (isWindow(value) && isWindowClosed(value)) { if (weakmap) try { weakmap.delete(value); } catch (err) {} keys.splice(i, 1); this.values.splice(i, 1); i -= 1; } } }; _proto.isSafeToReadWrite = function(key) { return !isWindow(key); }; _proto.set = function(key, value) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.set(key, value); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var name = this.name; var entry = key[name]; entry && entry[0] === key ? entry[1] = value : Object.defineProperty(key, name, { value: [ key, value ], writable: !0 }); return; } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var values = this.values; var index = util_safeIndexOf(keys, key); if (-1 === index) { keys.push(key); values.push(value); } else values[index] = value; }; _proto.get = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return weakmap.get(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return entry && entry[0] === key ? entry[1] : void 0; } catch (err) {} this._cleanupClosedWindows(); var index = util_safeIndexOf(this.keys, key); if (-1 !== index) return this.values[index]; }; _proto.delete = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.delete(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; entry && entry[0] === key && (entry[0] = entry[1] = void 0); } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var index = util_safeIndexOf(keys, key); if (-1 !== index) { keys.splice(index, 1); this.values.splice(index, 1); } }; _proto.has = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return !0; } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return !(!entry || entry[0] !== key); } catch (err) {} this._cleanupClosedWindows(); return -1 !== util_safeIndexOf(this.keys, key); }; _proto.getOrSet = function(key, getter) { if (this.has(key)) return this.get(key); var value = getter(); this.set(key, value); return value; }; return CrossDomainSafeWeakMap; }(); function _getPrototypeOf(o) { return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) { return o.__proto__ || Object.getPrototypeOf(o); })(o); } function _isNativeReflectConstruct() { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { Date.prototype.toString.call(Reflect.construct(Date, [], (function() {}))); return !0; } catch (e) { return !1; } } function construct_construct(Parent, args, Class) { return (construct_construct = _isNativeReflectConstruct() ? Reflect.construct : function(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var instance = new (Function.bind.apply(Parent, a)); Class && _setPrototypeOf(instance, Class.prototype); return instance; }).apply(null, arguments); } function wrapNativeSuper_wrapNativeSuper(Class) { var _cache = "function" == typeof Map ? new Map : void 0; return (wrapNativeSuper_wrapNativeSuper = function(Class) { if (null === Class || !(fn = Class, -1 !== Function.toString.call(fn).indexOf("[native code]"))) return Class; var fn; if ("function" != typeof Class) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== _cache) { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct_construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }); return _setPrototypeOf(Wrapper, Class); })(Class); } function isElement(element) { var passed = !1; try { (element instanceof window.Element || null !== element && "object" == typeof element && 1 === element.nodeType && "object" == typeof element.style && "object" == typeof element.ownerDocument) && (passed = !0); } catch (_) {} return passed; } function getFunctionName(fn) { return fn.name || fn.__name__ || fn.displayName || "anonymous"; } function setFunctionName(fn, name) { try { delete fn.name; fn.name = name; } catch (err) {} fn.__name__ = fn.displayName = name; return fn; } function base64encode(str) { if ("function" == typeof btoa) return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (function(m, p1) { return String.fromCharCode(parseInt(p1, 16)); }))).replace(/[=]/g, ""); if ("undefined" != typeof Buffer) return Buffer.from(str, "utf8").toString("base64").replace(/[=]/g, ""); throw new Error("Can not find window.btoa or Buffer"); } function uniqueID() { var chars = "0123456789abcdef"; return "uid_" + "xxxxxxxxxx".replace(/./g, (function() { return chars.charAt(Math.floor(Math.random() * chars.length)); })) + "_" + base64encode((new Date).toISOString().slice(11, 19).replace("T", ".")).replace(/[^a-zA-Z0-9]/g, "").toLowerCase(); } var objectIDs; function serializeArgs(args) { try { return JSON.stringify([].slice.call(args), (function(subkey, val) { return "function" == typeof val ? "memoize[" + function(obj) { objectIDs = objectIDs || new weakmap_CrossDomainSafeWeakMap; if (null == obj || "object" != typeof obj && "function" != typeof obj) throw new Error("Invalid object"); var uid = objectIDs.get(obj); if (!uid) { uid = typeof obj + ":" + uniqueID(); objectIDs.set(obj, uid); } return uid; }(val) + "]" : isElement(val) ? {} : val; })); } catch (err) { throw new Error("Arguments not serializable -- can not be used to memoize"); } } function getEmptyObject() { return {}; } var memoizeGlobalIndex = 0; var memoizeGlobalIndexValidFrom = 0; function memoize(method, options) { void 0 === options && (options = {}); var _options$thisNamespac = options.thisNamespace, thisNamespace = void 0 !== _options$thisNamespac && _options$thisNamespac, cacheTime = options.time; var simpleCache; var thisCache; var memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; var memoizedFunction = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; if (memoizeIndex < memoizeGlobalIndexValidFrom) { simpleCache = null; thisCache = null; memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; } var cache; cache = thisNamespace ? (thisCache = thisCache || new weakmap_CrossDomainSafeWeakMap).getOrSet(this, getEmptyObject) : simpleCache = simpleCache || {}; var cacheKey; try { cacheKey = serializeArgs(args); } catch (_unused) { return method.apply(this, arguments); } var cacheResult = cache[cacheKey]; if (cacheResult && cacheTime && Date.now() - cacheResult.time < cacheTime) { delete cache[cacheKey]; cacheResult = null; } if (cacheResult) return cacheResult.value; var time = Date.now(); var value = method.apply(this, arguments); cache[cacheKey] = { time: time, value: value }; return value; }; memoizedFunction.reset = function() { simpleCache = null; thisCache = null; }; return setFunctionName(memoizedFunction, (options.name || getFunctionName(method)) + "::memoized"); } memoize.clear = function() { memoizeGlobalIndexValidFrom = memoizeGlobalIndex; }; function memoizePromise(method) { var cache = {}; function memoizedPromiseFunction() { var _arguments = arguments, _this = this; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; var key = serializeArgs(args); if (cache.hasOwnProperty(key)) return cache[key]; cache[key] = promise_ZalgoPromise.try((function() { return method.apply(_this, _arguments); })).finally((function() { delete cache[key]; })); return cache[key]; } memoizedPromiseFunction.reset = function() { cache = {}; }; return setFunctionName(memoizedPromiseFunction, getFunctionName(method) + "::promiseMemoized"); } function src_util_noop() {} function once(method) { var called = !1; return setFunctionName((function() { if (!called) { called = !0; return method.apply(this, arguments); } }), getFunctionName(method) + "::once"); } function stringifyError(err, level) { void 0 === level && (level = 1); if (level >= 3) return "stringifyError stack overflow"; try { if (!err) return ""; if ("string" == typeof err) return err; if (err instanceof Error) { var stack = err && err.stack; var message = err && err.message; if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + "\n" + stack; if (stack) return stack; if (message) return message; } return err && err.toString && "function" == typeof err.toString ? err.toString() : {}.toString.call(err); } catch (newErr) { return "Error while stringifying error: " + stringifyError(newErr, level + 1); } } function stringify(item) { return "string" == typeof item ? item : item && item.toString && "function" == typeof item.toString ? item.toString() : {}.toString.call(item); } function extend(obj, source) { if (!source) return obj; if (Object.assign) return Object.assign(obj, source); for (var key in source) source.hasOwnProperty(key) && (obj[key] = source[key]); return obj; } memoize((function(obj) { if (Object.values) return Object.values(obj); var result = []; for (var key in obj) obj.hasOwnProperty(key) && result.push(obj[key]); return result; })); function identity(item) { return item; } function safeInterval(method, time) { var timeout; !function loop() { timeout = setTimeout((function() { method(); loop(); }), time); }(); return { cancel: function() { clearTimeout(timeout); } }; } function dasherizeToCamel(string) { return string.replace(/-([a-z])/g, (function(g) { return g[1].toUpperCase(); })); } function defineLazyProp(obj, key, getter) { if (Array.isArray(obj)) { if ("number" != typeof key) throw new TypeError("Array key must be number"); } else if ("object" == typeof obj && null !== obj && "string" != typeof key) throw new TypeError("Object key must be string"); Object.defineProperty(obj, key, { configurable: !0, enumerable: !0, get: function() { delete obj[key]; var value = getter(); obj[key] = value; return value; }, set: function(value) { delete obj[key]; obj[key] = value; } }); } function arrayFrom(item) { return [].slice.call(item); } function isObjectObject(obj) { return "object" == typeof (item = obj) && null !== item && "[object Object]" === {}.toString.call(obj); var item; } function isPlainObject(obj) { if (!isObjectObject(obj)) return !1; var constructor = obj.constructor; if ("function" != typeof constructor) return !1; var prototype = constructor.prototype; return !!isObjectObject(prototype) && !!prototype.hasOwnProperty("isPrototypeOf"); } function replaceObject(item, replacer, fullKey) { void 0 === fullKey && (fullKey = ""); if (Array.isArray(item)) { var length = item.length; var result = []; var _loop2 = function(i) { defineLazyProp(result, i, (function() { var itemKey = fullKey ? fullKey + "." + i : "" + i; var child = replacer(item[i], i, itemKey); (isPlainObject(child) || Array.isArray(child)) && (child = replaceObject(child, replacer, itemKey)); return child; })); }; for (var i = 0; i < length; i++) _loop2(i); return result; } if (isPlainObject(item)) { var _result = {}; var _loop3 = function(key) { if (!item.hasOwnProperty(key)) return "continue"; defineLazyProp(_result, key, (function() { var itemKey = fullKey ? fullKey + "." + key : "" + key; var child = replacer(item[key], key, itemKey); (isPlainObject(child) || Array.isArray(child)) && (child = replaceObject(child, replacer, itemKey)); return child; })); }; for (var key in item) _loop3(key); return _result; } throw new Error("Pass an object or array"); } function isDefined(value) { return null != value; } function util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function util_getOrSet(obj, key, getter) { if (obj.hasOwnProperty(key)) return obj[key]; var val = getter(); obj[key] = val; return val; } function cleanup(obj) { var tasks = []; var cleaned = !1; var cleanErr; var cleaner = { set: function(name, item) { if (!cleaned) { obj[name] = item; cleaner.register((function() { delete obj[name]; })); } return item; }, register: function(method) { var task = once((function() { return method(cleanErr); })); cleaned ? method(cleanErr) : tasks.push(task); return { cancel: function() { var index = tasks.indexOf(task); -1 !== index && tasks.splice(index, 1); } }; }, all: function(err) { cleanErr = err; var results = []; cleaned = !0; for (;tasks.length; ) { var task = tasks.shift(); results.push(task()); } return promise_ZalgoPromise.all(results).then(src_util_noop); } }; return cleaner; } function assertExists(name, thing) { if (null == thing) throw new Error("Expected " + name + " to be present"); return thing; } var util_ExtendableError = function(_Error) { _inheritsLoose(ExtendableError, _Error); function ExtendableError(message) { var _this6; (_this6 = _Error.call(this, message) || this).name = _this6.constructor.name; "function" == typeof Error.captureStackTrace ? Error.captureStackTrace(function(self) { if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; }(_this6), _this6.constructor) : _this6.stack = new Error(message).stack; return _this6; } return ExtendableError; }(wrapNativeSuper_wrapNativeSuper(Error)); function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); return body; } function isDocumentReady() { return Boolean(document.body) && "complete" === document.readyState; } function isDocumentInteractive() { return Boolean(document.body) && "interactive" === document.readyState; } function urlEncode(str) { return encodeURIComponent(str); } memoize((function() { return new promise_ZalgoPromise((function(resolve) { if (isDocumentReady() || isDocumentInteractive()) return resolve(); var interval = setInterval((function() { if (isDocumentReady() || isDocumentInteractive()) { clearInterval(interval); return resolve(); } }), 10); })); })); function parseQuery(queryString) { return function(method, logic, args) { void 0 === args && (args = []); var cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {}; var key = serializeArgs(args); return cache.hasOwnProperty(key) ? cache[key] : cache[key] = function() { var params = {}; if (!queryString) return params; if (-1 === queryString.indexOf("=")) return params; for (var _i2 = 0, _queryString$split2 = queryString.split("&"); _i2 < _queryString$split2.length; _i2++) { var pair = _queryString$split2[_i2]; (pair = pair.split("="))[0] && pair[1] && (params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1])); } return params; }.apply(void 0, args); }(parseQuery, 0, [ queryString ]); } function extendQuery(originalQuery, props) { void 0 === props && (props = {}); return props && Object.keys(props).length ? function(obj) { void 0 === obj && (obj = {}); return Object.keys(obj).filter((function(key) { return "string" == typeof obj[key] || "boolean" == typeof obj[key]; })).map((function(key) { var val = obj[key]; if ("string" != typeof val && "boolean" != typeof val) throw new TypeError("Invalid type for query"); return urlEncode(key) + "=" + urlEncode(val.toString()); })).join("&"); }(_extends({}, parseQuery(originalQuery), props)) : originalQuery; } function appendChild(container, child) { container.appendChild(child); } function getElementSafe(id, doc) { void 0 === doc && (doc = document); return isElement(id) ? id : "string" == typeof id ? doc.querySelector(id) : void 0; } function elementReady(id) { return new promise_ZalgoPromise((function(resolve, reject) { var name = stringify(id); var el = getElementSafe(id); if (el) return resolve(el); if (isDocumentReady()) return reject(new Error("Document is ready and element " + name + " does not exist")); var interval = setInterval((function() { if (el = getElementSafe(id)) { resolve(el); clearInterval(interval); } else if (isDocumentReady()) { clearInterval(interval); return reject(new Error("Document is ready and element " + name + " does not exist")); } }), 10); })); } var dom_PopupOpenError = function(_ExtendableError) { _inheritsLoose(PopupOpenError, _ExtendableError); function PopupOpenError() { return _ExtendableError.apply(this, arguments) || this; } return PopupOpenError; }(util_ExtendableError); var awaitFrameLoadPromises; function awaitFrameLoad(frame) { if ((awaitFrameLoadPromises = awaitFrameLoadPromises || new weakmap_CrossDomainSafeWeakMap).has(frame)) { var _promise = awaitFrameLoadPromises.get(frame); if (_promise) return _promise; } var promise = new promise_ZalgoPromise((function(resolve, reject) { frame.addEventListener("load", (function() { !function(frame) { !function() { for (var i = 0; i < iframeWindows.length; i++) { var closed = !1; try { closed = iframeWindows[i].closed; } catch (err) {} if (closed) { iframeFrames.splice(i, 1); iframeWindows.splice(i, 1); } } }(); if (frame && frame.contentWindow) try { iframeWindows.push(frame.contentWindow); iframeFrames.push(frame); } catch (err) {} }(frame); resolve(frame); })); frame.addEventListener("error", (function(err) { frame.contentWindow ? resolve(frame) : reject(err); })); })); awaitFrameLoadPromises.set(frame, promise); return promise; } function awaitFrameWindow(frame) { return awaitFrameLoad(frame).then((function(loadedFrame) { if (!loadedFrame.contentWindow) throw new Error("Could not find window in iframe"); return loadedFrame.contentWindow; })); } function dom_iframe(options, container) { void 0 === options && (options = {}); var style = options.style || {}; var frame = function(tag, options, container) { void 0 === tag && (tag = "div"); void 0 === options && (options = {}); tag = tag.toLowerCase(); var element = document.createElement(tag); options.style && extend(element.style, options.style); options.class && (element.className = options.class.join(" ")); options.id && element.setAttribute("id", options.id); if (options.attributes) for (var _i10 = 0, _Object$keys2 = Object.keys(options.attributes); _i10 < _Object$keys2.length; _i10++) { var key = _Object$keys2[_i10]; element.setAttribute(key, options.attributes[key]); } options.styleSheet && function(el, styleText, doc) { void 0 === doc && (doc = window.document); el.styleSheet ? el.styleSheet.cssText = styleText : el.appendChild(doc.createTextNode(styleText)); }(element, options.styleSheet); if (options.html) { if ("iframe" === tag) throw new Error("Iframe html can not be written unless container provided and iframe in DOM"); element.innerHTML = options.html; } return element; }("iframe", { attributes: _extends({ allowTransparency: "true" }, options.attributes || {}), style: _extends({ backgroundColor: "transparent", border: "none" }, style), html: options.html, class: options.class }); var isIE = window.navigator.userAgent.match(/MSIE|Edge/i); frame.hasAttribute("id") || frame.setAttribute("id", uniqueID()); awaitFrameLoad(frame); container && function(id, doc) { void 0 === doc && (doc = document); var element = getElementSafe(id, doc); if (element) return element; throw new Error("Can not find element: " + stringify(id)); }(container).appendChild(frame); (options.url || isIE) && frame.setAttribute("src", options.url || "about:blank"); return frame; } function addEventListener(obj, event, handler) { obj.addEventListener(event, handler); return { cancel: function() { obj.removeEventListener(event, handler); } }; } function showElement(element) { element.style.setProperty("display", ""); } function hideElement(element) { element.style.setProperty("display", "none", "important"); } function destroyElement(element) { element && element.parentNode && element.parentNode.removeChild(element); } function isElementClosed(el) { return !(el && el.parentNode && el.ownerDocument && el.ownerDocument.documentElement && el.ownerDocument.documentElement.contains(el)); } function onResize(el, handler, _temp) { var _ref2 = void 0 === _temp ? {} : _temp, _ref2$width = _ref2.width, width = void 0 === _ref2$width || _ref2$width, _ref2$height = _ref2.height, height = void 0 === _ref2$height || _ref2$height, _ref2$interval = _ref2.interval, interval = void 0 === _ref2$interval ? 100 : _ref2$interval, _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win; var currentWidth = el.offsetWidth; var currentHeight = el.offsetHeight; var canceled = !1; handler({ width: currentWidth, height: currentHeight }); var check = function() { if (!canceled && function(el) { return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length); }(el)) { var newWidth = el.offsetWidth; var newHeight = el.offsetHeight; (width && newWidth !== currentWidth || height && newHeight !== currentHeight) && handler({ width: newWidth, height: newHeight }); currentWidth = newWidth; currentHeight = newHeight; } }; var observer; var timeout; win.addEventListener("resize", check); if (void 0 !== win.ResizeObserver) { (observer = new win.ResizeObserver(check)).observe(el); timeout = safeInterval(check, 10 * interval); } else if (void 0 !== win.MutationObserver) { (observer = new win.MutationObserver(check)).observe(el, { attributes: !0, childList: !0, subtree: !0, characterData: !1 }); timeout = safeInterval(check, 10 * interval); } else timeout = safeInterval(check, interval); return { cancel: function() { canceled = !0; observer.disconnect(); window.removeEventListener("resize", check); timeout.cancel(); } }; } function isShadowElement(element) { for (;element.parentNode; ) element = element.parentNode; return "[object ShadowRoot]" === element.toString(); } var currentScript = "undefined" != typeof document ? document.currentScript : null; var getCurrentScript = memoize((function() { if (currentScript) return currentScript; if (currentScript = function() { try { var stack = function() { try { throw new Error("_"); } catch (err) { return err.stack || ""; } }(); var stackDetails = /.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(stack); var scriptLocation = stackDetails && stackDetails[1]; if (!scriptLocation) return; for (var _i22 = 0, _Array$prototype$slic2 = [].slice.call(document.getElementsByTagName("script")).reverse(); _i22 < _Array$prototype$slic2.length; _i22++) { var script = _Array$prototype$slic2[_i22]; if (script.src && script.src === scriptLocation) return script; } } catch (err) {} }()) return currentScript; throw new Error("Can not determine current script"); })); var currentUID = uniqueID(); memoize((function() { var script; try { script = getCurrentScript(); } catch (err) { return currentUID; } var uid = script.getAttribute("data-uid"); if (uid && "string" == typeof uid) return uid; if ((uid = script.getAttribute("data-uid-auto")) && "string" == typeof uid) return uid; if (script.src) { var hashedString = function(str) { var hash = ""; for (var i = 0; i < str.length; i++) { var total = str[i].charCodeAt(0) * i; str[i + 1] && (total += str[i + 1].charCodeAt(0) * (i - 1)); hash += String.fromCharCode(97 + Math.abs(total) % 26); } return hash; }(JSON.stringify({ src: script.src, dataset: script.dataset })); uid = "uid_" + hashedString.slice(hashedString.length - 30); } else uid = uniqueID(); script.setAttribute("data-uid-auto", uid); return uid; })); function isPerc(str) { return "string" == typeof str && /^[0-9]+%$/.test(str); } function toNum(val) { if ("number" == typeof val) return val; var match = val.match(/^([0-9]+)(px|%)$/); if (!match) throw new Error("Could not match css value from " + val); return parseInt(match[1], 10); } function toPx(val) { return toNum(val) + "px"; } function toCSS(val) { return "number" == typeof val ? toPx(val) : isPerc(val) ? val : toPx(val); } function normalizeDimension(dim, max) { if ("number" == typeof dim) return dim; if (isPerc(dim)) return parseInt(max * toNum(dim) / 100, 10); if ("string" == typeof (str = dim) && /^[0-9]+px$/.test(str)) return toNum(dim); var str; throw new Error("Can not normalize dimension: " + dim); } function global_getGlobal(win) { void 0 === win && (win = window); var globalKey = "__post_robot_10_0_46__"; return win !== window ? win[globalKey] : win[globalKey] = win[globalKey] || {}; } var getObj = function() { return {}; }; function globalStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return util_getOrSet(global_getGlobal(), key, (function() { var store = defStore(); return { has: function(storeKey) { return store.hasOwnProperty(storeKey); }, get: function(storeKey, defVal) { return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal; }, set: function(storeKey, val) { store[storeKey] = val; return val; }, del: function(storeKey) { delete store[storeKey]; }, getOrSet: function(storeKey, getter) { return util_getOrSet(store, storeKey, getter); }, reset: function() { store = defStore(); }, keys: function() { return Object.keys(store); } }; })); } var WildCard = function() {}; function getWildcard() { var global = global_getGlobal(); global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard; return global.WINDOW_WILDCARD; } function windowStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return globalStore("windowStore").getOrSet(key, (function() { var winStore = new weakmap_CrossDomainSafeWeakMap; var getStore = function(win) { return winStore.getOrSet(win, defStore); }; return { has: function(win) { return getStore(win).hasOwnProperty(key); }, get: function(win, defVal) { var store = getStore(win); return store.hasOwnProperty(key) ? store[key] : defVal; }, set: function(win, val) { getStore(win)[key] = val; return val; }, del: function(win) { delete getStore(win)[key]; }, getOrSet: function(win, getter) { return util_getOrSet(getStore(win), key, getter); } }; })); } function getInstanceID() { return globalStore("instance").getOrSet("instanceID", uniqueID); } function resolveHelloPromise(win, _ref) { var domain = _ref.domain; var helloPromises = windowStore("helloPromises"); var existingPromise = helloPromises.get(win); existingPromise && existingPromise.resolve({ domain: domain }); var newPromise = promise_ZalgoPromise.resolve({ domain: domain }); helloPromises.set(win, newPromise); return newPromise; } function sayHello(win, _ref4) { return (0, _ref4.send)(win, "postrobot_hello", { instanceID: getInstanceID() }, { domain: "*", timeout: -1 }).then((function(_ref5) { var origin = _ref5.origin, instanceID = _ref5.data.instanceID; resolveHelloPromise(win, { domain: origin }); return { win: win, domain: origin, instanceID: instanceID }; })); } function getWindowInstanceID(win, _ref6) { var send = _ref6.send; return windowStore("windowInstanceIDPromises").getOrSet(win, (function() { return sayHello(win, { send: send }).then((function(_ref7) { return _ref7.instanceID; })); })); } function awaitWindowHello(win, timeout, name) { void 0 === timeout && (timeout = 5e3); void 0 === name && (name = "Window"); var promise = function(win) { return windowStore("helloPromises").getOrSet(win, (function() { return new promise_ZalgoPromise; })); }(win); -1 !== timeout && (promise = promise.timeout(timeout, new Error(name + " did not load after " + timeout + "ms"))); return promise; } function markWindowKnown(win) { windowStore("knownWindows").set(win, !0); } function isSerializedType(item) { return "object" == typeof item && null !== item && "string" == typeof item.__type__; } function determineType(val) { return void 0 === val ? "undefined" : null === val ? "null" : Array.isArray(val) ? "array" : "function" == typeof val ? "function" : "object" == typeof val ? val instanceof Error ? "error" : "function" == typeof val.then ? "promise" : "[object RegExp]" === {}.toString.call(val) ? "regex" : "[object Date]" === {}.toString.call(val) ? "date" : "object" : "string" == typeof val ? "string" : "number" == typeof val ? "number" : "boolean" == typeof val ? "boolean" : void 0; } function serializeType(type, val) { return { __type__: type, __val__: val }; } var _SERIALIZER; var SERIALIZER = ((_SERIALIZER = {}).function = function() {}, _SERIALIZER.error = function(_ref) { return serializeType("error", { message: _ref.message, stack: _ref.stack, code: _ref.code, data: _ref.data }); }, _SERIALIZER.promise = function() {}, _SERIALIZER.regex = function(val) { return serializeType("regex", val.source); }, _SERIALIZER.date = function(val) { return serializeType("date", val.toJSON()); }, _SERIALIZER.array = function(val) { return val; }, _SERIALIZER.object = function(val) { return val; }, _SERIALIZER.string = function(val) { return val; }, _SERIALIZER.number = function(val) { return val; }, _SERIALIZER.boolean = function(val) { return val; }, _SERIALIZER.null = function(val) { return val; }, _SERIALIZER[void 0] = function(val) { return serializeType("undefined", val); }, _SERIALIZER); var defaultSerializers = {}; var _DESERIALIZER; var DESERIALIZER = ((_DESERIALIZER = {}).function = function() { throw new Error("Function serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.error = function(_ref2) { var stack = _ref2.stack, code = _ref2.code, data = _ref2.data; var error = new Error(_ref2.message); error.code = code; data && (error.data = data); error.stack = stack + "\n\n" + error.stack; return error; }, _DESERIALIZER.promise = function() { throw new Error("Promise serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.regex = function(val) { return new RegExp(val); }, _DESERIALIZER.date = function(val) { return new Date(val); }, _DESERIALIZER.array = function(val) { return val; }, _DESERIALIZER.object = function(val) { return val; }, _DESERIALIZER.string = function(val) { return val; }, _DESERIALIZER.number = function(val) { return val; }, _DESERIALIZER.boolean = function(val) { return val; }, _DESERIALIZER.null = function(val) { return val; }, _DESERIALIZER[void 0] = function() {}, _DESERIALIZER); var defaultDeserializers = {}; function needsBridgeForBrowser() { return !!utils_getUserAgent(window).match(/MSIE|trident|edge\/12|edge\/13/i); } function needsBridgeForWin(win) { return !isSameTopWindow(window, win); } function needsBridgeForDomain(domain, win) { if (domain) { if (getDomain() !== getDomainFromUrl(domain)) return !0; } else if (win && !isSameDomain(win)) return !0; return !1; } function needsBridge(_ref) { var win = _ref.win, domain = _ref.domain; return !(!needsBridgeForBrowser() || domain && !needsBridgeForDomain(domain, win) || win && !needsBridgeForWin(win)); } function getBridgeName(domain) { return "__postrobot_bridge___" + (domain = domain || getDomainFromUrl(domain)).replace(/[^a-zA-Z0-9]+/g, "_"); } function isBridge() { return Boolean(window.name && window.name === getBridgeName(getDomain())); } var documentBodyReady = new promise_ZalgoPromise((function(resolve) { if (window.document && window.document.body) return resolve(window.document.body); var interval = setInterval((function() { if (window.document && window.document.body) { clearInterval(interval); return resolve(window.document.body); } }), 10); })); function registerRemoteWindow(win) { windowStore("remoteWindowPromises").getOrSet(win, (function() { return new promise_ZalgoPromise; })); } function findRemoteWindow(win) { var remoteWinPromise = windowStore("remoteWindowPromises").get(win); if (!remoteWinPromise) throw new Error("Remote window promise not found"); return remoteWinPromise; } function registerRemoteSendMessage(win, domain, sendMessage) { findRemoteWindow(win).resolve((function(remoteWin, remoteDomain, message) { if (remoteWin !== win) throw new Error("Remote window does not match window"); if (!matchDomain(remoteDomain, domain)) throw new Error("Remote domain " + remoteDomain + " does not match domain " + domain); sendMessage.fireAndForget(message); })); } function rejectRemoteSendMessage(win, err) { findRemoteWindow(win).reject(err).catch(src_util_noop); } function linkWindow(_ref3) { var win = _ref3.win, name = _ref3.name, domain = _ref3.domain; var popupWindowsByName = globalStore("popupWindowsByName"); var popupWindowsByWin = windowStore("popupWindowsByWin"); for (var _i2 = 0, _popupWindowsByName$k2 = popupWindowsByName.keys(); _i2 < _popupWindowsByName$k2.length; _i2++) { var winName = _popupWindowsByName$k2[_i2]; var _details = popupWindowsByName.get(winName); _details && !isWindowClosed(_details.win) || popupWindowsByName.del(winName); } if (isWindowClosed(win)) return { win: win, name: name, domain: domain }; var details = popupWindowsByWin.getOrSet(win, (function() { return name ? popupWindowsByName.getOrSet(name, (function() { return { win: win, name: name }; })) : { win: win }; })); if (details.win && details.win !== win) throw new Error("Different window already linked for window: " + (name || "undefined")); if (name) { details.name = name; popupWindowsByName.set(name, details); } if (domain) { details.domain = domain; registerRemoteWindow(win); } popupWindowsByWin.set(win, details); return details; } function setupBridge(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; windowOpen = window.open, window.open = function(url, name, options, last) { var win = windowOpen.call(this, function(url) { if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); }(url), name, options, last); if (!win) return win; linkWindow({ win: win, name: name, domain: url ? getDomainFromUrl(url) : null }); return win; }; var windowOpen; !function(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; var popupWindowsByName = globalStore("popupWindowsByName"); on("postrobot_open_tunnel", (function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; var bridgePromise = globalStore("bridges").get(origin); if (!bridgePromise) throw new Error("Can not find bridge promise for domain " + origin); return bridgePromise.then((function(bridge) { if (source !== bridge) throw new Error("Message source does not matched registered bridge for domain " + origin); if (!data.name) throw new Error("Register window expected to be passed window name"); if (!data.sendMessage) throw new Error("Register window expected to be passed sendMessage method"); if (!popupWindowsByName.has(data.name)) throw new Error("Window with name " + data.name + " does not exist, or was not opened by this window"); var getWindowDetails = function() { return popupWindowsByName.get(data.name); }; if (!getWindowDetails().domain) throw new Error("We do not have a registered domain for window " + data.name); if (getWindowDetails().domain !== origin) throw new Error("Message origin " + origin + " does not matched registered window origin " + (getWindowDetails().domain || "unknown")); registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage); return { sendMessage: function(message) { if (window && !window.closed && getWindowDetails()) { var domain = getWindowDetails().domain; if (domain) try { receiveMessage({ data: message, origin: domain, source: getWindowDetails().win }, { on: on, send: send }); } catch (err) { promise_ZalgoPromise.reject(err); } } } }; })); })); }({ on: on, send: send, receiveMessage: receiveMessage }); !function(_ref2) { var send = _ref2.send; global_getGlobal(window).openTunnelToParent = function(_ref3) { var name = _ref3.name, source = _ref3.source, canary = _ref3.canary, sendMessage = _ref3.sendMessage; var tunnelWindows = globalStore("tunnelWindows"); var parentWindow = utils_getParent(window); if (!parentWindow) throw new Error("No parent window found to open tunnel to"); var id = function(_ref) { var name = _ref.name, source = _ref.source, canary = _ref.canary, sendMessage = _ref.sendMessage; !function() { var tunnelWindows = globalStore("tunnelWindows"); for (var _i2 = 0, _tunnelWindows$keys2 = tunnelWindows.keys(); _i2 < _tunnelWindows$keys2.length; _i2++) { var key = _tunnelWindows$keys2[_i2]; isWindowClosed(tunnelWindows[key].source) && tunnelWindows.del(key); } }(); var id = uniqueID(); globalStore("tunnelWindows").set(id, { name: name, source: source, canary: canary, sendMessage: sendMessage }); return id; }({ name: name, source: source, canary: canary, sendMessage: sendMessage }); return send(parentWindow, "postrobot_open_tunnel", { name: name, sendMessage: function() { var tunnelWindow = tunnelWindows.get(id); if (tunnelWindow && tunnelWindow.source && !isWindowClosed(tunnelWindow.source)) { try { tunnelWindow.canary(); } catch (err) { return; } tunnelWindow.sendMessage.apply(this, arguments); } } }, { domain: "*" }); }; }({ send: send }); !function(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; promise_ZalgoPromise.try((function() { var opener = getOpener(window); if (opener && needsBridge({ win: opener })) { registerRemoteWindow(opener); return (win = opener, windowStore("remoteBridgeAwaiters").getOrSet(win, (function() { return promise_ZalgoPromise.try((function() { var frame = getFrameByName(win, getBridgeName(getDomain())); if (frame) return isSameDomain(frame) && global_getGlobal(assertSameDomain(frame)) ? frame : new promise_ZalgoPromise((function(resolve) { var interval; var timeout; interval = setInterval((function() { if (frame && isSameDomain(frame) && global_getGlobal(assertSameDomain(frame))) { clearInterval(interval); clearTimeout(timeout); return resolve(frame); } }), 100); timeout = setTimeout((function() { clearInterval(interval); return resolve(); }), 2e3); })); })); }))).then((function(bridge) { return bridge ? window.name ? global_getGlobal(assertSameDomain(bridge)).openTunnelToParent({ name: window.name, source: window, canary: function() {}, sendMessage: function(message) { try { window; } catch (err) { return; } if (window && !window.closed) try { receiveMessage({ data: message, origin: this.origin, source: this.source }, { on: on, send: send }); } catch (err) { promise_ZalgoPromise.reject(err); } } }).then((function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; if (source !== opener) throw new Error("Source does not match opener"); registerRemoteSendMessage(source, origin, data.sendMessage); })).catch((function(err) { rejectRemoteSendMessage(opener, err); throw err; })) : rejectRemoteSendMessage(opener, new Error("Can not register with opener: window does not have a name")) : rejectRemoteSendMessage(opener, new Error("Can not register with opener: no bridge found in opener")); })); var win; } })); }({ on: on, send: send, receiveMessage: receiveMessage }); } function cleanupProxyWindows() { var idToProxyWindow = globalStore("idToProxyWindow"); for (var _i2 = 0, _idToProxyWindow$keys2 = idToProxyWindow.keys(); _i2 < _idToProxyWindow$keys2.length; _i2++) { var id = _idToProxyWindow$keys2[_i2]; idToProxyWindow.get(id).shouldClean() && idToProxyWindow.del(id); } } function getSerializedWindow(winPromise, _ref) { var send = _ref.send, _ref$id = _ref.id, id = void 0 === _ref$id ? uniqueID() : _ref$id; var windowNamePromise = winPromise.then((function(win) { if (isSameDomain(win)) return assertSameDomain(win).name; })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); return getOpener(window) ? "popup" : "iframe"; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); var getName = function() { return winPromise.then((function(win) { if (!isWindowClosed(win)) return isSameDomain(win) ? assertSameDomain(win).name : windowNamePromise; })); }; return { id: id, getType: function() { return windowTypePromise; }, getInstanceID: memoizePromise((function() { return winPromise.then((function(win) { return getWindowInstanceID(win, { send: send }); })); })), close: function() { return winPromise.then(closeWindow); }, getName: getName, focus: function() { return winPromise.then((function(win) { win.focus(); })); }, isClosed: function() { return winPromise.then((function(win) { return isWindowClosed(win); })); }, setLocation: function(href, opts) { void 0 === opts && (opts = {}); return winPromise.then((function(win) { var domain = window.location.protocol + "//" + window.location.host; var _opts$method = opts.method, method = void 0 === _opts$method ? "get" : _opts$method, body = opts.body; if (0 === href.indexOf("/")) href = "" + domain + href; else if (!href.match(/^https?:\/\//) && 0 !== href.indexOf(domain)) throw new Error("Expected url to be http or https url, or absolute path, got " + JSON.stringify(href)); if ("post" === method) return getName().then((function(name) { if (!name) throw new Error("Can not post to window without target name"); !function(_ref3) { var url = _ref3.url, target = _ref3.target, body = _ref3.body, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "post" : _ref3$method; var form = document.createElement("form"); form.setAttribute("target", target); form.setAttribute("method", method); form.setAttribute("action", url); form.style.display = "none"; if (body) for (var _i24 = 0, _Object$keys4 = Object.keys(body); _i24 < _Object$keys4.length; _i24++) { var _body$key; var key = _Object$keys4[_i24]; var input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", null == (_body$key = body[key]) ? void 0 : _body$key.toString()); form.appendChild(input); } getBody().appendChild(form); form.submit(); getBody().removeChild(form); }({ url: href, target: name, method: method, body: body }); })); if ("get" !== method) throw new Error("Unsupported method: " + method); if (isSameDomain(win)) try { if (win.location && "function" == typeof win.location.replace) { win.location.replace(href); return; } } catch (err) {} win.location = href; })); }, setName: function(name) { return winPromise.then((function(win) { linkWindow({ win: win, name: name }); var sameDomain = isSameDomain(win); var frame = getFrameForWindow(win); if (!sameDomain) throw new Error("Can not set name for cross-domain window: " + name); assertSameDomain(win).name = name; frame && frame.setAttribute("name", name); windowNamePromise = promise_ZalgoPromise.resolve(name); })); } }; } var window_ProxyWindow = function() { function ProxyWindow(_ref2) { var send = _ref2.send, win = _ref2.win, serializedWindow = _ref2.serializedWindow; this.id = void 0; this.isProxyWindow = !0; this.serializedWindow = void 0; this.actualWindow = void 0; this.actualWindowPromise = void 0; this.send = void 0; this.name = void 0; this.actualWindowPromise = new promise_ZalgoPromise; this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send: send }); globalStore("idToProxyWindow").set(this.getID(), this); win && this.setWindow(win, { send: send }); } var _proto = ProxyWindow.prototype; _proto.getID = function() { return this.serializedWindow.id; }; _proto.getType = function() { return this.serializedWindow.getType(); }; _proto.isPopup = function() { return this.getType().then((function(type) { return "popup" === type; })); }; _proto.setLocation = function(href, opts) { var _this = this; return this.serializedWindow.setLocation(href, opts).then((function() { return _this; })); }; _proto.getName = function() { return this.serializedWindow.getName(); }; _proto.setName = function(name) { var _this2 = this; return this.serializedWindow.setName(name).then((function() { return _this2; })); }; _proto.close = function() { var _this3 = this; return this.serializedWindow.close().then((function() { return _this3; })); }; _proto.focus = function() { var _this4 = this; var isPopupPromise = this.isPopup(); var getNamePromise = this.getName(); var reopenPromise = promise_ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then((function(_ref3) { var name = _ref3.name; _ref3.isPopup && name && window.open("", name, "noopener"); })); var focusPromise = this.serializedWindow.focus(); return promise_ZalgoPromise.all([ reopenPromise, focusPromise ]).then((function() { return _this4; })); }; _proto.isClosed = function() { return this.serializedWindow.isClosed(); }; _proto.getWindow = function() { return this.actualWindow; }; _proto.setWindow = function(win, _ref4) { var send = _ref4.send; this.actualWindow = win; this.actualWindowPromise.resolve(this.actualWindow); this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send: send, id: this.getID() }); windowStore("winToProxyWindow").set(win, this); }; _proto.awaitWindow = function() { return this.actualWindowPromise; }; _proto.matchWindow = function(win, _ref5) { var _this5 = this; var send = _ref5.send; return promise_ZalgoPromise.try((function() { return _this5.actualWindow ? win === _this5.actualWindow : promise_ZalgoPromise.hash({ proxyInstanceID: _this5.getInstanceID(), knownWindowInstanceID: getWindowInstanceID(win, { send: send }) }).then((function(_ref6) { var match = _ref6.proxyInstanceID === _ref6.knownWindowInstanceID; match && _this5.setWindow(win, { send: send }); return match; })); })); }; _proto.unwrap = function() { return this.actualWindow || this; }; _proto.getInstanceID = function() { return this.serializedWindow.getInstanceID(); }; _proto.shouldClean = function() { return Boolean(this.actualWindow && isWindowClosed(this.actualWindow)); }; _proto.serialize = function() { return this.serializedWindow; }; ProxyWindow.unwrap = function(win) { return ProxyWindow.isProxyWindow(win) ? win.unwrap() : win; }; ProxyWindow.serialize = function(win, _ref7) { var send = _ref7.send; cleanupProxyWindows(); return ProxyWindow.toProxyWindow(win, { send: send }).serialize(); }; ProxyWindow.deserialize = function(serializedWindow, _ref8) { var send = _ref8.send; cleanupProxyWindows(); return globalStore("idToProxyWindow").get(serializedWindow.id) || new ProxyWindow({ serializedWindow: serializedWindow, send: send }); }; ProxyWindow.isProxyWindow = function(obj) { return Boolean(obj && !isWindow(obj) && obj.isProxyWindow); }; ProxyWindow.toProxyWindow = function(win, _ref9) { var send = _ref9.send; cleanupProxyWindows(); if (ProxyWindow.isProxyWindow(win)) return win; var actualWindow = win; return windowStore("winToProxyWindow").get(actualWindow) || new ProxyWindow({ win: actualWindow, send: send }); }; return ProxyWindow; }(); function addMethod(id, val, name, source, domain) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); if (window_ProxyWindow.isProxyWindow(source)) proxyWindowMethods.set(id, { val: val, name: name, domain: domain, source: source }); else { proxyWindowMethods.del(id); methodStore.getOrSet(source, (function() { return {}; }))[id] = { domain: domain, name: name, val: val, source: source }; } } function lookupMethod(source, id) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); return methodStore.getOrSet(source, (function() { return {}; }))[id] || proxyWindowMethods.get(id); } function function_serializeFunction(destination, domain, val, key, _ref3) { on = (_ref = { on: _ref3.on, send: _ref3.send }).on, send = _ref.send, globalStore("builtinListeners").getOrSet("functionCalls", (function() { return on("postrobot_method", { domain: "*" }, (function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; var id = data.id, name = data.name; var meth = lookupMethod(source, id); if (!meth) throw new Error("Could not find method '" + name + "' with id: " + data.id + " in " + getDomain(window)); var methodSource = meth.source, domain = meth.domain, val = meth.val; return promise_ZalgoPromise.try((function() { if (!matchDomain(domain, origin)) throw new Error("Method '" + data.name + "' domain " + JSON.stringify(util_isRegex(meth.domain) ? meth.domain.source : meth.domain) + " does not match origin " + origin + " in " + getDomain(window)); if (window_ProxyWindow.isProxyWindow(methodSource)) return methodSource.matchWindow(source, { send: send }).then((function(match) { if (!match) throw new Error("Method call '" + data.name + "' failed - proxy window does not match source in " + getDomain(window)); })); })).then((function() { return val.apply({ source: source, origin: origin }, data.args); }), (function(err) { return promise_ZalgoPromise.try((function() { if (val.onError) return val.onError(err); })).then((function() { err.stack && (err.stack = "Remote call to " + name + "(" + function(args) { void 0 === args && (args = []); return arrayFrom(args).map((function(arg) { return "string" == typeof arg ? "'" + arg + "'" : void 0 === arg ? "undefined" : null === arg ? "null" : "boolean" == typeof arg ? arg.toString() : Array.isArray(arg) ? "[ ... ]" : "object" == typeof arg ? "{ ... }" : "function" == typeof arg ? "() => { ... }" : "<" + typeof arg + ">"; })).join(", "); }(data.args) + ") failed\n\n" + err.stack); throw err; })); })).then((function(result) { return { result: result, id: id, name: name }; })); })); })); var _ref, on, send; var id = val.__id__ || uniqueID(); destination = window_ProxyWindow.unwrap(destination); var name = val.__name__ || val.name || key; "string" == typeof name && "function" == typeof name.indexOf && 0 === name.indexOf("anonymous::") && (name = name.replace("anonymous::", key + "::")); if (window_ProxyWindow.isProxyWindow(destination)) { addMethod(id, val, name, destination, domain); destination.awaitWindow().then((function(win) { addMethod(id, val, name, win, domain); })); } else addMethod(id, val, name, destination, domain); return serializeType("cross_domain_function", { id: id, name: name }); } function serializeMessage(destination, domain, obj, _ref) { var _serialize; var on = _ref.on, send = _ref.send; return function(obj, serializers) { void 0 === serializers && (serializers = defaultSerializers); var result = JSON.stringify(obj, (function(key) { var val = this[key]; if (isSerializedType(this)) return val; var type = determineType(val); if (!type) return val; var serializer = serializers[type] || SERIALIZER[type]; return serializer ? serializer(val, key) : val; })); return void 0 === result ? "undefined" : result; }(obj, ((_serialize = {}).promise = function(val, key) { return function(destination, domain, val, key, _ref) { return serializeType("cross_domain_zalgo_promise", { then: function_serializeFunction(destination, domain, (function(resolve, reject) { return val.then(resolve, reject); }), key, { on: _ref.on, send: _ref.send }) }); }(destination, domain, val, key, { on: on, send: send }); }, _serialize.function = function(val, key) { return function_serializeFunction(destination, domain, val, key, { on: on, send: send }); }, _serialize.object = function(val) { return isWindow(val) || window_ProxyWindow.isProxyWindow(val) ? serializeType("cross_domain_window", window_ProxyWindow.serialize(val, { send: send })) : val; }, _serialize)); } function deserializeMessage(source, origin, message, _ref2) { var _deserialize; var send = _ref2.send; return function(str, deserializers) { void 0 === deserializers && (deserializers = defaultDeserializers); if ("undefined" !== str) return JSON.parse(str, (function(key, val) { if (isSerializedType(this)) return val; var type; var value; if (isSerializedType(val)) { type = val.__type__; value = val.__val__; } else { type = determineType(val); value = val; } if (!type) return value; var deserializer = deserializers[type] || DESERIALIZER[type]; return deserializer ? deserializer(value, key) : value; })); }(message, ((_deserialize = {}).cross_domain_zalgo_promise = function(serializedPromise) { return function(source, origin, _ref2) { return new promise_ZalgoPromise(_ref2.then); }(0, 0, serializedPromise); }, _deserialize.cross_domain_function = function(serializedFunction) { return function(source, origin, _ref4, _ref5) { var id = _ref4.id, name = _ref4.name; var send = _ref5.send; var getDeserializedFunction = function(opts) { void 0 === opts && (opts = {}); function crossDomainFunctionWrapper() { var _arguments = arguments; return window_ProxyWindow.toProxyWindow(source, { send: send }).awaitWindow().then((function(win) { var meth = lookupMethod(win, id); if (meth && meth.val !== crossDomainFunctionWrapper) return meth.val.apply({ source: window, origin: getDomain() }, _arguments); var _args = [].slice.call(_arguments); return opts.fireAndForget ? send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !0 }) : send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !1 }).then((function(res) { return res.data.result; })); })).catch((function(err) { throw err; })); } crossDomainFunctionWrapper.__name__ = name; crossDomainFunctionWrapper.__origin__ = origin; crossDomainFunctionWrapper.__source__ = source; crossDomainFunctionWrapper.__id__ = id; crossDomainFunctionWrapper.origin = origin; return crossDomainFunctionWrapper; }; var crossDomainFunctionWrapper = getDeserializedFunction(); crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: !0 }); return crossDomainFunctionWrapper; }(source, origin, serializedFunction, { send: send }); }, _deserialize.cross_domain_window = function(serializedWindow) { return window_ProxyWindow.deserialize(serializedWindow, { send: send }); }, _deserialize)); } var SEND_MESSAGE_STRATEGIES = {}; SEND_MESSAGE_STRATEGIES.postrobot_post_message = function(win, serializedMessage, domain) { 0 === domain.indexOf("file:") && (domain = "*"); win.postMessage(serializedMessage, domain); }; SEND_MESSAGE_STRATEGIES.postrobot_bridge = function(win, serializedMessage, domain) { if (!needsBridgeForBrowser() && !isBridge()) throw new Error("Bridge not needed for browser"); if (isSameDomain(win)) throw new Error("Post message through bridge disabled between same domain windows"); if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use bridge to communicate between two different windows, not between frames"); !function(win, domain, message) { var messagingChild = isOpener(window, win); var messagingParent = isOpener(win, window); if (!messagingChild && !messagingParent) throw new Error("Can only send messages to and from parent and popup windows"); findRemoteWindow(win).then((function(sendMessage) { return sendMessage(win, domain, message); })); }(win, domain, serializedMessage); }; SEND_MESSAGE_STRATEGIES.postrobot_global = function(win, serializedMessage) { if (!utils_getUserAgent(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser"); if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows"); if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); var foreignGlobal = global_getGlobal(win); if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window"); foreignGlobal.receiveMessage({ source: window, origin: getDomain(), data: serializedMessage }); }; function send_sendMessage(win, domain, message, _ref2) { var on = _ref2.on, send = _ref2.send; return promise_ZalgoPromise.try((function() { var domainBuffer = windowStore().getOrSet(win, (function() { return {}; })); domainBuffer.buffer = domainBuffer.buffer || []; domainBuffer.buffer.push(message); domainBuffer.flush = domainBuffer.flush || promise_ZalgoPromise.flush().then((function() { if (isWindowClosed(win)) throw new Error("Window is closed"); var serializedMessage = serializeMessage(win, domain, ((_ref = {}).__post_robot_10_0_46__ = domainBuffer.buffer || [], _ref), { on: on, send: send }); var _ref; delete domainBuffer.buffer; var strategies = Object.keys(SEND_MESSAGE_STRATEGIES); var errors = []; for (var _i2 = 0; _i2 < strategies.length; _i2++) { var strategyName = strategies[_i2]; try { SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain); } catch (err) { errors.push(err); } } if (errors.length === strategies.length) throw new Error("All post-robot messaging strategies failed:\n\n" + errors.map((function(err, i) { return i + ". " + stringifyError(err); })).join("\n\n")); })); return domainBuffer.flush.then((function() { delete domainBuffer.flush; })); })).then(src_util_noop); } function getResponseListener(hash) { return globalStore("responseListeners").get(hash); } function deleteResponseListener(hash) { globalStore("responseListeners").del(hash); } function isResponseListenerErrored(hash) { return globalStore("erroredResponseListeners").has(hash); } function getRequestListener(_ref) { var name = _ref.name, win = _ref.win, domain = _ref.domain; var requestListeners = windowStore("requestListeners"); "*" === win && (win = null); "*" === domain && (domain = null); if (!name) throw new Error("Name required to get request listener"); for (var _i4 = 0, _ref3 = [ win, getWildcard() ]; _i4 < _ref3.length; _i4++) { var winQualifier = _ref3[_i4]; if (winQualifier) { var nameListeners = requestListeners.get(winQualifier); if (nameListeners) { var domainListeners = nameListeners[name]; if (domainListeners) { if (domain && "string" == typeof domain) { if (domainListeners[domain]) return domainListeners[domain]; if (domainListeners.__domain_regex__) for (var _i6 = 0, _domainListeners$__DO2 = domainListeners.__domain_regex__; _i6 < _domainListeners$__DO2.length; _i6++) { var _domainListeners$__DO3 = _domainListeners$__DO2[_i6], listener = _domainListeners$__DO3.listener; if (matchDomain(_domainListeners$__DO3.regex, domain)) return listener; } } if (domainListeners["*"]) return domainListeners["*"]; } } } } } function handleRequest(source, origin, message, _ref) { var on = _ref.on, send = _ref.send; var options = getRequestListener({ name: message.name, win: source, domain: origin }); var logName = "postrobot_method" === message.name && message.data && "string" == typeof message.data.name ? message.data.name + "()" : message.name; function sendResponse(ack, data, error) { return promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_response", hash: message.hash, name: message.name, ack: ack, data: data, error: error }, { on: on, send: send }); } catch (err) { throw new Error("Send response message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })); } return promise_ZalgoPromise.all([ promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_ack", hash: message.hash, name: message.name }, { on: on, send: send }); } catch (err) { throw new Error("Send ack message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })), promise_ZalgoPromise.try((function() { if (!options) throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); return options.handler({ source: source, origin: origin, data: message.data }); })).then((function(data) { return sendResponse("success", data); }), (function(error) { return sendResponse("error", null, error); })) ]).then(src_util_noop).catch((function(err) { if (options && options.handleError) return options.handleError(err); throw err; })); } function handleAck(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); try { if (!matchDomain(options.domain, origin)) throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString()); if (source !== options.win) throw new Error("Ack source does not match registered window"); } catch (err) { options.promise.reject(err); } options.ack = !0; } } function handleResponse(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); if (!matchDomain(options.domain, origin)) throw new Error("Response origin " + origin + " does not match domain " + (pattern = options.domain, Array.isArray(pattern) ? "(" + pattern.join(" | ") + ")" : isRegex(pattern) ? "RegExp(" + pattern.toString() + ")" : pattern.toString())); var pattern; if (source !== options.win) throw new Error("Response source does not match registered window"); deleteResponseListener(message.hash); "error" === message.ack ? options.promise.reject(message.error) : "success" === message.ack && options.promise.resolve({ source: source, origin: origin, data: message.data }); } } function receive_receiveMessage(event, _ref2) { var on = _ref2.on, send = _ref2.send; var receivedMessages = globalStore("receivedMessages"); try { if (!window || window.closed || !event.source) return; } catch (err) { return; } var source = event.source, origin = event.origin; var messages = function(message, source, origin, _ref) { var on = _ref.on, send = _ref.send; var parsedMessage; try { parsedMessage = deserializeMessage(source, origin, message, { on: on, send: send }); } catch (err) { return; } if (parsedMessage && "object" == typeof parsedMessage && null !== parsedMessage) { var parseMessages = parsedMessage.__post_robot_10_0_46__; if (Array.isArray(parseMessages)) return parseMessages; } }(event.data, source, origin, { on: on, send: send }); if (messages) { markWindowKnown(source); for (var _i2 = 0; _i2 < messages.length; _i2++) { var message = messages[_i2]; if (receivedMessages.has(message.id)) return; receivedMessages.set(message.id, !0); if (isWindowClosed(source) && !message.fireAndForget) return; 0 === message.origin.indexOf("file:") && (origin = "file://"); try { "postrobot_message_request" === message.type ? handleRequest(source, origin, message, { on: on, send: send }) : "postrobot_message_response" === message.type ? handleResponse(source, origin, message) : "postrobot_message_ack" === message.type && handleAck(source, origin, message); } catch (err) { setTimeout((function() { throw err; }), 0); } } } } function on_on(name, options, handler) { if (!name) throw new Error("Expected name"); if ("function" == typeof (options = options || {})) { handler = options; options = {}; } if (!handler) throw new Error("Expected handler"); var requestListener = function addRequestListener(_ref4, listener) { var name = _ref4.name, winCandidate = _ref4.win, domain = _ref4.domain; var requestListeners = windowStore("requestListeners"); if (!name || "string" != typeof name) throw new Error("Name required to add request listener"); if (winCandidate && "*" !== winCandidate && window_ProxyWindow.isProxyWindow(winCandidate)) { var requestListenerPromise = winCandidate.awaitWindow().then((function(actualWin) { return addRequestListener({ name: name, win: actualWin, domain: domain }, listener); })); return { cancel: function() { requestListenerPromise.then((function(requestListener) { return requestListener.cancel(); }), src_util_noop); } }; } var win = winCandidate; if (Array.isArray(win)) { var listenersCollection = []; for (var _i8 = 0, _win2 = win; _i8 < _win2.length; _i8++) listenersCollection.push(addRequestListener({ name: name, domain: domain, win: _win2[_i8] }, listener)); return { cancel: function() { for (var _i10 = 0; _i10 < listenersCollection.length; _i10++) listenersCollection[_i10].cancel(); } }; } if (Array.isArray(domain)) { var _listenersCollection = []; for (var _i12 = 0, _domain2 = domain; _i12 < _domain2.length; _i12++) _listenersCollection.push(addRequestListener({ name: name, win: win, domain: _domain2[_i12] }, listener)); return { cancel: function() { for (var _i14 = 0; _i14 < _listenersCollection.length; _i14++) _listenersCollection[_i14].cancel(); } }; } var existingListener = getRequestListener({ name: name, win: win, domain: domain }); win && "*" !== win || (win = getWildcard()); var strDomain = (domain = domain || "*").toString(); if (existingListener) throw win && domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : win ? new Error("Request listener already exists for " + name + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString()) : new Error("Request listener already exists for " + name); var winNameListeners = requestListeners.getOrSet(win, (function() { return {}; })); var winNameDomainListeners = util_getOrSet(winNameListeners, name, (function() { return {}; })); var winNameDomainRegexListeners; var winNameDomainRegexListener; util_isRegex(domain) ? (winNameDomainRegexListeners = util_getOrSet(winNameDomainListeners, "__domain_regex__", (function() { return []; }))).push(winNameDomainRegexListener = { regex: domain, listener: listener }) : winNameDomainListeners[strDomain] = listener; return { cancel: function() { delete winNameDomainListeners[strDomain]; if (winNameDomainRegexListener) { winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1)); winNameDomainRegexListeners.length || delete winNameDomainListeners.__domain_regex__; } Object.keys(winNameDomainListeners).length || delete winNameListeners[name]; win && !Object.keys(winNameListeners).length && requestListeners.del(win); } }; }({ name: name, win: options.window, domain: options.domain || "*" }, { handler: handler || options.handler, handleError: options.errorHandler || function(err) { throw err; } }); return { cancel: function() { requestListener.cancel(); } }; } var send_send = function send(winOrProxyWin, name, data, options) { var domainMatcher = (options = options || {}).domain || "*"; var responseTimeout = options.timeout || -1; var childTimeout = options.timeout || 5e3; var fireAndForget = options.fireAndForget || !1; return window_ProxyWindow.toProxyWindow(winOrProxyWin, { send: send }).awaitWindow().then((function(win) { return promise_ZalgoPromise.try((function() { !function(name, win, domain) { if (!name) throw new Error("Expected name"); if (domain && "string" != typeof domain && !Array.isArray(domain) && !util_isRegex(domain)) throw new TypeError("Can not send " + name + ". Expected domain " + JSON.stringify(domain) + " to be a string, array, or regex"); if (isWindowClosed(win)) throw new Error("Can not send " + name + ". Target window is closed"); }(name, win, domainMatcher); if (function(parent, child) { var actualParent = getAncestor(child); if (actualParent) return actualParent === parent; if (child === parent) return !1; if (getTop(child) === child) return !1; for (var _i15 = 0, _getFrames8 = getFrames(parent); _i15 < _getFrames8.length; _i15++) if (_getFrames8[_i15] === child) return !0; return !1; }(window, win)) return awaitWindowHello(win, childTimeout); })).then((function(_temp) { return function(win, targetDomain, actualDomain, _ref) { var send = _ref.send; return promise_ZalgoPromise.try((function() { return "string" == typeof targetDomain ? targetDomain : promise_ZalgoPromise.try((function() { return actualDomain || sayHello(win, { send: send }).then((function(_ref2) { return _ref2.domain; })); })).then((function(normalizedDomain) { if (!matchDomain(targetDomain, targetDomain)) throw new Error("Domain " + stringify(targetDomain) + " does not match " + stringify(targetDomain)); return normalizedDomain; })); })); }(win, domainMatcher, (void 0 === _temp ? {} : _temp).domain, { send: send }); })).then((function(targetDomain) { var domain = targetDomain; var logName = "postrobot_method" === name && data && "string" == typeof data.name ? data.name + "()" : name; var promise = new promise_ZalgoPromise; var hash = name + "_" + uniqueID(); if (!fireAndForget) { var responseListener = { name: name, win: win, domain: domain, promise: promise }; !function(hash, listener) { globalStore("responseListeners").set(hash, listener); }(hash, responseListener); var reqPromises = windowStore("requestPromises").getOrSet(win, (function() { return []; })); reqPromises.push(promise); promise.catch((function() { !function(hash) { globalStore("erroredResponseListeners").set(hash, !0); }(hash); deleteResponseListener(hash); })); var totalAckTimeout = function(win) { return windowStore("knownWindows").get(win, !1); }(win) ? 1e4 : 2e3; var totalResTimeout = responseTimeout; var ackTimeout = totalAckTimeout; var resTimeout = totalResTimeout; var interval = safeInterval((function() { if (isWindowClosed(win)) return promise.reject(new Error("Window closed for " + name + " before " + (responseListener.ack ? "response" : "ack"))); if (responseListener.cancelled) return promise.reject(new Error("Response listener was cancelled for " + name)); ackTimeout = Math.max(ackTimeout - 500, 0); -1 !== resTimeout && (resTimeout = Math.max(resTimeout - 500, 0)); return responseListener.ack || 0 !== ackTimeout ? 0 === resTimeout ? promise.reject(new Error("No response for postMessage " + logName + " in " + getDomain() + " in " + totalResTimeout + "ms")) : void 0 : promise.reject(new Error("No ack for postMessage " + logName + " in " + getDomain() + " in " + totalAckTimeout + "ms")); }), 500); promise.finally((function() { interval.cancel(); reqPromises.splice(reqPromises.indexOf(promise, 1)); })).catch(src_util_noop); } return send_sendMessage(win, domain, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_request", hash: hash, name: name, data: data, fireAndForget: fireAndForget }, { on: on_on, send: send }).then((function() { return fireAndForget ? promise.resolve() : promise; }), (function(err) { throw new Error("Send request message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); })); })); })); }; function setup_toProxyWindow(win) { return window_ProxyWindow.toProxyWindow(win, { send: send_send }); } function cleanUpWindow(win) { for (var _i2 = 0, _requestPromises$get2 = windowStore("requestPromises").get(win, []); _i2 < _requestPromises$get2.length; _i2++) _requestPromises$get2[_i2].reject(new Error("Window " + (isWindowClosed(win) ? "closed" : "cleaned up") + " before response")).catch(src_util_noop); } var src_bridge; src_bridge = { setupBridge: setupBridge, openBridge: function(url, domain) { var bridges = globalStore("bridges"); var bridgeFrames = globalStore("bridgeFrames"); domain = domain || getDomainFromUrl(url); return bridges.getOrSet(domain, (function() { return promise_ZalgoPromise.try((function() { if (getDomain() === domain) throw new Error("Can not open bridge on the same domain as current domain: " + domain); var name = getBridgeName(domain); if (getFrameByName(window, name)) throw new Error("Frame with name " + name + " already exists on page"); var iframe = function(name, url) { var iframe = document.createElement("iframe"); iframe.setAttribute("name", name); iframe.setAttribute("id", name); iframe.setAttribute("style", "display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;"); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("border", "0"); iframe.setAttribute("scrolling", "no"); iframe.setAttribute("allowTransparency", "true"); iframe.setAttribute("tabindex", "-1"); iframe.setAttribute("hidden", "true"); iframe.setAttribute("title", ""); iframe.setAttribute("role", "presentation"); iframe.src = url; return iframe; }(name, url); bridgeFrames.set(domain, iframe); return documentBodyReady.then((function(body) { body.appendChild(iframe); var bridge = iframe.contentWindow; return new promise_ZalgoPromise((function(resolve, reject) { iframe.addEventListener("load", resolve); iframe.addEventListener("error", reject); })).then((function() { return awaitWindowHello(bridge, 5e3, "Bridge " + url); })).then((function() { return bridge; })); })); })); })); }, linkWindow: linkWindow, linkUrl: function(win, url) { linkWindow({ win: win, domain: getDomainFromUrl(url) }); }, isBridge: isBridge, needsBridge: needsBridge, needsBridgeForBrowser: needsBridgeForBrowser, hasBridge: function(url, domain) { return globalStore("bridges").has(domain || getDomainFromUrl(url)); }, needsBridgeForWin: needsBridgeForWin, needsBridgeForDomain: needsBridgeForDomain, destroyBridges: function() { var bridges = globalStore("bridges"); var bridgeFrames = globalStore("bridgeFrames"); for (var _i4 = 0, _bridgeFrames$keys2 = bridgeFrames.keys(); _i4 < _bridgeFrames$keys2.length; _i4++) { var frame = bridgeFrames.get(_bridgeFrames$keys2[_i4]); frame && frame.parentNode && frame.parentNode.removeChild(frame); } bridgeFrames.reset(); bridges.reset(); } }; function src_util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function utils_getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function utils_getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return utils_getActualProtocol(win); } function utils_isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === utils_getProtocol(win); } function src_utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function utils_getOpener(win) { void 0 === win && (win = window); if (win && !src_utils_getParent(win)) try { return win.opener; } catch (err) {} } function utils_canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function utils_getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = utils_getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = src_utils_getParent(win); return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function utils_getDomain(win) { void 0 === win && (win = window); var domain = utils_getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function utils_isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === utils_getProtocol(win); }(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; if (utils_getDomain(window) === utils_getDomain(win)) return !0; } catch (err) {} return !1; } function utils_assertSameDomain(win) { if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function utils_isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = src_utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function utils_getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function utils_getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function utils_getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (src_utils_getParent(win) === win) return win; try { if (utils_isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (utils_isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (src_utils_getParent(frame) === frame) return frame; } } function utils_getAllFramesInWindow(win) { var top = utils_getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(utils_getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); return result; } var utils_iframeWindows = []; var utils_iframeFrames = []; function utils_isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || "Call was rejected by callee.\r\n" !== err.message; } if (allowMock && utils_isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(utils_iframeWindows, win); if (-1 !== iframeIndex) { var frame = utils_iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function utils_getFrameByName(win, name) { var winFrames = utils_getFrames(win); for (var _i9 = 0; _i9 < winFrames.length; _i9++) { var childFrame = winFrames[_i9]; try { if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; } catch (err) {} } try { if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; } catch (err) {} try { if (-1 !== winFrames.indexOf(win[name])) return win[name]; } catch (err) {} } function utils_getAncestor(win) { void 0 === win && (win = window); return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; } function utils_anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function utils_getDistanceFromTop(win) { void 0 === win && (win = window); var distance = 0; var parent = win; for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); return distance; } function utils_matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (src_util_isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return src_util_isRegex(pattern) ? src_util_isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { return utils_matchDomain(subpattern, origin); }))); } function utils_getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); } function utils_onCloseWindow(win, callback, delay, maxtime) { void 0 === delay && (delay = 1e3); void 0 === maxtime && (maxtime = 1 / 0); var timeout; !function check() { if (utils_isWindowClosed(win)) { timeout && clearTimeout(timeout); return callback(); } if (maxtime <= 0) clearTimeout(timeout); else { maxtime -= delay; timeout = setTimeout(check, delay); } }(); return { cancel: function() { timeout && clearTimeout(timeout); } }; } function utils_isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function utils_normalizeMockUrl(url) { if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); } function lib_global_getGlobal(win) { if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); return win.__zoid_9_0_87__; } function tryGlobal(win, handler) { try { return handler(lib_global_getGlobal(win)); } catch (err) {} } function getProxyObject(obj) { return { get: function() { var _this = this; return promise_ZalgoPromise.try((function() { if (_this.source && _this.source !== window) throw new Error("Can not call get on proxy object from a remote window"); return obj; })); } }; } function basicSerialize(data) { return base64encode(JSON.stringify(data)); } function getUIDRefStore(win) { var global = lib_global_getGlobal(win); global.references = global.references || {}; return global.references; } function crossDomainSerialize(_ref) { var data = _ref.data, metaData = _ref.metaData, sender = _ref.sender, receiver = _ref.receiver, _ref$passByReference = _ref.passByReference, passByReference = void 0 !== _ref$passByReference && _ref$passByReference, _ref$basic = _ref.basic, basic = void 0 !== _ref$basic && _ref$basic; var proxyWin = setup_toProxyWindow(receiver.win); var serializedMessage = basic ? JSON.stringify(data) : serializeMessage(proxyWin, receiver.domain, data, { on: on_on, send: send_send }); var reference = passByReference ? function(val) { var uid = uniqueID(); getUIDRefStore(window)[uid] = val; return { type: "uid", uid: uid }; }(serializedMessage) : { type: "raw", val: serializedMessage }; return { serializedData: basicSerialize({ sender: { domain: sender.domain }, metaData: metaData, reference: reference }), cleanReference: function() { win = window, "uid" === (ref = reference).type && delete getUIDRefStore(win)[ref.uid]; var win, ref; } }; } function crossDomainDeserialize(_ref2) { var sender = _ref2.sender, _ref2$basic = _ref2.basic, basic = void 0 !== _ref2$basic && _ref2$basic; var message = function(serializedData) { return JSON.parse(function(str) { if ("function" == typeof atob) return decodeURIComponent([].map.call(atob(str), (function(c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); })).join("")); if ("undefined" != typeof Buffer) return Buffer.from(str, "base64").toString("utf8"); throw new Error("Can not find window.atob or Buffer"); }(serializedData)); }(_ref2.data); var reference = message.reference, metaData = message.metaData; var win; win = "function" == typeof sender.win ? sender.win({ metaData: metaData }) : sender.win; var domain; domain = "function" == typeof sender.domain ? sender.domain({ metaData: metaData }) : "string" == typeof sender.domain ? sender.domain : message.sender.domain; var serializedData = function(win, ref) { if ("raw" === ref.type) return ref.val; if ("uid" === ref.type) return getUIDRefStore(win)[ref.uid]; throw new Error("Unsupported ref type: " + ref.type); }(win, reference); return { data: basic ? JSON.parse(serializedData) : function(source, origin, message) { return deserializeMessage(source, origin, message, { on: on_on, send: send_send }); }(win, domain, serializedData), metaData: metaData, sender: { win: win, domain: domain }, reference: reference }; } var PROP_TYPE = { STRING: "string", OBJECT: "object", FUNCTION: "function", BOOLEAN: "boolean", NUMBER: "number", ARRAY: "array" }; var PROP_SERIALIZATION = { JSON: "json", DOTIFY: "dotify", BASE64: "base64" }; var CONTEXT = { IFRAME: "iframe", POPUP: "popup" }; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", DISPLAY: "zoid-display", ERROR: "zoid-error", CLOSE: "zoid-close", DESTROY: "zoid-destroy", PROPS: "zoid-props", RESIZE: "zoid-resize", FOCUS: "zoid-focus" }; function buildChildWindowName(_ref) { return "__zoid__" + _ref.name + "__" + _ref.serializedPayload + "__"; } function parseWindowName(windowName) { if (!windowName) throw new Error("No window name"); var _windowName$split = windowName.split("__"), zoidcomp = _windowName$split[1], name = _windowName$split[2], serializedInitialPayload = _windowName$split[3]; if ("zoid" !== zoidcomp) throw new Error("Window not rendered by zoid - got " + zoidcomp); if (!name) throw new Error("Expected component name"); if (!serializedInitialPayload) throw new Error("Expected serialized payload ref"); return { name: name, serializedInitialPayload: serializedInitialPayload }; } var parseInitialParentPayload = memoize((function(windowName) { var _crossDomainDeseriali = crossDomainDeserialize({ data: parseWindowName(windowName).serializedInitialPayload, sender: { win: function(_ref2) { return function(windowRef) { if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { void 0 === n && (n = 1); var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; parent = src_utils_getParent(parent); } return parent; }(win, utils_getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; var ancestor = utils_getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); if (win) return { v: win }; } } }(); if ("object" == typeof _ret) return _ret.v; } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { var frame = utils_getFrameByName(win, name); if (frame) return frame; for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } }(utils_getTop(win) || win, name); }(assertExists("ancestor", utils_getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); } } }); return { parent: _crossDomainDeseriali.sender, payload: _crossDomainDeseriali.data, reference: _crossDomainDeseriali.reference }; })); function getInitialParentPayload() { return parseInitialParentPayload(window.name); } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); if (targetWindow === src_utils_getParent(currentWindow)) return { type: "parent", distance: utils_getDistanceFromTop(targetWindow) }; if (targetWindow === utils_getOpener(currentWindow)) return { type: "opener" }; if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { var windowName = utils_assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName }; } var win; } function normalizeChildProp(propsDef, props, key, value, helpers) { if (!propsDef.hasOwnProperty(key)) return value; var prop = propsDef[key]; return "function" == typeof prop.childDecorate ? prop.childDecorate({ value: value, uid: helpers.uid, tag: helpers.tag, close: helpers.close, focus: helpers.focus, onError: helpers.onError, onProps: helpers.onProps, resize: helpers.resize, getParent: helpers.getParent, getParentDomain: helpers.getParentDomain, show: helpers.show, hide: helpers.hide, export: helpers.export, getSiblings: helpers.getSiblings }) : value; } function child_focus() { return promise_ZalgoPromise.try((function() { window.focus(); })); } function child_destroy() { return promise_ZalgoPromise.try((function() { window.close(); })); } var props_defaultNoop = function() { return src_util_noop; }; var props_decorateOnce = function(_ref) { return once(_ref.value); }; function eachProp(props, propsDef, handler) { for (var _i2 = 0, _Object$keys2 = Object.keys(_extends({}, props, propsDef)); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; handler(key, propsDef[key], props[key]); } } function serializeProps(propsDef, props, method) { var params = {}; return promise_ZalgoPromise.all(function(props, propsDef, handler) { var results = []; eachProp(props, propsDef, (function(key, propDef, value) { var result = function(key, propDef, value) { return promise_ZalgoPromise.resolve().then((function() { var _METHOD$GET$METHOD$PO, _METHOD$GET$METHOD$PO2; if (null != value && propDef) { var getParam = (_METHOD$GET$METHOD$PO = {}, _METHOD$GET$METHOD$PO.get = propDef.queryParam, _METHOD$GET$METHOD$PO.post = propDef.bodyParam, _METHOD$GET$METHOD$PO)[method]; var getValue = (_METHOD$GET$METHOD$PO2 = {}, _METHOD$GET$METHOD$PO2.get = propDef.queryValue, _METHOD$GET$METHOD$PO2.post = propDef.bodyValue, _METHOD$GET$METHOD$PO2)[method]; if (getParam) return promise_ZalgoPromise.hash({ finalParam: promise_ZalgoPromise.try((function() { return "function" == typeof getParam ? getParam({ value: value }) : "string" == typeof getParam ? getParam : key; })), finalValue: promise_ZalgoPromise.try((function() { return "function" == typeof getValue && isDefined(value) ? getValue({ value: value }) : value; })) }).then((function(_ref) { var finalParam = _ref.finalParam, finalValue = _ref.finalValue; var result; if ("boolean" == typeof finalValue) result = finalValue.toString(); else if ("string" == typeof finalValue) result = finalValue.toString(); else if ("object" == typeof finalValue && null !== finalValue) { if (propDef.serialization === PROP_SERIALIZATION.JSON) result = JSON.stringify(finalValue); else if (propDef.serialization === PROP_SERIALIZATION.BASE64) result = base64encode(JSON.stringify(finalValue)); else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) { result = function dotify(obj, prefix, newobj) { void 0 === prefix && (prefix = ""); void 0 === newobj && (newobj = {}); prefix = prefix ? prefix + "." : prefix; for (var key in obj) obj.hasOwnProperty(key) && null != obj[key] && "function" != typeof obj[key] && (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every((function(val) { return "object" != typeof val; })) ? newobj["" + prefix + key + "[]"] = obj[key].join(",") : obj[key] && "object" == typeof obj[key] ? newobj = dotify(obj[key], "" + prefix + key, newobj) : newobj["" + prefix + key] = obj[key].toString()); return newobj; }(finalValue, key); for (var _i2 = 0, _Object$keys2 = Object.keys(result); _i2 < _Object$keys2.length; _i2++) { var dotkey = _Object$keys2[_i2]; params[dotkey] = result[dotkey]; } return; } } else "number" == typeof finalValue && (result = finalValue.toString()); params[finalParam] = result; })); } })); }(key, propDef, value); results.push(result); })); return results; }(props, propsDef)).then((function() { return params; })); } function parentComponent(_ref) { var uid = _ref.uid, options = _ref.options, _ref$overrides = _ref.overrides, overrides = void 0 === _ref$overrides ? {} : _ref$overrides, _ref$parentWin = _ref.parentWin, parentWin = void 0 === _ref$parentWin ? window : _ref$parentWin; var propsDef = options.propsDef, containerTemplate = options.containerTemplate, prerenderTemplate = options.prerenderTemplate, tag = options.tag, name = options.name, attributes = options.attributes, dimensions = options.dimensions, autoResize = options.autoResize, url = options.url, domainMatch = options.domain, xports = options.exports; var initPromise = new promise_ZalgoPromise; var handledErrors = []; var clean = cleanup(); var state = {}; var inputProps = {}; var internalState = { visible: !0 }; var event = overrides.event ? overrides.event : (triggered = {}, handlers = {}, emitter = { on: function(eventName, handler) { var handlerList = handlers[eventName] = handlers[eventName] || []; handlerList.push(handler); var cancelled = !1; return { cancel: function() { if (!cancelled) { cancelled = !0; handlerList.splice(handlerList.indexOf(handler), 1); } } }; }, once: function(eventName, handler) { var listener = emitter.on(eventName, (function() { listener.cancel(); handler(); })); return listener; }, trigger: function(eventName) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3]; var handlerList = handlers[eventName]; var promises = []; if (handlerList) { var _loop = function(_i2) { var handler = handlerList[_i2]; promises.push(promise_ZalgoPromise.try((function() { return handler.apply(void 0, args); }))); }; for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(_i2); } return promise_ZalgoPromise.all(promises).then(src_util_noop); }, triggerOnce: function(eventName) { if (triggered[eventName]) return promise_ZalgoPromise.resolve(); triggered[eventName] = !0; for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) args[_key4 - 1] = arguments[_key4]; return emitter.trigger.apply(emitter, [ eventName ].concat(args)); }, reset: function() { handlers = {}; } }); var triggered, handlers, emitter; var props = overrides.props ? overrides.props : {}; var currentProxyWin; var currentProxyContainer; var childComponent; var currentChildDomain; var currentContainer; var onErrorOverride = overrides.onError; var getProxyContainerOverride = overrides.getProxyContainer; var showOverride = overrides.show; var hideOverride = overrides.hide; var closeOverride = overrides.close; var renderContainerOverride = overrides.renderContainer; var getProxyWindowOverride = overrides.getProxyWindow; var setProxyWinOverride = overrides.setProxyWin; var openFrameOverride = overrides.openFrame; var openPrerenderFrameOverride = overrides.openPrerenderFrame; var prerenderOverride = overrides.prerender; var openOverride = overrides.open; var openPrerenderOverride = overrides.openPrerender; var watchForUnloadOverride = overrides.watchForUnload; var getInternalStateOverride = overrides.getInternalState; var setInternalStateOverride = overrides.setInternalState; var getDimensions = function() { return "function" == typeof dimensions ? dimensions({ props: props }) : dimensions; }; var resolveInitPromise = function() { return promise_ZalgoPromise.try((function() { return overrides.resolveInitPromise ? overrides.resolveInitPromise() : initPromise.resolve(); })); }; var rejectInitPromise = function(err) { return promise_ZalgoPromise.try((function() { return overrides.rejectInitPromise ? overrides.rejectInitPromise(err) : initPromise.reject(err); })); }; var getPropsForChild = function(initialChildDomain) { var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; var getInternalState = function() { return promise_ZalgoPromise.try((function() { return getInternalStateOverride ? getInternalStateOverride() : internalState; })); }; var setInternalState = function(newInternalState) { return promise_ZalgoPromise.try((function() { return setInternalStateOverride ? setInternalStateOverride(newInternalState) : internalState = _extends({}, internalState, newInternalState); })); }; var getProxyWindow = function() { return getProxyWindowOverride ? getProxyWindowOverride() : promise_ZalgoPromise.try((function() { var windowProp = props.window; if (windowProp) { var _proxyWin = setup_toProxyWindow(windowProp); clean.register((function() { return windowProp.close(); })); return _proxyWin; } return new window_ProxyWindow({ send: send_send }); })); }; var setProxyWin = function(proxyWin) { return setProxyWinOverride ? setProxyWinOverride(proxyWin) : promise_ZalgoPromise.try((function() { currentProxyWin = proxyWin; })); }; var show = function() { return showOverride ? showOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !0 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null }).then(src_util_noop); }; var hide = function() { return hideOverride ? hideOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !1 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null }).then(src_util_noop); }; var getUrl = function() { return "function" == typeof url ? url({ props: props }) : url; }; var getAttributes = function() { return "function" == typeof attributes ? attributes({ props: props }) : attributes; }; var getInitialChildDomain = function() { return utils_getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; return openFrameOverride ? openFrameOverride(context, { windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: windowName, title: name }, getAttributes().iframe) })); })); }; var openPrerenderFrame = function(context) { return openPrerenderFrameOverride ? openPrerenderFrameOverride(context) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: "__zoid_prerender_frame__" + name + "_" + uniqueID() + "__", title: "prerender__" + name }, getAttributes().iframe) })); })); }; var openPrerender = function(context, proxyWin, proxyPrerenderFrame) { return openPrerenderOverride ? openPrerenderOverride(context, proxyWin, proxyPrerenderFrame) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyPrerenderFrame) throw new Error("Expected proxy frame to be passed"); return proxyPrerenderFrame.get().then((function(prerenderFrame) { clean.register((function() { return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { return utils_assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); })); } if (context === CONTEXT.POPUP) return proxyWin; throw new Error("No render context available for " + context); })); }; var focus = function() { return promise_ZalgoPromise.try((function() { if (currentProxyWin) return promise_ZalgoPromise.all([ event.trigger(EVENT.FOCUS), currentProxyWin.focus() ]).then(src_util_noop); })); }; var getCurrentWindowReferenceUID = function() { var global = lib_global_getGlobal(window); global.windows = global.windows || {}; global.windows[uid] = window; clean.register((function() { delete global.windows[uid]; })); return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { if (initialChildDomain === utils_getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; if (target !== window) throw new Error("Can not construct cross-domain window reference for different target window"); if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", distance: utils_getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; var initChild = function(childDomain, childExports) { return promise_ZalgoPromise.try((function() { currentChildDomain = childDomain; childComponent = childExports; resolveInitPromise(); clean.register((function() { return childExports.close.fireAndForget().catch(src_util_noop); })); })); }; var resize = function(_ref3) { var width = _ref3.width, height = _ref3.height; return promise_ZalgoPromise.try((function() { event.trigger(EVENT.RESIZE, { width: width, height: height }); })); }; var destroy = function(err) { return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.DESTROY); })).catch(src_util_noop).then((function() { return clean.all(err); })).then((function() { initPromise.asyncReject(err || new Error("Component destroyed")); })); }; var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { if (utils_isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.CLOSE); })).then((function() { return destroy(err || new Error("Component closed")); })); })); })); var open = function(context, _ref4) { var proxyWin = _ref4.proxyWin, proxyFrame = _ref4.proxyFrame, windowName = _ref4.windowName; return openOverride ? openOverride(context, { proxyWin: proxyWin, proxyFrame: proxyFrame, windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyFrame) throw new Error("Expected proxy frame to be passed"); return proxyFrame.get().then((function(frame) { return awaitFrameWindow(frame).then((function(win) { clean.register((function() { return destroyElement(frame); })); clean.register((function() { return cleanUpWindow(win); })); return win; })); })); } if (context === CONTEXT.POPUP) { var _getDimensions = getDimensions(), _getDimensions$width = _getDimensions.width, width = void 0 === _getDimensions$width ? "300px" : _getDimensions$width, _getDimensions$height = _getDimensions.height, height = void 0 === _getDimensions$height ? "150px" : _getDimensions$height; width = normalizeDimension(width, window.outerWidth); height = normalizeDimension(height, window.outerWidth); var win = function(url, options) { var _options$closeOnUnloa = (options = options || {}).closeOnUnload, closeOnUnload = void 0 === _options$closeOnUnloa ? 1 : _options$closeOnUnloa, _options$name = options.name, name = void 0 === _options$name ? "" : _options$name, width = options.width, height = options.height; var top = 0; var left = 0; width && (window.outerWidth ? left = Math.round((window.outerWidth - width) / 2) + window.screenX : window.screen.width && (left = Math.round((window.screen.width - width) / 2))); height && (window.outerHeight ? top = Math.round((window.outerHeight - height) / 2) + window.screenY : window.screen.height && (top = Math.round((window.screen.height - height) / 2))); delete options.closeOnUnload; delete options.name; width && height && (options = _extends({ top: top, left: left, width: width, height: height, status: 1, toolbar: 0, menubar: 0, resizable: 1, scrollbars: 1 }, options)); var params = Object.keys(options).map((function(key) { if (null != options[key]) return key + "=" + stringify(options[key]); })).filter(Boolean).join(","); var win; try { win = window.open("", name, params); } catch (err) { throw new dom_PopupOpenError("Can not open popup window - " + (err.stack || err.message)); } if (isWindowClosed(win)) { var err; throw new dom_PopupOpenError("Can not open popup window - blocked"); } closeOnUnload && window.addEventListener("unload", (function() { return win.close(); })); return win; }(0, _extends({ name: windowName, width: width, height: height }, getAttributes().popup)); clean.register((function() { return function(win) { if (function(win) { void 0 === win && (win = window); return Boolean(src_utils_getParent(win)); }(win)) { var frame = function(win) { if (utils_isSameDomain(win)) return utils_assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { var frame = _document$querySelect2[_i21]; if (frame && frame.contentWindow && frame.contentWindow === win) return frame; } }(win); if (frame && frame.parentElement) { frame.parentElement.removeChild(frame); return; } } try { win.close(); } catch (err) {} }(win); })); clean.register((function() { return cleanUpWindow(win); })); return win; } throw new Error("No render context available for " + context); })).then((function(win) { proxyWin.setWindow(win, { send: send_send }); return proxyWin.setName(windowName).then((function() { return proxyWin; })); })); }; var watchForUnload = function() { return promise_ZalgoPromise.try((function() { var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); })); }; var checkWindowClose = function(proxyWin) { var closed = !1; return proxyWin.isClosed().then((function(isClosed) { if (isClosed) { closed = !0; return close(new Error("Detected component window close")); } return promise_ZalgoPromise.delay(200).then((function() { return proxyWin.isClosed(); })).then((function(secondIsClosed) { if (secondIsClosed) { closed = !0; return close(new Error("Detected component window close")); } })); })).then((function() { return closed; })); }; var onError = function(err) { return onErrorOverride ? onErrorOverride(err) : promise_ZalgoPromise.try((function() { if (-1 === handledErrors.indexOf(err)) { handledErrors.push(err); initPromise.asyncReject(err); return event.trigger(EVENT.ERROR, err); } })); }; var exportsPromise = new promise_ZalgoPromise; var xport = function(actualExports) { return promise_ZalgoPromise.try((function() { exportsPromise.resolve(actualExports); })); }; initChild.onError = onError; var renderTemplate = function(renderer, _ref8) { return renderer({ uid: uid, container: _ref8.container, context: _ref8.context, doc: _ref8.doc, frame: _ref8.frame, prerenderFrame: _ref8.prerenderFrame, focus: focus, close: close, state: state, props: props, tag: tag, dimensions: getDimensions(), event: event }); }; var prerender = function(proxyPrerenderWin, _ref9) { var context = _ref9.context; return prerenderOverride ? prerenderOverride(proxyPrerenderWin, { context: context }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc }); if (el) { if (el.ownerDocument !== doc) throw new Error("Expected prerender template to have been created with document from child window"); !function(win, el) { var tag = el.tagName.toLowerCase(); if ("html" !== tag) throw new Error("Expected element to be html, got " + tag); var documentElement = win.document.documentElement; for (var _i6 = 0, _arrayFrom2 = arrayFrom(documentElement.children); _i6 < _arrayFrom2.length; _i6++) documentElement.removeChild(_arrayFrom2[_i6]); for (var _i8 = 0, _arrayFrom4 = arrayFrom(el.children); _i8 < _arrayFrom4.length; _i8++) documentElement.appendChild(_arrayFrom4[_i8]); }(prerenderWindow, el); var _autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, element = void 0 === _autoResize$element ? "body" : _autoResize$element; if ((element = getElementSafe(element, doc)) && (width || height)) { var prerenderResizeListener = onResize(element, (function(_ref10) { resize({ width: width ? _ref10.width : void 0, height: height ? _ref10.height : void 0 }); }), { width: width, height: height, win: prerenderWindow }); event.on(EVENT.RENDERED, prerenderResizeListener.cancel); } } } } })); }; var renderContainer = function(proxyContainer, _ref11) { var proxyFrame = _ref11.proxyFrame, proxyPrerenderFrame = _ref11.proxyPrerenderFrame, context = _ref11.context, rerender = _ref11.rerender; return renderContainerOverride ? renderContainerOverride(proxyContainer, { proxyFrame: proxyFrame, proxyPrerenderFrame: proxyPrerenderFrame, context: context, rerender: rerender }) : promise_ZalgoPromise.hash({ container: proxyContainer.get(), frame: proxyFrame ? proxyFrame.get() : null, prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null, internalState: getInternalState() }).then((function(_ref12) { var container = _ref12.container, visible = _ref12.internalState.visible; var innerContainer = renderTemplate(containerTemplate, { context: context, container: container, frame: _ref12.frame, prerenderFrame: _ref12.prerenderFrame, doc: document }); if (innerContainer) { visible || hideElement(innerContainer); appendChild(container, innerContainer); var containerWatcher = function(element, handler) { handler = once(handler); var cancelled = !1; var mutationObservers = []; var interval; var sacrificialFrame; var sacrificialFrameWin; var cancel = function() { cancelled = !0; for (var _i18 = 0; _i18 < mutationObservers.length; _i18++) mutationObservers[_i18].disconnect(); interval && interval.cancel(); sacrificialFrameWin && sacrificialFrameWin.removeEventListener("unload", elementClosed); sacrificialFrame && destroyElement(sacrificialFrame); }; var elementClosed = function() { if (!cancelled) { handler(); cancel(); } }; if (isElementClosed(element)) { elementClosed(); return { cancel: cancel }; } if (window.MutationObserver) { var mutationElement = element.parentElement; for (;mutationElement; ) { var mutationObserver = new window.MutationObserver((function() { isElementClosed(element) && elementClosed(); })); mutationObserver.observe(mutationElement, { childList: !0 }); mutationObservers.push(mutationObserver); mutationElement = mutationElement.parentElement; } } (sacrificialFrame = document.createElement("iframe")).setAttribute("name", "__detect_close_" + uniqueID() + "__"); sacrificialFrame.style.display = "none"; awaitFrameWindow(sacrificialFrame).then((function(frameWin) { (sacrificialFrameWin = assertSameDomain(frameWin)).addEventListener("unload", elementClosed); })); element.appendChild(sacrificialFrame); interval = safeInterval((function() { isElementClosed(element) && elementClosed(); }), 1e3); return { cancel: cancel }; }(innerContainer, (function() { var removeError = new Error("Detected container element removed from DOM"); return promise_ZalgoPromise.delay(1).then((function() { if (!isElementClosed(innerContainer)) { clean.all(removeError); return rerender().then(resolveInitPromise, rejectInitPromise); } close(removeError); })); })); clean.register((function() { return containerWatcher.cancel(); })); clean.register((function() { return destroyElement(innerContainer); })); return currentProxyContainer = getProxyObject(innerContainer); } })); }; var getHelpers = function() { return { state: state, event: event, close: close, focus: focus, resize: resize, onError: onError, updateProps: updateProps, show: show, hide: hide }; }; var setProps = function(newInputProps) { void 0 === newInputProps && (newInputProps = {}); var container = currentContainer; var helpers = getHelpers(); extend(inputProps, newInputProps); !function(propsDef, existingProps, inputProps, helpers, container) { var state = helpers.state, close = helpers.close, focus = helpers.focus, event = helpers.event, onError = helpers.onError; eachProp(inputProps, propsDef, (function(key, propDef, val) { var valueDetermined = !1; var value = val; Object.defineProperty(existingProps, key, { configurable: !0, enumerable: !0, get: function() { if (valueDetermined) return value; valueDetermined = !0; return function() { if (!propDef) return value; var alias = propDef.alias; alias && !isDefined(val) && isDefined(inputProps[alias]) && (value = inputProps[alias]); propDef.value && (value = propDef.value({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); !propDef.default || isDefined(value) || isDefined(inputProps[key]) || (value = propDef.default({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); if (isDefined(value)) { if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : typeof value !== propDef.type) throw new TypeError("Prop is not of type " + propDef.type + ": " + key); } else if (!1 !== propDef.required && !isDefined(inputProps[key])) throw new Error('Expected prop "' + key + '" to be defined'); isDefined(value) && propDef.decorate && (value = propDef.decorate({ value: value, props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); return value; }(); } }); })); eachProp(existingProps, propsDef, src_util_noop); }(propsDef, props, inputProps, helpers, container); }; var updateProps = function(newProps) { setProps(newProps); return initPromise.then((function() { var child = childComponent; var proxyWin = currentProxyWin; if (child && proxyWin && currentChildDomain) return getPropsForChild(currentChildDomain).then((function(childProps) { return child.updateProps(childProps).catch((function(err) { return checkWindowClose(proxyWin).then((function(closed) { if (!closed) throw err; })); })); })); })); }; var getProxyContainer = function(container) { return getProxyContainerOverride ? getProxyContainerOverride(container) : promise_ZalgoPromise.try((function() { return elementReady(container); })).then((function(containerElement) { isShadowElement(containerElement) && (containerElement = function insertShadowSlot(element) { var shadowHost = function(element) { var shadowRoot = function(element) { for (;element.parentNode; ) element = element.parentNode; if (isShadowElement(element)) return element; }(element); if (shadowRoot && shadowRoot.host) return shadowRoot.host; }(element); if (!shadowHost) throw new Error("Element is not in shadow dom"); var slotName = "shadow-slot-" + uniqueID(); var slot = document.createElement("slot"); slot.setAttribute("name", slotName); element.appendChild(slot); var slotProvider = document.createElement("div"); slotProvider.setAttribute("slot", slotName); shadowHost.appendChild(slotProvider); return isShadowElement(shadowHost) ? insertShadowSlot(slotProvider) : slotProvider; }(containerElement)); currentContainer = containerElement; return getProxyObject(containerElement); })); }; return { init: function() { !function() { event.on(EVENT.RENDER, (function() { return props.onRender(); })); event.on(EVENT.DISPLAY, (function() { return props.onDisplay(); })); event.on(EVENT.RENDERED, (function() { return props.onRendered(); })); event.on(EVENT.CLOSE, (function() { return props.onClose(); })); event.on(EVENT.DESTROY, (function() { return props.onDestroy(); })); event.on(EVENT.RESIZE, (function() { return props.onResize(); })); event.on(EVENT.FOCUS, (function() { return props.onFocus(); })); event.on(EVENT.PROPS, (function(newProps) { return props.onProps(newProps); })); event.on(EVENT.ERROR, (function(err) { return props && props.onError ? props.onError(err) : rejectInitPromise(err).then((function() { setTimeout((function() { throw err; }), 1); })); })); clean.register(event.reset); }(); }, render: function(_ref14) { var target = _ref14.target, container = _ref14.container, context = _ref14.context, rerender = _ref14.rerender; return promise_ZalgoPromise.try((function() { var initialChildDomain = getInitialChildDomain(); var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { if (!function(win1, win2) { var top1 = utils_getTop(win1) || win1; var top2 = utils_getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = utils_getAllFramesInWindow(win1); var allFrames2 = utils_getAllFramesInWindow(win2); if (utils_anyMatch(allFrames1, allFrames2)) return !0; var opener1 = utils_getOpener(top1); var opener2 = utils_getOpener(top2); return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), !1; }(window, target)) throw new Error("Can only renderTo an adjacent frame"); var origin = utils_getDomain(); if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); var delegatePromise = promise_ZalgoPromise.try((function() { if (target !== window) return function(context, target) { var delegateProps = {}; for (var _i4 = 0, _Object$keys4 = Object.keys(props); _i4 < _Object$keys4.length; _i4++) { var propName = _Object$keys4[_i4]; var propDef = propsDef[propName]; propDef && propDef.allowDelegate && (delegateProps[propName] = props[propName]); } var childOverridesPromise = send_send(target, "zoid_delegate_" + name, { uid: uid, overrides: { props: delegateProps, event: event, close: close, onError: onError, getInternalState: getInternalState, setInternalState: setInternalState, resolveInitPromise: resolveInitPromise, rejectInitPromise: rejectInitPromise } }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { if (!utils_isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { throw new Error("Unable to delegate rendering. Possibly the component is not loaded in the target window.\n\n" + stringifyError(err)); })); getProxyContainerOverride = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyContainer.apply(childOverrides, args); })); }; renderContainerOverride = function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.renderContainer.apply(childOverrides, args); })); }; showOverride = function() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) args[_key3] = arguments[_key3]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.show.apply(childOverrides, args); })); }; hideOverride = function() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) args[_key4] = arguments[_key4]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.hide.apply(childOverrides, args); })); }; watchForUnloadOverride = function() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) args[_key5] = arguments[_key5]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.watchForUnload.apply(childOverrides, args); })); }; if (context === CONTEXT.IFRAME) { getProxyWindowOverride = function() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) args[_key6] = arguments[_key6]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyWindow.apply(childOverrides, args); })); }; openFrameOverride = function() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) args[_key7] = arguments[_key7]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openFrame.apply(childOverrides, args); })); }; openPrerenderFrameOverride = function() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) args[_key8] = arguments[_key8]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerenderFrame.apply(childOverrides, args); })); }; prerenderOverride = function() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) args[_key9] = arguments[_key9]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.prerender.apply(childOverrides, args); })); }; openOverride = function() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) args[_key10] = arguments[_key10]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.open.apply(childOverrides, args); })); }; openPrerenderOverride = function() { for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) args[_key11] = arguments[_key11]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerender.apply(childOverrides, args); })); }; } else context === CONTEXT.POPUP && (setProxyWinOverride = function() { for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) args[_key12] = arguments[_key12]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.setProxyWin.apply(childOverrides, args); })); }); return childOverridesPromise; }(context, target); })); var windowProp = props.window; var watchForUnloadPromise = watchForUnload(); var buildBodyPromise = serializeProps(propsDef, props, "post"); var onRenderPromise = event.trigger(EVENT.RENDER); var getProxyContainerPromise = getProxyContainer(container); var getProxyWindowPromise = getProxyWindow(); var finalSetPropsPromise = getProxyContainerPromise.then((function() { return setProps(); })); var buildUrlPromise = finalSetPropsPromise.then((function() { return serializeProps(propsDef, props, "get").then((function(query) { return function(url, options) { var query = options.query || {}; var hash = options.hash || {}; var originalUrl; var originalHash; var _url$split = url.split("#"); originalHash = _url$split[1]; var _originalUrl$split = (originalUrl = _url$split[0]).split("?"); originalUrl = _originalUrl$split[0]; var queryString = extendQuery(_originalUrl$split[1], query); var hashString = extendQuery(originalHash, hash); queryString && (originalUrl = originalUrl + "?" + queryString); hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; }(utils_normalizeMockUrl(getUrl()), { query: query }); })); })); var buildWindowNamePromise = getProxyWindowPromise.then((function(proxyWin) { return function(_temp2) { var _ref6 = void 0 === _temp2 ? {} : _temp2, proxyWin = _ref6.proxyWin, initialChildDomain = _ref6.initialChildDomain, childDomainMatch = _ref6.childDomainMatch, _ref6$target = _ref6.target, target = void 0 === _ref6$target ? window : _ref6$target, context = _ref6.context; return function(_temp) { var _ref5 = void 0 === _temp ? {} : _temp, proxyWin = _ref5.proxyWin, childDomainMatch = _ref5.childDomainMatch, context = _ref5.context; return getPropsForChild(_ref5.initialChildDomain).then((function(childProps) { return { uid: uid, context: context, tag: tag, childDomainMatch: childDomainMatch, version: "9_0_87", props: childProps, exports: (win = proxyWin, { init: function(childExports) { return initChild(this.origin, childExports); }, close: close, checkClose: function() { return checkWindowClose(win); }, resize: resize, onError: onError, show: show, hide: hide, export: xport }) }; var win; })); }({ proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, context: context }).then((function(childPayload) { var _crossDomainSerialize = crossDomainSerialize({ data: childPayload, metaData: { windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { domain: utils_getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, passByReference: initialChildDomain === utils_getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; })); }({ proxyWin: (_ref7 = { proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, target: target, context: context }).proxyWin, initialChildDomain: _ref7.initialChildDomain, childDomainMatch: _ref7.childDomainMatch, target: _ref7.target, context: _ref7.context }).then((function(serializedPayload) { return buildChildWindowName({ name: name, serializedPayload: serializedPayload }); })); var _ref7; })); var openFramePromise = buildWindowNamePromise.then((function(windowName) { return openFrame(context, { windowName: windowName }); })); var openPrerenderFramePromise = openPrerenderFrame(context); var renderContainerPromise = promise_ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref15) { return renderContainer(_ref15.proxyContainer, { context: context, proxyFrame: _ref15.proxyFrame, proxyPrerenderFrame: _ref15.proxyPrerenderFrame, rerender: rerender }); })).then((function(proxyContainer) { return proxyContainer; })); var openPromise = promise_ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then((function(_ref16) { var proxyWin = _ref16.proxyWin; return windowProp ? proxyWin : open(context, { windowName: _ref16.windowName, proxyWin: proxyWin, proxyFrame: _ref16.proxyFrame }); })); var openPrerenderPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref17) { return openPrerender(context, _ref17.proxyWin, _ref17.proxyPrerenderFrame); })); var setStatePromise = openPromise.then((function(proxyWin) { currentProxyWin = proxyWin; return setProxyWin(proxyWin); })); var prerenderPromise = promise_ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then((function(_ref18) { return prerender(_ref18.proxyPrerenderWin, { context: context }); })); var setWindowNamePromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then((function(_ref19) { if (windowProp) return _ref19.proxyWin.setName(_ref19.windowName); })); var getMethodPromise = promise_ZalgoPromise.hash({ body: buildBodyPromise }).then((function(_ref20) { return options.method ? options.method : Object.keys(_ref20.body).length ? "post" : "get"; })); var loadUrlPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then((function(_ref21) { return _ref21.proxyWin.setLocation(_ref21.windowUrl, { method: _ref21.method, body: _ref21.body }); })); var watchForClosePromise = openPromise.then((function(proxyWin) { !function watchForClose(proxyWin, context) { var cancelled = !1; clean.register((function() { cancelled = !0; })); return promise_ZalgoPromise.delay(2e3).then((function() { return proxyWin.isClosed(); })).then((function(isClosed) { if (!cancelled) return isClosed ? close(new Error("Detected " + context + " close")) : watchForClose(proxyWin, context); })); }(proxyWin, context); })); var onDisplayPromise = promise_ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then((function() { return event.trigger(EVENT.DISPLAY); })); var openBridgePromise = openPromise.then((function(proxyWin) { return function(proxyWin, initialChildDomain, context) { return promise_ZalgoPromise.try((function() { return proxyWin.awaitWindow(); })).then((function(win) { if (src_bridge && src_bridge.needsBridge({ win: win, domain: initialChildDomain }) && !src_bridge.hasBridge(initialChildDomain, initialChildDomain)) { var bridgeUrl = "function" == typeof options.bridgeUrl ? options.bridgeUrl({ props: props }) : options.bridgeUrl; if (!bridgeUrl) throw new Error("Bridge needed to render " + context); var bridgeDomain = utils_getDomainFromUrl(bridgeUrl); src_bridge.linkUrl(win, initialChildDomain); return src_bridge.openBridge(utils_normalizeMockUrl(bridgeUrl), bridgeDomain); } })); }(proxyWin, initialChildDomain, context); })); var runTimeoutPromise = loadUrlPromise.then((function() { return promise_ZalgoPromise.try((function() { var timeout = props.timeout; if (timeout) return initPromise.timeout(timeout, new Error("Loading component timed out after " + timeout + " milliseconds")); })); })); var onRenderedPromise = initPromise.then((function() { return event.trigger(EVENT.RENDERED); })); return promise_ZalgoPromise.hash({ initPromise: initPromise, buildUrlPromise: buildUrlPromise, onRenderPromise: onRenderPromise, getProxyContainerPromise: getProxyContainerPromise, openFramePromise: openFramePromise, openPrerenderFramePromise: openPrerenderFramePromise, renderContainerPromise: renderContainerPromise, openPromise: openPromise, openPrerenderPromise: openPrerenderPromise, setStatePromise: setStatePromise, prerenderPromise: prerenderPromise, loadUrlPromise: loadUrlPromise, buildWindowNamePromise: buildWindowNamePromise, setWindowNamePromise: setWindowNamePromise, watchForClosePromise: watchForClosePromise, onDisplayPromise: onDisplayPromise, openBridgePromise: openBridgePromise, runTimeoutPromise: runTimeoutPromise, onRenderedPromise: onRenderedPromise, delegatePromise: delegatePromise, watchForUnloadPromise: watchForUnloadPromise, finalSetPropsPromise: finalSetPropsPromise }); })).catch((function(err) { return promise_ZalgoPromise.all([ onError(err), destroy(err) ]).then((function() { throw err; }), (function() { throw err; })); })).then(src_util_noop); }, destroy: destroy, getProps: function() { return props; }, setProps: setProps, export: xport, getHelpers: getHelpers, getDelegateOverrides: function() { return promise_ZalgoPromise.try((function() { return { getProxyContainer: getProxyContainer, show: show, hide: hide, renderContainer: renderContainer, getProxyWindow: getProxyWindow, watchForUnload: watchForUnload, openFrame: openFrame, openPrerenderFrame: openPrerenderFrame, prerender: prerender, open: open, openPrerender: openPrerender, setProxyWin: setProxyWin }; })); }, getExports: function() { return xports({ getExports: function() { return exportsPromise; } }); } }; } var react = { register: function(tag, propsDef, init, _ref) { var React = _ref.React, ReactDOM = _ref.ReactDOM; return function(_React$Component) { _inheritsLoose(_class, _React$Component); function _class() { return _React$Component.apply(this, arguments) || this; } var _proto = _class.prototype; _proto.render = function() { return React.createElement("div", null); }; _proto.componentDidMount = function() { var el = ReactDOM.findDOMNode(this); var parent = init(extend({}, this.props)); parent.render(el, CONTEXT.IFRAME); this.setState({ parent: parent }); }; _proto.componentDidUpdate = function() { this.state && this.state.parent && this.state.parent.updateProps(extend({}, this.props)).catch(src_util_noop); }; return _class; }(React.Component); } }; var vue = { register: function(tag, propsDef, init, Vue) { return Vue.component(tag, { render: function(createElement) { return createElement("div"); }, inheritAttrs: !1, mounted: function() { var el = this.$el; this.parent = init(_extends({}, (props = this.$attrs, Object.keys(props).reduce((function(acc, key) { var value = props[key]; if ("style-object" === key || "styleObject" === key) { acc.style = value; acc.styleObject = value; } else key.includes("-") ? acc[dasherizeToCamel(key)] = value : acc[key] = value; return acc; }), {})))); var props; this.parent.render(el, CONTEXT.IFRAME); }, watch: { $attrs: { handler: function() { this.parent && this.$attrs && this.parent.updateProps(_extends({}, this.$attrs)).catch(src_util_noop); }, deep: !0 } } }); } }; var vue3 = { register: function(tag, propsDef, init) { return { template: "
", inheritAttrs: !1, mounted: function() { var el = this.$el; this.parent = init(_extends({}, (props = this.$attrs, Object.keys(props).reduce((function(acc, key) { var value = props[key]; if ("style-object" === key || "styleObject" === key) { acc.style = value; acc.styleObject = value; } else key.includes("-") ? acc[dasherizeToCamel(key)] = value : acc[key] = value; return acc; }), {})))); var props; this.parent.render(el, CONTEXT.IFRAME); }, watch: { $attrs: { handler: function() { this.parent && this.$attrs && this.parent.updateProps(_extends({}, this.$attrs)).catch(src_util_noop); }, deep: !0 } } }; } }; var angular = { register: function(tag, propsDef, init, ng) { return ng.module(tag, []).directive(dasherizeToCamel(tag), (function() { var scope = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(propsDef); _i2 < _Object$keys2.length; _i2++) scope[_Object$keys2[_i2]] = "="; scope.props = "="; return { scope: scope, restrict: "E", controller: [ "$scope", "$element", function($scope, $element) { function safeApply() { if ("$apply" !== $scope.$root.$$phase && "$digest" !== $scope.$root.$$phase) try { $scope.$apply(); } catch (err) {} } var getProps = function() { return replaceObject($scope.props, (function(item) { return "function" == typeof item ? function() { var result = item.apply(this, arguments); safeApply(); return result; } : item; })); }; var instance = init(getProps()); instance.render($element[0], CONTEXT.IFRAME); $scope.$watch((function() { instance.updateProps(getProps()).catch(src_util_noop); })); } ] }; })); } }; var angular2 = { register: function(tag, propsDef, init, _ref) { var AngularComponent = _ref.Component, NgModule = _ref.NgModule, ElementRef = _ref.ElementRef, NgZone = _ref.NgZone, Inject = _ref.Inject; var ComponentInstance = function() { function ComponentInstance(elementRef, zone) { this.elementRef = void 0; this.internalProps = void 0; this.parent = void 0; this.props = void 0; this.zone = void 0; this._props = void 0; this._props = {}; this.elementRef = elementRef; this.zone = zone; } var _proto = ComponentInstance.prototype; _proto.getProps = function() { var _this = this; return replaceObject(_extends({}, this.internalProps, this.props), (function(item) { if ("function" == typeof item) { var zone = _this.zone; return function() { var _arguments = arguments, _this2 = this; return zone.run((function() { return item.apply(_this2, _arguments); })); }; } return item; })); }; _proto.ngOnInit = function() { var targetElement = this.elementRef.nativeElement; this.parent = init(this.getProps()); this.parent.render(targetElement, CONTEXT.IFRAME); }; _proto.ngDoCheck = function() { if (this.parent && !function(obj1, obj2) { var checked = {}; for (var key in obj1) if (obj1.hasOwnProperty(key)) { checked[key] = !0; if (obj1[key] !== obj2[key]) return !1; } for (var _key in obj2) if (!checked[_key]) return !1; return !0; }(this._props, this.props)) { this._props = _extends({}, this.props); this.parent.updateProps(this.getProps()); } }; return ComponentInstance; }(); ComponentInstance.annotations = void 0; ComponentInstance.parameters = void 0; ComponentInstance.parameters = [ [ new Inject(ElementRef) ], [ new Inject(NgZone) ] ]; ComponentInstance.annotations = [ new AngularComponent({ selector: tag, template: "
", inputs: [ "props" ] }) ]; var ModuleInstance = function() {}; ModuleInstance.annotations = void 0; ModuleInstance.annotations = [ new NgModule({ declarations: [ ComponentInstance ], exports: [ ComponentInstance ] }) ]; return ModuleInstance; } }; function defaultContainerTemplate(_ref) { var uid = _ref.uid, frame = _ref.frame, prerenderFrame = _ref.prerenderFrame, doc = _ref.doc, props = _ref.props, event = _ref.event, dimensions = _ref.dimensions; var width = dimensions.width, height = dimensions.height; if (frame && prerenderFrame) { var div = doc.createElement("div"); div.setAttribute("id", uid); var style = doc.createElement("style"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); style.appendChild(doc.createTextNode("\n #" + uid + " {\n display: inline-block;\n position: relative;\n width: " + width + ";\n height: " + height + ";\n }\n\n #" + uid + " > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #" + uid + " > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #" + uid + " > iframe.zoid-visible {\n opacity: 1;\n }\n ")); div.appendChild(frame); div.appendChild(prerenderFrame); div.appendChild(style); prerenderFrame.classList.add("zoid-visible"); frame.classList.add("zoid-invisible"); event.on(EVENT.RENDERED, (function() { prerenderFrame.classList.remove("zoid-visible"); prerenderFrame.classList.add("zoid-invisible"); frame.classList.remove("zoid-invisible"); frame.classList.add("zoid-visible"); setTimeout((function() { destroyElement(prerenderFrame); }), 1); })); event.on(EVENT.RESIZE, (function(_ref2) { var newWidth = _ref2.width, newHeight = _ref2.height; "number" == typeof newWidth && (div.style.width = toCSS(newWidth)); "number" == typeof newHeight && (div.style.height = toCSS(newHeight)); })); return div; } } function defaultPrerenderTemplate(_ref) { var doc = _ref.doc, props = _ref.props; var html = doc.createElement("html"); var body = doc.createElement("body"); var style = doc.createElement("style"); var spinner = doc.createElement("div"); spinner.classList.add("spinner"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); html.appendChild(body); body.appendChild(spinner); body.appendChild(style); style.appendChild(doc.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")); return html; } var cleanInstances = cleanup(); var cleanZoid = cleanup(); function component(opts) { var options = function(options) { var tag = options.tag, url = options.url, domain = options.domain, bridgeUrl = options.bridgeUrl, _options$props = options.props, props = void 0 === _options$props ? {} : _options$props, _options$dimensions = options.dimensions, dimensions = void 0 === _options$dimensions ? {} : _options$dimensions, _options$autoResize = options.autoResize, autoResize = void 0 === _options$autoResize ? {} : _options$autoResize, _options$allowedParen = options.allowedParentDomains, allowedParentDomains = void 0 === _options$allowedParen ? "*" : _options$allowedParen, _options$attributes = options.attributes, attributes = void 0 === _options$attributes ? {} : _options$attributes, _options$defaultConte = options.defaultContext, defaultContext = void 0 === _options$defaultConte ? CONTEXT.IFRAME : _options$defaultConte, _options$containerTem = options.containerTemplate, containerTemplate = void 0 === _options$containerTem ? defaultContainerTemplate : _options$containerTem, _options$prerenderTem = options.prerenderTemplate, prerenderTemplate = void 0 === _options$prerenderTem ? defaultPrerenderTemplate : _options$prerenderTem, validate = options.validate, _options$eligible = options.eligible, eligible = void 0 === _options$eligible ? function() { return { eligible: !0 }; } : _options$eligible, _options$logger = options.logger, logger = void 0 === _options$logger ? { info: src_util_noop } : _options$logger, _options$exports = options.exports, xportsDefinition = void 0 === _options$exports ? src_util_noop : _options$exports, method = options.method, _options$children = options.children, children = void 0 === _options$children ? function() { return {}; } : _options$children; var name = tag.replace(/-/g, "_"); var propsDef = _extends({}, { window: { type: PROP_TYPE.OBJECT, sendToChild: !1, required: !1, allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); if (utils_isWindow(value)) { if (utils_isWindowClosed(value)) throw new Error("Window is closed"); if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { return setup_toProxyWindow(_ref3.value); } }, timeout: { type: PROP_TYPE.NUMBER, required: !1, sendToChild: !1 }, cspNonce: { type: PROP_TYPE.STRING, required: !1 }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onRendered: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onRender: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onClose: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onDestroy: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onResize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, onFocus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, close: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref4) { return _ref4.close; } }, focus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref5) { return _ref5.focus; } }, resize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref6) { return _ref6.resize; } }, uid: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref7) { return _ref7.uid; } }, tag: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref8) { return _ref8.tag; } }, getParent: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref9) { return _ref9.getParent; } }, getParentDomain: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref10) { return _ref10.getParentDomain; } }, show: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref11) { return _ref11.show; } }, hide: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref12) { return _ref12.hide; } }, export: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref13) { return _ref13.export; } }, onError: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref14) { return _ref14.onError; } }, onProps: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref15) { return _ref15.onProps; } }, getSiblings: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref16) { return _ref16.getSiblings; } } }, props); if (!containerTemplate) throw new Error("Container template required"); return { name: name, tag: tag, url: url, domain: domain, bridgeUrl: bridgeUrl, method: method, propsDef: propsDef, dimensions: dimensions, autoResize: autoResize, allowedParentDomains: allowedParentDomains, attributes: attributes, defaultContext: defaultContext, containerTemplate: containerTemplate, prerenderTemplate: prerenderTemplate, validate: validate, logger: logger, eligible: eligible, children: children, exports: "function" == typeof xportsDefinition ? xportsDefinition : function(_ref) { var getExports = _ref.getExports; var result = {}; var _loop = function(_i2, _Object$keys2) { var key = _Object$keys2[_i2]; var type = xportsDefinition[key].type; var valuePromise = getExports().then((function(res) { return res[key]; })); result[key] = type === PROP_TYPE.FUNCTION ? function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return valuePromise.then((function(value) { return value.apply(void 0, args); })); } : valuePromise; }; for (var _i2 = 0, _Object$keys2 = Object.keys(xportsDefinition); _i2 < _Object$keys2.length; _i2++) _loop(_i2, _Object$keys2); return result; } }; }(opts); var name = options.name, tag = options.tag, defaultContext = options.defaultContext, propsDef = options.propsDef, eligible = options.eligible, children = options.children; var global = lib_global_getGlobal(window); var driverCache = {}; var instances = []; var isChild = function() { if (function(name) { try { return parseWindowName(window.name).name === name; } catch (err) {} return !1; }(name)) { var _payload = getInitialParentPayload().payload; if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; } return !1; }; var registerChild = memoize((function() { if (isChild()) { if (window.xprops) { delete global.components[tag]; throw new Error("Can not register " + name + " as child - child already registered"); } var child = function(options) { var tag = options.tag, propsDef = options.propsDef, autoResize = options.autoResize, allowedParentDomains = options.allowedParentDomains; var onPropHandlers = []; var _getInitialParentPayl = getInitialParentPayload(), parent = _getInitialParentPayl.parent, payload = _getInitialParentPayl.payload; var parentComponentWindow = parent.win, parentDomain = parent.domain; var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; }; var getParentDomain = function() { return parentDomain; }; var onProps = function(handler) { onPropHandlers.push(handler); return { cancel: function() { onPropHandlers.splice(onPropHandlers.indexOf(handler), 1); } }; }; var resize = function(_ref) { return parentResize.fireAndForget({ width: _ref.width, height: _ref.height }); }; var xport = function(xports) { exportsPromise.resolve(xports); return parentExport(xports); }; var getSiblings = function(_temp) { var anyParent = (void 0 === _temp ? {} : _temp).anyParent; var result = []; var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(win)) { var xprops = utils_assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { var xports = tryGlobal(win, (function(global) { return global.exports; })); result.push({ props: xprops, exports: xports }); } } } } return result; }; var setProps = function(newProps, origin, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var normalizedProps = function(parentComponentWindow, propsDef, props, origin, helpers, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); } } if (!isUpdate) for (var _i4 = 0, _Object$keys4 = Object.keys(propsDef); _i4 < _Object$keys4.length; _i4++) { var _key = _Object$keys4[_i4]; props.hasOwnProperty(_key) || (result[_key] = normalizeChildProp(propsDef, 0, _key, void 0, helpers)); } return result; }(parentComponentWindow, propsDef, newProps, origin, { tag: tag, show: show, hide: hide, close: close, focus: child_focus, onError: onError, resize: resize, getSiblings: getSiblings, onProps: onProps, getParent: getParent, getParentDomain: getParentDomain, uid: uid, export: xport }, isUpdate); props ? extend(props, normalizedProps) : props = normalizedProps; for (var _i4 = 0; _i4 < onPropHandlers.length; _i4++) (0, onPropHandlers[_i4])(props); }; var updateProps = function(newProps) { return promise_ZalgoPromise.try((function() { return setProps(newProps, parentDomain, !0); })); }; return { init: function() { return promise_ZalgoPromise.try((function() { utils_isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, sender: { win: parentComponentWindow }, basic: !0 }), sender = _crossDomainDeseriali2.sender; if ("uid" === _crossDomainDeseriali2.reference.type || "global" === _crossDomainDeseriali2.metaData.windowRef.type) { var _crossDomainSerialize = crossDomainSerialize({ data: _crossDomainDeseriali2.data, metaData: { windowRef: window_getWindowRef(parentComponentWindow) }, sender: { domain: sender.domain }, receiver: { win: window, domain: utils_getDomain() }, basic: !0 }); window.name = buildChildWindowName({ name: componentName, serializedPayload: _crossDomainSerialize.serializedData }); } }({ componentName: options.name, parentComponentWindow: parentComponentWindow }); lib_global_getGlobal(window).exports = options.exports({ getExports: function() { return exportsPromise; } }); !function(allowedParentDomains, domain) { if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { window.addEventListener("beforeunload", (function() { checkClose.fireAndForget(); })); window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); utils_onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); return parentInit({ updateProps: updateProps, close: child_destroy }); })).then((function() { return (_autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, elementReady(void 0 === _autoResize$element ? "body" : _autoResize$element).catch(src_util_noop).then((function(element) { return { width: width, height: height, element: element }; }))).then((function(_ref3) { var width = _ref3.width, height = _ref3.height, element = _ref3.element; element && (width || height) && context !== CONTEXT.POPUP && onResize(element, (function(_ref4) { resize({ width: width ? _ref4.width : void 0, height: height ? _ref4.height : void 0 }); }), { width: width, height: height }); })); var _autoResize$width, width, _autoResize$height, height, _autoResize$element; })).catch((function(err) { onError(err); })); }, getProps: function() { if (props) return props; setProps(initialProps, parentDomain); return props; } }; }(options); child.init(); return child; } })); var init = function init(inputProps) { var instance; var uid = "zoid-" + tag + "-" + uniqueID(); var props = inputProps || {}; var _eligible = eligible({ props: props }), eligibility = _eligible.eligible, reason = _eligible.reason; var onDestroy = props.onDestroy; props.onDestroy = function() { instance && eligibility && instances.splice(instances.indexOf(instance), 1); if (onDestroy) return onDestroy.apply(void 0, arguments); }; var parent = parentComponent({ uid: uid, options: options }); parent.init(); eligibility ? parent.setProps(props) : props.onDestroy && props.onDestroy(); cleanInstances.register((function(err) { return parent.destroy(err || new Error("zoid destroyed all components")); })); var clone = function(_temp) { var _ref4$decorate = (void 0 === _temp ? {} : _temp).decorate; return init((void 0 === _ref4$decorate ? identity : _ref4$decorate)(props)); }; var _render = function(target, container, context) { return promise_ZalgoPromise.try((function() { if (!eligibility) { var err = new Error(reason || name + " component is not eligible"); return parent.destroy(err).then((function() { throw err; })); } if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); if (context) { if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) throw new Error("Unrecognized context: " + context); return context; } return defaultContext; })); }(props, context); })).then((function(finalContext) { container = function(context, container) { if (container) { if ("string" != typeof container && !isElement(container)) throw new TypeError("Expected string or element selector to be passed"); return container; } if (context === CONTEXT.POPUP) return "body"; throw new Error("Expected element to be passed to render iframe"); }(finalContext, container); if (target !== window && "string" != typeof container) throw new Error("Must pass string element when rendering to another window"); return parent.render({ target: target, container: container, context: finalContext, rerender: function() { var newInstance = clone(); extend(instance, newInstance); return newInstance.renderTo(target, container, context); } }); })).catch((function(err) { return parent.destroy(err).then((function() { throw err; })); })); }; instance = _extends({}, parent.getExports(), parent.getHelpers(), function() { var childComponents = children(); var result = {}; var _loop2 = function(_i4, _Object$keys4) { var childName = _Object$keys4[_i4]; var Child = childComponents[childName]; result[childName] = function(childInputProps) { var parentProps = parent.getProps(); var childProps = _extends({}, childInputProps, { parent: { uid: uid, props: parentProps, export: parent.export } }); return Child(childProps); }; }; for (var _i4 = 0, _Object$keys4 = Object.keys(childComponents); _i4 < _Object$keys4.length; _i4++) _loop2(_i4, _Object$keys4); return result; }(), { isEligible: function() { return eligibility; }, clone: clone, render: function(container, context) { return _render(window, container, context); }, renderTo: function(target, container, context) { return _render(target, container, context); } }); eligibility && instances.push(instance); return instance; }; registerChild(); !function() { var allowDelegateListener = on_on("zoid_allow_delegate_" + name, (function() { return !0; })); var delegateListener = on_on("zoid_delegate_" + name, (function(_ref2) { var _ref2$data = _ref2.data; return { parent: parentComponent({ uid: _ref2$data.uid, options: options, overrides: _ref2$data.overrides, parentWin: _ref2.source }) }; })); cleanZoid.register(allowDelegateListener.cancel); cleanZoid.register(delegateListener.cancel); }(); global.components = global.components || {}; if (global.components[tag]) throw new Error("Can not register multiple components with the same tag: " + tag); global.components[tag] = !0; return { init: init, instances: instances, driver: function(driverName, dep) { var drivers = { react: react, angular: angular, vue: vue, vue3: vue3, angular2: angular2 }; if (!drivers[driverName]) throw new Error("Could not find driver for framework: " + driverName); driverCache[driverName] || (driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep)); return driverCache[driverName]; }, isChild: isChild, canRenderTo: function(win) { return send_send(win, "zoid_allow_delegate_" + name).then((function(_ref3) { return _ref3.data; })).catch((function() { return !1; })); }, registerChild: registerChild }; } var component_create = function(options) { !function() { if (!global_getGlobal().initialized) { global_getGlobal().initialized = !0; on = (_ref3 = { on: on_on, send: send_send }).on, send = _ref3.send, (global = global_getGlobal()).receiveMessage = global.receiveMessage || function(message) { return receive_receiveMessage(message, { on: on, send: send }); }; !function(_ref5) { var on = _ref5.on, send = _ref5.send; globalStore().getOrSet("postMessageListener", (function() { return addEventListener(window, "message", (function(event) { !function(event, _ref4) { var on = _ref4.on, send = _ref4.send; promise_ZalgoPromise.try((function() { var source = event.source || event.sourceElement; var origin = event.origin || event.originalEvent && event.originalEvent.origin; var data = event.data; "null" === origin && (origin = "file://"); if (source) { if (!origin) throw new Error("Post message did not have origin domain"); receive_receiveMessage({ source: source, origin: origin, data: data }, { on: on, send: send }); } })); }(event, { on: on, send: send }); })); })); }({ on: on_on, send: send_send }); setupBridge({ on: on_on, send: send_send, receiveMessage: receive_receiveMessage }); !function(_ref8) { var on = _ref8.on, send = _ref8.send; globalStore("builtinListeners").getOrSet("helloListener", (function() { var listener = on("postrobot_hello", { domain: "*" }, (function(_ref3) { resolveHelloPromise(_ref3.source, { domain: _ref3.origin }); return { instanceID: getInstanceID() }; })); var parent = getAncestor(); parent && sayHello(parent, { send: send }).catch((function(err) {})); return listener; })); }({ on: on_on, send: send_send }); } var _ref3, on, send, global; }(); var comp = component(options); var init = function(props) { return comp.init(props); }; init.driver = function(name, dep) { return comp.driver(name, dep); }; init.isChild = function() { return comp.isChild(); }; init.canRenderTo = function(win) { return comp.canRenderTo(win); }; init.instances = comp.instances; var child = comp.registerChild(); child && (window.xprops = init.xprops = child.getProps()); return init; }; function destroyComponents(err) { src_bridge && src_bridge.destroyBridges(); var destroyPromise = cleanInstances.all(err); cleanInstances = cleanup(); return destroyPromise; } var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); delete window.__zoid_9_0_87__; !function() { !function() { var responseListeners = globalStore("responseListeners"); for (var _i2 = 0, _responseListeners$ke2 = responseListeners.keys(); _i2 < _responseListeners$ke2.length; _i2++) { var hash = _responseListeners$ke2[_i2]; var listener = responseListeners.get(hash); listener && (listener.cancelled = !0); responseListeners.del(hash); } }(); (listener = globalStore().get("postMessageListener")) && listener.cancel(); var listener; delete window.__post_robot_10_0_46__; }(); return cleanZoid.all(err); } } ]); })); ================================================ FILE: dist/zoid.js ================================================ !function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define("zoid", [], factory) : "object" == typeof exports ? exports.zoid = factory() : root.zoid = factory(); }("undefined" != typeof self ? self : this, (function() { return function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module = installedModules[moduleId] = { i: moduleId, l: !1, exports: {} }; modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); module.l = !0; return module.exports; } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d = function(exports, name, getter) { __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, { enumerable: !0, get: getter }); }; __webpack_require__.r = function(exports) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); Object.defineProperty(exports, "__esModule", { value: !0 }); }; __webpack_require__.t = function(value, mode) { 1 & mode && (value = __webpack_require__(value)); if (8 & mode) return value; if (4 & mode && "object" == typeof value && value && value.__esModule) return value; var ns = Object.create(null); __webpack_require__.r(ns); Object.defineProperty(ns, "default", { enumerable: !0, value: value }); if (2 & mode && "string" != typeof value) for (var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); return ns; }; __webpack_require__.n = function(module) { var getter = module && module.__esModule ? function() { return module.default; } : function() { return module; }; __webpack_require__.d(getter, "a", getter); return getter; }; __webpack_require__.o = function(object, property) { return {}.hasOwnProperty.call(object, property); }; __webpack_require__.p = ""; return __webpack_require__(__webpack_require__.s = 0); }([ function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, "PopupOpenError", (function() { return dom_PopupOpenError; })); __webpack_require__.d(__webpack_exports__, "create", (function() { return component_create; })); __webpack_require__.d(__webpack_exports__, "destroy", (function() { return component_destroy; })); __webpack_require__.d(__webpack_exports__, "destroyComponents", (function() { return destroyComponents; })); __webpack_require__.d(__webpack_exports__, "destroyAll", (function() { return destroyAll; })); __webpack_require__.d(__webpack_exports__, "PROP_TYPE", (function() { return PROP_TYPE; })); __webpack_require__.d(__webpack_exports__, "PROP_SERIALIZATION", (function() { return PROP_SERIALIZATION; })); __webpack_require__.d(__webpack_exports__, "CONTEXT", (function() { return CONTEXT; })); __webpack_require__.d(__webpack_exports__, "EVENT", (function() { return EVENT; })); function _setPrototypeOf(o, p) { return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) { o.__proto__ = p; return o; })(o, p); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _extends() { return (_extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) ({}).hasOwnProperty.call(source, key) && (target[key] = source[key]); } return target; }).apply(this, arguments); } function utils_isPromise(item) { try { if (!item) return !1; if ("undefined" != typeof Promise && item instanceof Promise) return !0; if ("undefined" != typeof window && "function" == typeof window.Window && item instanceof window.Window) return !1; if ("undefined" != typeof window && "function" == typeof window.constructor && item instanceof window.constructor) return !1; var _toString = {}.toString; if (_toString) { var name = _toString.call(item); if ("[object Window]" === name || "[object global]" === name || "[object DOMWindow]" === name) return !1; } if ("function" == typeof item.then) return !0; } catch (err) { return !1; } return !1; } var dispatchedErrors = []; var possiblyUnhandledPromiseHandlers = []; var activeCount = 0; var flushPromise; function flushActive() { if (!activeCount && flushPromise) { var promise = flushPromise; flushPromise = null; promise.resolve(); } } function startActive() { activeCount += 1; } function endActive() { activeCount -= 1; flushActive(); } var promise_ZalgoPromise = function() { function ZalgoPromise(handler) { var _this = this; this.resolved = void 0; this.rejected = void 0; this.errorHandled = void 0; this.value = void 0; this.error = void 0; this.handlers = void 0; this.dispatching = void 0; this.stack = void 0; this.resolved = !1; this.rejected = !1; this.errorHandled = !1; this.handlers = []; if (handler) { var _result; var _error; var resolved = !1; var rejected = !1; var isAsync = !1; startActive(); try { handler((function(res) { if (isAsync) _this.resolve(res); else { resolved = !0; _result = res; } }), (function(err) { if (isAsync) _this.reject(err); else { rejected = !0; _error = err; } })); } catch (err) { endActive(); this.reject(err); return; } endActive(); isAsync = !0; resolved ? this.resolve(_result) : rejected && this.reject(_error); } } var _proto = ZalgoPromise.prototype; _proto.resolve = function(result) { if (this.resolved || this.rejected) return this; if (utils_isPromise(result)) throw new Error("Can not resolve promise with another promise"); this.resolved = !0; this.value = result; this.dispatch(); return this; }; _proto.reject = function(error) { var _this2 = this; if (this.resolved || this.rejected) return this; if (utils_isPromise(error)) throw new Error("Can not reject promise with another promise"); if (!error) { var _err = error && "function" == typeof error.toString ? error.toString() : {}.toString.call(error); error = new Error("Expected reject to be called with Error, got " + _err); } this.rejected = !0; this.error = error; this.errorHandled || setTimeout((function() { _this2.errorHandled || function(err, promise) { if (-1 === dispatchedErrors.indexOf(err)) { dispatchedErrors.push(err); setTimeout((function() { throw err; }), 1); for (var j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) possiblyUnhandledPromiseHandlers[j](err, promise); } }(error, _this2); }), 1); this.dispatch(); return this; }; _proto.asyncReject = function(error) { this.errorHandled = !0; this.reject(error); return this; }; _proto.dispatch = function() { var resolved = this.resolved, rejected = this.rejected, handlers = this.handlers; if (!this.dispatching && (resolved || rejected)) { this.dispatching = !0; startActive(); var chain = function(firstPromise, secondPromise) { return firstPromise.then((function(res) { secondPromise.resolve(res); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < handlers.length; i++) { var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise; var _result2 = void 0; if (resolved) try { _result2 = onSuccess ? onSuccess(this.value) : this.value; } catch (err) { promise.reject(err); continue; } else if (rejected) { if (!onError) { promise.reject(this.error); continue; } try { _result2 = onError(this.error); } catch (err) { promise.reject(err); continue; } } if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) { var promiseResult = _result2; promiseResult.resolved ? promise.resolve(promiseResult.value) : promise.reject(promiseResult.error); promiseResult.errorHandled = !0; } else utils_isPromise(_result2) ? _result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected) ? _result2.resolved ? promise.resolve(_result2.value) : promise.reject(_result2.error) : chain(_result2, promise) : promise.resolve(_result2); } handlers.length = 0; this.dispatching = !1; endActive(); } }; _proto.then = function(onSuccess, onError) { if (onSuccess && "function" != typeof onSuccess && !onSuccess.call) throw new Error("Promise.then expected a function for success handler"); if (onError && "function" != typeof onError && !onError.call) throw new Error("Promise.then expected a function for error handler"); var promise = new ZalgoPromise; this.handlers.push({ promise: promise, onSuccess: onSuccess, onError: onError }); this.errorHandled = !0; this.dispatch(); return promise; }; _proto.catch = function(onError) { return this.then(void 0, onError); }; _proto.finally = function(onFinally) { if (onFinally && "function" != typeof onFinally && !onFinally.call) throw new Error("Promise.finally expected a function"); return this.then((function(result) { return ZalgoPromise.try(onFinally).then((function() { return result; })); }), (function(err) { return ZalgoPromise.try(onFinally).then((function() { throw err; })); })); }; _proto.timeout = function(time, err) { var _this3 = this; if (this.resolved || this.rejected) return this; var timeout = setTimeout((function() { _this3.resolved || _this3.rejected || _this3.reject(err || new Error("Promise timed out after " + time + "ms")); }), time); return this.then((function(result) { clearTimeout(timeout); return result; })); }; _proto.toPromise = function() { if ("undefined" == typeof Promise) throw new TypeError("Could not find Promise"); return Promise.resolve(this); }; _proto.lazy = function() { this.errorHandled = !0; return this; }; ZalgoPromise.resolve = function(value) { return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise((function(resolve, reject) { return value.then(resolve, reject); })) : (new ZalgoPromise).resolve(value); }; ZalgoPromise.reject = function(error) { return (new ZalgoPromise).reject(error); }; ZalgoPromise.asyncReject = function(error) { return (new ZalgoPromise).asyncReject(error); }; ZalgoPromise.all = function(promises) { var promise = new ZalgoPromise; var count = promises.length; var results = [].slice(); if (!count) { promise.resolve(results); return promise; } var chain = function(i, firstPromise, secondPromise) { return firstPromise.then((function(res) { results[i] = res; 0 == (count -= 1) && promise.resolve(results); }), (function(err) { secondPromise.reject(err); })); }; for (var i = 0; i < promises.length; i++) { var prom = promises[i]; if (prom instanceof ZalgoPromise) { if (prom.resolved) { results[i] = prom.value; count -= 1; continue; } } else if (!utils_isPromise(prom)) { results[i] = prom; count -= 1; continue; } chain(i, ZalgoPromise.resolve(prom), promise); } 0 === count && promise.resolve(results); return promise; }; ZalgoPromise.hash = function(promises) { var result = {}; var awaitPromises = []; var _loop = function(key) { if (promises.hasOwnProperty(key)) { var value = promises[key]; utils_isPromise(value) ? awaitPromises.push(value.then((function(res) { result[key] = res; }))) : result[key] = value; } }; for (var key in promises) _loop(key); return ZalgoPromise.all(awaitPromises).then((function() { return result; })); }; ZalgoPromise.map = function(items, method) { return ZalgoPromise.all(items.map(method)); }; ZalgoPromise.onPossiblyUnhandledException = function(handler) { return function(handler) { possiblyUnhandledPromiseHandlers.push(handler); return { cancel: function() { possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1); } }; }(handler); }; ZalgoPromise.try = function(method, context, args) { if (method && "function" != typeof method && !method.call) throw new Error("Promise.try expected a function"); var result; startActive(); try { result = method.apply(context, args || []); } catch (err) { endActive(); return ZalgoPromise.reject(err); } endActive(); return ZalgoPromise.resolve(result); }; ZalgoPromise.delay = function(_delay) { return new ZalgoPromise((function(resolve) { setTimeout(resolve, _delay); })); }; ZalgoPromise.isPromise = function(value) { return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value); }; ZalgoPromise.flush = function() { return function(Zalgo) { var promise = flushPromise = flushPromise || new Zalgo; flushActive(); return promise; }(ZalgoPromise); }; return ZalgoPromise; }(); function isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } var IE_WIN_ACCESS_ERROR = "Call was rejected by callee.\r\n"; function getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return getActualProtocol(win); } function isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === getProtocol(win); } function utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function getOpener(win) { void 0 === win && (win = window); if (win && !utils_getParent(win)) try { return win.opener; } catch (err) {} } function canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = utils_getParent(win); return parent && canReadFromWindow() ? getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function getDomain(win) { void 0 === win && (win = window); var domain = getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (isAboutProtocol(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === getProtocol(win); }(win) && canReadFromWindow()) return !0; } catch (err) {} try { if (getActualDomain(win) === getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (isAboutProtocol(win) && canReadFromWindow()) return !0; if (getDomain(window) === getDomain(win)) return !0; } catch (err) {} return !1; } function assertSameDomain(win) { if (!isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (utils_getParent(win) === win) return win; try { if (isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (utils_getParent(frame) === frame) return frame; } } function getAllFramesInWindow(win) { var top = getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], getAllChildFrames(win))); return result; } var iframeWindows = []; var iframeFrames = []; function isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || err.message !== IE_WIN_ACCESS_ERROR; } if (allowMock && isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(iframeWindows, win); if (-1 !== iframeIndex) { var frame = iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function utils_getUserAgent(win) { return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent; } function getFrameByName(win, name) { var winFrames = getFrames(win); for (var _i9 = 0; _i9 < winFrames.length; _i9++) { var childFrame = winFrames[_i9]; try { if (isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; } catch (err) {} } try { if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; } catch (err) {} try { if (-1 !== winFrames.indexOf(win[name])) return win[name]; } catch (err) {} } function isOpener(parent, child) { return parent === getOpener(child); } function getAncestor(win) { void 0 === win && (win = window); return getOpener(win = win || window) || utils_getParent(win) || void 0; } function anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function isSameTopWindow(win1, win2) { var top1 = getTop(win1) || win1; var top2 = getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = getAllFramesInWindow(win1); var allFrames2 = getAllFramesInWindow(win2); if (anyMatch(allFrames1, allFrames2)) return !0; var opener1 = getOpener(top1); var opener2 = getOpener(top2); return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), !1; } function matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some((function(subpattern) { return matchDomain(subpattern, origin); }))); } function getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : getDomain(); } function isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && err.message === IE_WIN_ACCESS_ERROR) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function getFrameForWindow(win) { if (isSameDomain(win)) return assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { var frame = _document$querySelect2[_i21]; if (frame && frame.contentWindow && frame.contentWindow === win) return frame; } } function closeWindow(win) { if (function(win) { void 0 === win && (win = window); return Boolean(utils_getParent(win)); }(win)) { var frame = getFrameForWindow(win); if (frame && frame.parentElement) { frame.parentElement.removeChild(frame); return; } } try { win.close(); } catch (err) {} } function util_safeIndexOf(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; } var weakmap_CrossDomainSafeWeakMap = function() { function CrossDomainSafeWeakMap() { this.name = void 0; this.weakmap = void 0; this.keys = void 0; this.values = void 0; this.name = "__weakmap_" + (1e9 * Math.random() >>> 0) + "__"; if (function() { if ("undefined" == typeof WeakMap) return !1; if (void 0 === Object.freeze) return !1; try { var testWeakMap = new WeakMap; var testKey = {}; Object.freeze(testKey); testWeakMap.set(testKey, "__testvalue__"); return "__testvalue__" === testWeakMap.get(testKey); } catch (err) { return !1; } }()) try { this.weakmap = new WeakMap; } catch (err) {} this.keys = []; this.values = []; } var _proto = CrossDomainSafeWeakMap.prototype; _proto._cleanupClosedWindows = function() { var weakmap = this.weakmap; var keys = this.keys; for (var i = 0; i < keys.length; i++) { var value = keys[i]; if (isWindow(value) && isWindowClosed(value)) { if (weakmap) try { weakmap.delete(value); } catch (err) {} keys.splice(i, 1); this.values.splice(i, 1); i -= 1; } } }; _proto.isSafeToReadWrite = function(key) { return !isWindow(key); }; _proto.set = function(key, value) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.set(key, value); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var name = this.name; var entry = key[name]; entry && entry[0] === key ? entry[1] = value : Object.defineProperty(key, name, { value: [ key, value ], writable: !0 }); return; } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var values = this.values; var index = util_safeIndexOf(keys, key); if (-1 === index) { keys.push(key); values.push(value); } else values[index] = value; }; _proto.get = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return weakmap.get(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return entry && entry[0] === key ? entry[1] : void 0; } catch (err) {} this._cleanupClosedWindows(); var index = util_safeIndexOf(this.keys, key); if (-1 !== index) return this.values[index]; }; _proto.delete = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { weakmap.delete(key); } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; entry && entry[0] === key && (entry[0] = entry[1] = void 0); } catch (err) {} this._cleanupClosedWindows(); var keys = this.keys; var index = util_safeIndexOf(keys, key); if (-1 !== index) { keys.splice(index, 1); this.values.splice(index, 1); } }; _proto.has = function(key) { if (!key) throw new Error("WeakMap expected key"); var weakmap = this.weakmap; if (weakmap) try { if (weakmap.has(key)) return !0; } catch (err) { delete this.weakmap; } if (this.isSafeToReadWrite(key)) try { var entry = key[this.name]; return !(!entry || entry[0] !== key); } catch (err) {} this._cleanupClosedWindows(); return -1 !== util_safeIndexOf(this.keys, key); }; _proto.getOrSet = function(key, getter) { if (this.has(key)) return this.get(key); var value = getter(); this.set(key, value); return value; }; return CrossDomainSafeWeakMap; }(); function _getPrototypeOf(o) { return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) { return o.__proto__ || Object.getPrototypeOf(o); })(o); } function _isNativeReflectConstruct() { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { Date.prototype.toString.call(Reflect.construct(Date, [], (function() {}))); return !0; } catch (e) { return !1; } } function construct_construct(Parent, args, Class) { return (construct_construct = _isNativeReflectConstruct() ? Reflect.construct : function(Parent, args, Class) { var a = [ null ]; a.push.apply(a, args); var instance = new (Function.bind.apply(Parent, a)); Class && _setPrototypeOf(instance, Class.prototype); return instance; }).apply(null, arguments); } function wrapNativeSuper_wrapNativeSuper(Class) { var _cache = "function" == typeof Map ? new Map : void 0; return (wrapNativeSuper_wrapNativeSuper = function(Class) { if (null === Class || !(fn = Class, -1 !== Function.toString.call(fn).indexOf("[native code]"))) return Class; var fn; if ("function" != typeof Class) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== _cache) { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return construct_construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }); return _setPrototypeOf(Wrapper, Class); })(Class); } function isElement(element) { var passed = !1; try { (element instanceof window.Element || null !== element && "object" == typeof element && 1 === element.nodeType && "object" == typeof element.style && "object" == typeof element.ownerDocument) && (passed = !0); } catch (_) {} return passed; } function getFunctionName(fn) { return fn.name || fn.__name__ || fn.displayName || "anonymous"; } function setFunctionName(fn, name) { try { delete fn.name; fn.name = name; } catch (err) {} fn.__name__ = fn.displayName = name; return fn; } function base64encode(str) { if ("function" == typeof btoa) return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (function(m, p1) { return String.fromCharCode(parseInt(p1, 16)); }))).replace(/[=]/g, ""); if ("undefined" != typeof Buffer) return Buffer.from(str, "utf8").toString("base64").replace(/[=]/g, ""); throw new Error("Can not find window.btoa or Buffer"); } function uniqueID() { var chars = "0123456789abcdef"; return "uid_" + "xxxxxxxxxx".replace(/./g, (function() { return chars.charAt(Math.floor(Math.random() * chars.length)); })) + "_" + base64encode((new Date).toISOString().slice(11, 19).replace("T", ".")).replace(/[^a-zA-Z0-9]/g, "").toLowerCase(); } var objectIDs; function serializeArgs(args) { try { return JSON.stringify([].slice.call(args), (function(subkey, val) { return "function" == typeof val ? "memoize[" + function(obj) { objectIDs = objectIDs || new weakmap_CrossDomainSafeWeakMap; if (null == obj || "object" != typeof obj && "function" != typeof obj) throw new Error("Invalid object"); var uid = objectIDs.get(obj); if (!uid) { uid = typeof obj + ":" + uniqueID(); objectIDs.set(obj, uid); } return uid; }(val) + "]" : isElement(val) ? {} : val; })); } catch (err) { throw new Error("Arguments not serializable -- can not be used to memoize"); } } function getEmptyObject() { return {}; } var memoizeGlobalIndex = 0; var memoizeGlobalIndexValidFrom = 0; function memoize(method, options) { void 0 === options && (options = {}); var _options$thisNamespac = options.thisNamespace, thisNamespace = void 0 !== _options$thisNamespac && _options$thisNamespac, cacheTime = options.time; var simpleCache; var thisCache; var memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; var memoizedFunction = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; if (memoizeIndex < memoizeGlobalIndexValidFrom) { simpleCache = null; thisCache = null; memoizeIndex = memoizeGlobalIndex; memoizeGlobalIndex += 1; } var cache; cache = thisNamespace ? (thisCache = thisCache || new weakmap_CrossDomainSafeWeakMap).getOrSet(this, getEmptyObject) : simpleCache = simpleCache || {}; var cacheKey; try { cacheKey = serializeArgs(args); } catch (_unused) { return method.apply(this, arguments); } var cacheResult = cache[cacheKey]; if (cacheResult && cacheTime && Date.now() - cacheResult.time < cacheTime) { delete cache[cacheKey]; cacheResult = null; } if (cacheResult) return cacheResult.value; var time = Date.now(); var value = method.apply(this, arguments); cache[cacheKey] = { time: time, value: value }; return value; }; memoizedFunction.reset = function() { simpleCache = null; thisCache = null; }; return setFunctionName(memoizedFunction, (options.name || getFunctionName(method)) + "::memoized"); } memoize.clear = function() { memoizeGlobalIndexValidFrom = memoizeGlobalIndex; }; function memoizePromise(method) { var cache = {}; function memoizedPromiseFunction() { var _arguments = arguments, _this = this; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; var key = serializeArgs(args); if (cache.hasOwnProperty(key)) return cache[key]; cache[key] = promise_ZalgoPromise.try((function() { return method.apply(_this, _arguments); })).finally((function() { delete cache[key]; })); return cache[key]; } memoizedPromiseFunction.reset = function() { cache = {}; }; return setFunctionName(memoizedPromiseFunction, getFunctionName(method) + "::promiseMemoized"); } function src_util_noop() {} function once(method) { var called = !1; return setFunctionName((function() { if (!called) { called = !0; return method.apply(this, arguments); } }), getFunctionName(method) + "::once"); } function stringifyError(err, level) { void 0 === level && (level = 1); if (level >= 3) return "stringifyError stack overflow"; try { if (!err) return ""; if ("string" == typeof err) return err; if (err instanceof Error) { var stack = err && err.stack; var message = err && err.message; if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + "\n" + stack; if (stack) return stack; if (message) return message; } return err && err.toString && "function" == typeof err.toString ? err.toString() : {}.toString.call(err); } catch (newErr) { return "Error while stringifying error: " + stringifyError(newErr, level + 1); } } function stringify(item) { return "string" == typeof item ? item : item && item.toString && "function" == typeof item.toString ? item.toString() : {}.toString.call(item); } function extend(obj, source) { if (!source) return obj; if (Object.assign) return Object.assign(obj, source); for (var key in source) source.hasOwnProperty(key) && (obj[key] = source[key]); return obj; } memoize((function(obj) { if (Object.values) return Object.values(obj); var result = []; for (var key in obj) obj.hasOwnProperty(key) && result.push(obj[key]); return result; })); function identity(item) { return item; } function safeInterval(method, time) { var timeout; !function loop() { timeout = setTimeout((function() { method(); loop(); }), time); }(); return { cancel: function() { clearTimeout(timeout); } }; } function arrayFrom(item) { return [].slice.call(item); } function isDefined(value) { return null != value; } function util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function util_getOrSet(obj, key, getter) { if (obj.hasOwnProperty(key)) return obj[key]; var val = getter(); obj[key] = val; return val; } function cleanup(obj) { var tasks = []; var cleaned = !1; var cleanErr; var cleaner = { set: function(name, item) { if (!cleaned) { obj[name] = item; cleaner.register((function() { delete obj[name]; })); } return item; }, register: function(method) { var task = once((function() { return method(cleanErr); })); cleaned ? method(cleanErr) : tasks.push(task); return { cancel: function() { var index = tasks.indexOf(task); -1 !== index && tasks.splice(index, 1); } }; }, all: function(err) { cleanErr = err; var results = []; cleaned = !0; for (;tasks.length; ) { var task = tasks.shift(); results.push(task()); } return promise_ZalgoPromise.all(results).then(src_util_noop); } }; return cleaner; } function assertExists(name, thing) { if (null == thing) throw new Error("Expected " + name + " to be present"); return thing; } var util_ExtendableError = function(_Error) { _inheritsLoose(ExtendableError, _Error); function ExtendableError(message) { var _this6; (_this6 = _Error.call(this, message) || this).name = _this6.constructor.name; "function" == typeof Error.captureStackTrace ? Error.captureStackTrace(function(self) { if (void 0 === self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; }(_this6), _this6.constructor) : _this6.stack = new Error(message).stack; return _this6; } return ExtendableError; }(wrapNativeSuper_wrapNativeSuper(Error)); function getBody() { var body = document.body; if (!body) throw new Error("Body element not found"); return body; } function isDocumentReady() { return Boolean(document.body) && "complete" === document.readyState; } function isDocumentInteractive() { return Boolean(document.body) && "interactive" === document.readyState; } function urlEncode(str) { return encodeURIComponent(str); } memoize((function() { return new promise_ZalgoPromise((function(resolve) { if (isDocumentReady() || isDocumentInteractive()) return resolve(); var interval = setInterval((function() { if (isDocumentReady() || isDocumentInteractive()) { clearInterval(interval); return resolve(); } }), 10); })); })); function parseQuery(queryString) { return function(method, logic, args) { void 0 === args && (args = []); var cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {}; var key = serializeArgs(args); return cache.hasOwnProperty(key) ? cache[key] : cache[key] = function() { var params = {}; if (!queryString) return params; if (-1 === queryString.indexOf("=")) return params; for (var _i2 = 0, _queryString$split2 = queryString.split("&"); _i2 < _queryString$split2.length; _i2++) { var pair = _queryString$split2[_i2]; (pair = pair.split("="))[0] && pair[1] && (params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1])); } return params; }.apply(void 0, args); }(parseQuery, 0, [ queryString ]); } function extendQuery(originalQuery, props) { void 0 === props && (props = {}); return props && Object.keys(props).length ? function(obj) { void 0 === obj && (obj = {}); return Object.keys(obj).filter((function(key) { return "string" == typeof obj[key] || "boolean" == typeof obj[key]; })).map((function(key) { var val = obj[key]; if ("string" != typeof val && "boolean" != typeof val) throw new TypeError("Invalid type for query"); return urlEncode(key) + "=" + urlEncode(val.toString()); })).join("&"); }(_extends({}, parseQuery(originalQuery), props)) : originalQuery; } function appendChild(container, child) { container.appendChild(child); } function getElementSafe(id, doc) { void 0 === doc && (doc = document); return isElement(id) ? id : "string" == typeof id ? doc.querySelector(id) : void 0; } function elementReady(id) { return new promise_ZalgoPromise((function(resolve, reject) { var name = stringify(id); var el = getElementSafe(id); if (el) return resolve(el); if (isDocumentReady()) return reject(new Error("Document is ready and element " + name + " does not exist")); var interval = setInterval((function() { if (el = getElementSafe(id)) { resolve(el); clearInterval(interval); } else if (isDocumentReady()) { clearInterval(interval); return reject(new Error("Document is ready and element " + name + " does not exist")); } }), 10); })); } var dom_PopupOpenError = function(_ExtendableError) { _inheritsLoose(PopupOpenError, _ExtendableError); function PopupOpenError() { return _ExtendableError.apply(this, arguments) || this; } return PopupOpenError; }(util_ExtendableError); var awaitFrameLoadPromises; function awaitFrameLoad(frame) { if ((awaitFrameLoadPromises = awaitFrameLoadPromises || new weakmap_CrossDomainSafeWeakMap).has(frame)) { var _promise = awaitFrameLoadPromises.get(frame); if (_promise) return _promise; } var promise = new promise_ZalgoPromise((function(resolve, reject) { frame.addEventListener("load", (function() { !function(frame) { !function() { for (var i = 0; i < iframeWindows.length; i++) { var closed = !1; try { closed = iframeWindows[i].closed; } catch (err) {} if (closed) { iframeFrames.splice(i, 1); iframeWindows.splice(i, 1); } } }(); if (frame && frame.contentWindow) try { iframeWindows.push(frame.contentWindow); iframeFrames.push(frame); } catch (err) {} }(frame); resolve(frame); })); frame.addEventListener("error", (function(err) { frame.contentWindow ? resolve(frame) : reject(err); })); })); awaitFrameLoadPromises.set(frame, promise); return promise; } function awaitFrameWindow(frame) { return awaitFrameLoad(frame).then((function(loadedFrame) { if (!loadedFrame.contentWindow) throw new Error("Could not find window in iframe"); return loadedFrame.contentWindow; })); } function dom_iframe(options, container) { void 0 === options && (options = {}); var style = options.style || {}; var frame = function(tag, options, container) { void 0 === tag && (tag = "div"); void 0 === options && (options = {}); tag = tag.toLowerCase(); var element = document.createElement(tag); options.style && extend(element.style, options.style); options.class && (element.className = options.class.join(" ")); options.id && element.setAttribute("id", options.id); if (options.attributes) for (var _i10 = 0, _Object$keys2 = Object.keys(options.attributes); _i10 < _Object$keys2.length; _i10++) { var key = _Object$keys2[_i10]; element.setAttribute(key, options.attributes[key]); } options.styleSheet && function(el, styleText, doc) { void 0 === doc && (doc = window.document); el.styleSheet ? el.styleSheet.cssText = styleText : el.appendChild(doc.createTextNode(styleText)); }(element, options.styleSheet); if (options.html) { if ("iframe" === tag) throw new Error("Iframe html can not be written unless container provided and iframe in DOM"); element.innerHTML = options.html; } return element; }("iframe", { attributes: _extends({ allowTransparency: "true" }, options.attributes || {}), style: _extends({ backgroundColor: "transparent", border: "none" }, style), html: options.html, class: options.class }); var isIE = window.navigator.userAgent.match(/MSIE|Edge/i); frame.hasAttribute("id") || frame.setAttribute("id", uniqueID()); awaitFrameLoad(frame); container && function(id, doc) { void 0 === doc && (doc = document); var element = getElementSafe(id, doc); if (element) return element; throw new Error("Can not find element: " + stringify(id)); }(container).appendChild(frame); (options.url || isIE) && frame.setAttribute("src", options.url || "about:blank"); return frame; } function addEventListener(obj, event, handler) { obj.addEventListener(event, handler); return { cancel: function() { obj.removeEventListener(event, handler); } }; } function showElement(element) { element.style.setProperty("display", ""); } function hideElement(element) { element.style.setProperty("display", "none", "important"); } function destroyElement(element) { element && element.parentNode && element.parentNode.removeChild(element); } function isElementClosed(el) { return !(el && el.parentNode && el.ownerDocument && el.ownerDocument.documentElement && el.ownerDocument.documentElement.contains(el)); } function onResize(el, handler, _temp) { var _ref2 = void 0 === _temp ? {} : _temp, _ref2$width = _ref2.width, width = void 0 === _ref2$width || _ref2$width, _ref2$height = _ref2.height, height = void 0 === _ref2$height || _ref2$height, _ref2$interval = _ref2.interval, interval = void 0 === _ref2$interval ? 100 : _ref2$interval, _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win; var currentWidth = el.offsetWidth; var currentHeight = el.offsetHeight; var canceled = !1; handler({ width: currentWidth, height: currentHeight }); var check = function() { if (!canceled && function(el) { return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length); }(el)) { var newWidth = el.offsetWidth; var newHeight = el.offsetHeight; (width && newWidth !== currentWidth || height && newHeight !== currentHeight) && handler({ width: newWidth, height: newHeight }); currentWidth = newWidth; currentHeight = newHeight; } }; var observer; var timeout; win.addEventListener("resize", check); if (void 0 !== win.ResizeObserver) { (observer = new win.ResizeObserver(check)).observe(el); timeout = safeInterval(check, 10 * interval); } else if (void 0 !== win.MutationObserver) { (observer = new win.MutationObserver(check)).observe(el, { attributes: !0, childList: !0, subtree: !0, characterData: !1 }); timeout = safeInterval(check, 10 * interval); } else timeout = safeInterval(check, interval); return { cancel: function() { canceled = !0; observer.disconnect(); window.removeEventListener("resize", check); timeout.cancel(); } }; } function isShadowElement(element) { for (;element.parentNode; ) element = element.parentNode; return "[object ShadowRoot]" === element.toString(); } var currentScript = "undefined" != typeof document ? document.currentScript : null; var getCurrentScript = memoize((function() { if (currentScript) return currentScript; if (currentScript = function() { try { var stack = function() { try { throw new Error("_"); } catch (err) { return err.stack || ""; } }(); var stackDetails = /.*at [^(]*\((.*):(.+):(.+)\)$/gi.exec(stack); var scriptLocation = stackDetails && stackDetails[1]; if (!scriptLocation) return; for (var _i22 = 0, _Array$prototype$slic2 = [].slice.call(document.getElementsByTagName("script")).reverse(); _i22 < _Array$prototype$slic2.length; _i22++) { var script = _Array$prototype$slic2[_i22]; if (script.src && script.src === scriptLocation) return script; } } catch (err) {} }()) return currentScript; throw new Error("Can not determine current script"); })); var currentUID = uniqueID(); memoize((function() { var script; try { script = getCurrentScript(); } catch (err) { return currentUID; } var uid = script.getAttribute("data-uid"); if (uid && "string" == typeof uid) return uid; if ((uid = script.getAttribute("data-uid-auto")) && "string" == typeof uid) return uid; if (script.src) { var hashedString = function(str) { var hash = ""; for (var i = 0; i < str.length; i++) { var total = str[i].charCodeAt(0) * i; str[i + 1] && (total += str[i + 1].charCodeAt(0) * (i - 1)); hash += String.fromCharCode(97 + Math.abs(total) % 26); } return hash; }(JSON.stringify({ src: script.src, dataset: script.dataset })); uid = "uid_" + hashedString.slice(hashedString.length - 30); } else uid = uniqueID(); script.setAttribute("data-uid-auto", uid); return uid; })); function isPerc(str) { return "string" == typeof str && /^[0-9]+%$/.test(str); } function toNum(val) { if ("number" == typeof val) return val; var match = val.match(/^([0-9]+)(px|%)$/); if (!match) throw new Error("Could not match css value from " + val); return parseInt(match[1], 10); } function toPx(val) { return toNum(val) + "px"; } function toCSS(val) { return "number" == typeof val ? toPx(val) : isPerc(val) ? val : toPx(val); } function normalizeDimension(dim, max) { if ("number" == typeof dim) return dim; if (isPerc(dim)) return parseInt(max * toNum(dim) / 100, 10); if ("string" == typeof (str = dim) && /^[0-9]+px$/.test(str)) return toNum(dim); var str; throw new Error("Can not normalize dimension: " + dim); } function global_getGlobal(win) { void 0 === win && (win = window); var globalKey = "__post_robot_10_0_46__"; return win !== window ? win[globalKey] : win[globalKey] = win[globalKey] || {}; } var getObj = function() { return {}; }; function globalStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return util_getOrSet(global_getGlobal(), key, (function() { var store = defStore(); return { has: function(storeKey) { return store.hasOwnProperty(storeKey); }, get: function(storeKey, defVal) { return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal; }, set: function(storeKey, val) { store[storeKey] = val; return val; }, del: function(storeKey) { delete store[storeKey]; }, getOrSet: function(storeKey, getter) { return util_getOrSet(store, storeKey, getter); }, reset: function() { store = defStore(); }, keys: function() { return Object.keys(store); } }; })); } var WildCard = function() {}; function getWildcard() { var global = global_getGlobal(); global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard; return global.WINDOW_WILDCARD; } function windowStore(key, defStore) { void 0 === key && (key = "store"); void 0 === defStore && (defStore = getObj); return globalStore("windowStore").getOrSet(key, (function() { var winStore = new weakmap_CrossDomainSafeWeakMap; var getStore = function(win) { return winStore.getOrSet(win, defStore); }; return { has: function(win) { return getStore(win).hasOwnProperty(key); }, get: function(win, defVal) { var store = getStore(win); return store.hasOwnProperty(key) ? store[key] : defVal; }, set: function(win, val) { getStore(win)[key] = val; return val; }, del: function(win) { delete getStore(win)[key]; }, getOrSet: function(win, getter) { return util_getOrSet(getStore(win), key, getter); } }; })); } function getInstanceID() { return globalStore("instance").getOrSet("instanceID", uniqueID); } function resolveHelloPromise(win, _ref) { var domain = _ref.domain; var helloPromises = windowStore("helloPromises"); var existingPromise = helloPromises.get(win); existingPromise && existingPromise.resolve({ domain: domain }); var newPromise = promise_ZalgoPromise.resolve({ domain: domain }); helloPromises.set(win, newPromise); return newPromise; } function sayHello(win, _ref4) { return (0, _ref4.send)(win, "postrobot_hello", { instanceID: getInstanceID() }, { domain: "*", timeout: -1 }).then((function(_ref5) { var origin = _ref5.origin, instanceID = _ref5.data.instanceID; resolveHelloPromise(win, { domain: origin }); return { win: win, domain: origin, instanceID: instanceID }; })); } function getWindowInstanceID(win, _ref6) { var send = _ref6.send; return windowStore("windowInstanceIDPromises").getOrSet(win, (function() { return sayHello(win, { send: send }).then((function(_ref7) { return _ref7.instanceID; })); })); } function awaitWindowHello(win, timeout, name) { void 0 === timeout && (timeout = 5e3); void 0 === name && (name = "Window"); var promise = function(win) { return windowStore("helloPromises").getOrSet(win, (function() { return new promise_ZalgoPromise; })); }(win); -1 !== timeout && (promise = promise.timeout(timeout, new Error(name + " did not load after " + timeout + "ms"))); return promise; } function markWindowKnown(win) { windowStore("knownWindows").set(win, !0); } function isSerializedType(item) { return "object" == typeof item && null !== item && "string" == typeof item.__type__; } function determineType(val) { return void 0 === val ? "undefined" : null === val ? "null" : Array.isArray(val) ? "array" : "function" == typeof val ? "function" : "object" == typeof val ? val instanceof Error ? "error" : "function" == typeof val.then ? "promise" : "[object RegExp]" === {}.toString.call(val) ? "regex" : "[object Date]" === {}.toString.call(val) ? "date" : "object" : "string" == typeof val ? "string" : "number" == typeof val ? "number" : "boolean" == typeof val ? "boolean" : void 0; } function serializeType(type, val) { return { __type__: type, __val__: val }; } var _SERIALIZER; var SERIALIZER = ((_SERIALIZER = {}).function = function() {}, _SERIALIZER.error = function(_ref) { return serializeType("error", { message: _ref.message, stack: _ref.stack, code: _ref.code, data: _ref.data }); }, _SERIALIZER.promise = function() {}, _SERIALIZER.regex = function(val) { return serializeType("regex", val.source); }, _SERIALIZER.date = function(val) { return serializeType("date", val.toJSON()); }, _SERIALIZER.array = function(val) { return val; }, _SERIALIZER.object = function(val) { return val; }, _SERIALIZER.string = function(val) { return val; }, _SERIALIZER.number = function(val) { return val; }, _SERIALIZER.boolean = function(val) { return val; }, _SERIALIZER.null = function(val) { return val; }, _SERIALIZER[void 0] = function(val) { return serializeType("undefined", val); }, _SERIALIZER); var defaultSerializers = {}; var _DESERIALIZER; var DESERIALIZER = ((_DESERIALIZER = {}).function = function() { throw new Error("Function serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.error = function(_ref2) { var stack = _ref2.stack, code = _ref2.code, data = _ref2.data; var error = new Error(_ref2.message); error.code = code; data && (error.data = data); error.stack = stack + "\n\n" + error.stack; return error; }, _DESERIALIZER.promise = function() { throw new Error("Promise serialization is not implemented; nothing to deserialize"); }, _DESERIALIZER.regex = function(val) { return new RegExp(val); }, _DESERIALIZER.date = function(val) { return new Date(val); }, _DESERIALIZER.array = function(val) { return val; }, _DESERIALIZER.object = function(val) { return val; }, _DESERIALIZER.string = function(val) { return val; }, _DESERIALIZER.number = function(val) { return val; }, _DESERIALIZER.boolean = function(val) { return val; }, _DESERIALIZER.null = function(val) { return val; }, _DESERIALIZER[void 0] = function() {}, _DESERIALIZER); var defaultDeserializers = {}; function needsBridgeForBrowser() { return !!utils_getUserAgent(window).match(/MSIE|trident|edge\/12|edge\/13/i); } function needsBridgeForWin(win) { return !isSameTopWindow(window, win); } function needsBridgeForDomain(domain, win) { if (domain) { if (getDomain() !== getDomainFromUrl(domain)) return !0; } else if (win && !isSameDomain(win)) return !0; return !1; } function needsBridge(_ref) { var win = _ref.win, domain = _ref.domain; return !(!needsBridgeForBrowser() || domain && !needsBridgeForDomain(domain, win) || win && !needsBridgeForWin(win)); } function getBridgeName(domain) { return "__postrobot_bridge___" + (domain = domain || getDomainFromUrl(domain)).replace(/[^a-zA-Z0-9]+/g, "_"); } function isBridge() { return Boolean(window.name && window.name === getBridgeName(getDomain())); } var documentBodyReady = new promise_ZalgoPromise((function(resolve) { if (window.document && window.document.body) return resolve(window.document.body); var interval = setInterval((function() { if (window.document && window.document.body) { clearInterval(interval); return resolve(window.document.body); } }), 10); })); function registerRemoteWindow(win) { windowStore("remoteWindowPromises").getOrSet(win, (function() { return new promise_ZalgoPromise; })); } function findRemoteWindow(win) { var remoteWinPromise = windowStore("remoteWindowPromises").get(win); if (!remoteWinPromise) throw new Error("Remote window promise not found"); return remoteWinPromise; } function registerRemoteSendMessage(win, domain, sendMessage) { findRemoteWindow(win).resolve((function(remoteWin, remoteDomain, message) { if (remoteWin !== win) throw new Error("Remote window does not match window"); if (!matchDomain(remoteDomain, domain)) throw new Error("Remote domain " + remoteDomain + " does not match domain " + domain); sendMessage.fireAndForget(message); })); } function rejectRemoteSendMessage(win, err) { findRemoteWindow(win).reject(err).catch(src_util_noop); } function linkWindow(_ref3) { var win = _ref3.win, name = _ref3.name, domain = _ref3.domain; var popupWindowsByName = globalStore("popupWindowsByName"); var popupWindowsByWin = windowStore("popupWindowsByWin"); for (var _i2 = 0, _popupWindowsByName$k2 = popupWindowsByName.keys(); _i2 < _popupWindowsByName$k2.length; _i2++) { var winName = _popupWindowsByName$k2[_i2]; var _details = popupWindowsByName.get(winName); _details && !isWindowClosed(_details.win) || popupWindowsByName.del(winName); } if (isWindowClosed(win)) return { win: win, name: name, domain: domain }; var details = popupWindowsByWin.getOrSet(win, (function() { return name ? popupWindowsByName.getOrSet(name, (function() { return { win: win, name: name }; })) : { win: win }; })); if (details.win && details.win !== win) throw new Error("Different window already linked for window: " + (name || "undefined")); if (name) { details.name = name; popupWindowsByName.set(name, details); } if (domain) { details.domain = domain; registerRemoteWindow(win); } popupWindowsByWin.set(win, details); return details; } function setupBridge(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; windowOpen = window.open, window.open = function(url, name, options, last) { var win = windowOpen.call(this, function(url) { if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); }(url), name, options, last); if (!win) return win; linkWindow({ win: win, name: name, domain: url ? getDomainFromUrl(url) : null }); return win; }; var windowOpen; !function(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; var popupWindowsByName = globalStore("popupWindowsByName"); on("postrobot_open_tunnel", (function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; var bridgePromise = globalStore("bridges").get(origin); if (!bridgePromise) throw new Error("Can not find bridge promise for domain " + origin); return bridgePromise.then((function(bridge) { if (source !== bridge) throw new Error("Message source does not matched registered bridge for domain " + origin); if (!data.name) throw new Error("Register window expected to be passed window name"); if (!data.sendMessage) throw new Error("Register window expected to be passed sendMessage method"); if (!popupWindowsByName.has(data.name)) throw new Error("Window with name " + data.name + " does not exist, or was not opened by this window"); var getWindowDetails = function() { return popupWindowsByName.get(data.name); }; if (!getWindowDetails().domain) throw new Error("We do not have a registered domain for window " + data.name); if (getWindowDetails().domain !== origin) throw new Error("Message origin " + origin + " does not matched registered window origin " + (getWindowDetails().domain || "unknown")); registerRemoteSendMessage(getWindowDetails().win, origin, data.sendMessage); return { sendMessage: function(message) { if (window && !window.closed && getWindowDetails()) { var domain = getWindowDetails().domain; if (domain) try { receiveMessage({ data: message, origin: domain, source: getWindowDetails().win }, { on: on, send: send }); } catch (err) { promise_ZalgoPromise.reject(err); } } } }; })); })); }({ on: on, send: send, receiveMessage: receiveMessage }); !function(_ref2) { var send = _ref2.send; global_getGlobal(window).openTunnelToParent = function(_ref3) { var name = _ref3.name, source = _ref3.source, canary = _ref3.canary, sendMessage = _ref3.sendMessage; var tunnelWindows = globalStore("tunnelWindows"); var parentWindow = utils_getParent(window); if (!parentWindow) throw new Error("No parent window found to open tunnel to"); var id = function(_ref) { var name = _ref.name, source = _ref.source, canary = _ref.canary, sendMessage = _ref.sendMessage; !function() { var tunnelWindows = globalStore("tunnelWindows"); for (var _i2 = 0, _tunnelWindows$keys2 = tunnelWindows.keys(); _i2 < _tunnelWindows$keys2.length; _i2++) { var key = _tunnelWindows$keys2[_i2]; isWindowClosed(tunnelWindows[key].source) && tunnelWindows.del(key); } }(); var id = uniqueID(); globalStore("tunnelWindows").set(id, { name: name, source: source, canary: canary, sendMessage: sendMessage }); return id; }({ name: name, source: source, canary: canary, sendMessage: sendMessage }); return send(parentWindow, "postrobot_open_tunnel", { name: name, sendMessage: function() { var tunnelWindow = tunnelWindows.get(id); if (tunnelWindow && tunnelWindow.source && !isWindowClosed(tunnelWindow.source)) { try { tunnelWindow.canary(); } catch (err) { return; } tunnelWindow.sendMessage.apply(this, arguments); } } }, { domain: "*" }); }; }({ send: send }); !function(_ref) { var on = _ref.on, send = _ref.send, receiveMessage = _ref.receiveMessage; promise_ZalgoPromise.try((function() { var opener = getOpener(window); if (opener && needsBridge({ win: opener })) { registerRemoteWindow(opener); return (win = opener, windowStore("remoteBridgeAwaiters").getOrSet(win, (function() { return promise_ZalgoPromise.try((function() { var frame = getFrameByName(win, getBridgeName(getDomain())); if (frame) return isSameDomain(frame) && global_getGlobal(assertSameDomain(frame)) ? frame : new promise_ZalgoPromise((function(resolve) { var interval; var timeout; interval = setInterval((function() { if (frame && isSameDomain(frame) && global_getGlobal(assertSameDomain(frame))) { clearInterval(interval); clearTimeout(timeout); return resolve(frame); } }), 100); timeout = setTimeout((function() { clearInterval(interval); return resolve(); }), 2e3); })); })); }))).then((function(bridge) { return bridge ? window.name ? global_getGlobal(assertSameDomain(bridge)).openTunnelToParent({ name: window.name, source: window, canary: function() {}, sendMessage: function(message) { try { window; } catch (err) { return; } if (window && !window.closed) try { receiveMessage({ data: message, origin: this.origin, source: this.source }, { on: on, send: send }); } catch (err) { promise_ZalgoPromise.reject(err); } } }).then((function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; if (source !== opener) throw new Error("Source does not match opener"); registerRemoteSendMessage(source, origin, data.sendMessage); })).catch((function(err) { rejectRemoteSendMessage(opener, err); throw err; })) : rejectRemoteSendMessage(opener, new Error("Can not register with opener: window does not have a name")) : rejectRemoteSendMessage(opener, new Error("Can not register with opener: no bridge found in opener")); })); var win; } })); }({ on: on, send: send, receiveMessage: receiveMessage }); } function cleanupProxyWindows() { var idToProxyWindow = globalStore("idToProxyWindow"); for (var _i2 = 0, _idToProxyWindow$keys2 = idToProxyWindow.keys(); _i2 < _idToProxyWindow$keys2.length; _i2++) { var id = _idToProxyWindow$keys2[_i2]; idToProxyWindow.get(id).shouldClean() && idToProxyWindow.del(id); } } function getSerializedWindow(winPromise, _ref) { var send = _ref.send, _ref$id = _ref.id, id = void 0 === _ref$id ? uniqueID() : _ref$id; var windowNamePromise = winPromise.then((function(win) { if (isSameDomain(win)) return assertSameDomain(win).name; })); var windowTypePromise = winPromise.then((function(window) { if (isWindowClosed(window)) throw new Error("Window is closed, can not determine type"); return getOpener(window) ? "popup" : "iframe"; })); windowNamePromise.catch(src_util_noop); windowTypePromise.catch(src_util_noop); var getName = function() { return winPromise.then((function(win) { if (!isWindowClosed(win)) return isSameDomain(win) ? assertSameDomain(win).name : windowNamePromise; })); }; return { id: id, getType: function() { return windowTypePromise; }, getInstanceID: memoizePromise((function() { return winPromise.then((function(win) { return getWindowInstanceID(win, { send: send }); })); })), close: function() { return winPromise.then(closeWindow); }, getName: getName, focus: function() { return winPromise.then((function(win) { win.focus(); })); }, isClosed: function() { return winPromise.then((function(win) { return isWindowClosed(win); })); }, setLocation: function(href, opts) { void 0 === opts && (opts = {}); return winPromise.then((function(win) { var domain = window.location.protocol + "//" + window.location.host; var _opts$method = opts.method, method = void 0 === _opts$method ? "get" : _opts$method, body = opts.body; if (0 === href.indexOf("/")) href = "" + domain + href; else if (!href.match(/^https?:\/\//) && 0 !== href.indexOf(domain)) throw new Error("Expected url to be http or https url, or absolute path, got " + JSON.stringify(href)); if ("post" === method) return getName().then((function(name) { if (!name) throw new Error("Can not post to window without target name"); !function(_ref3) { var url = _ref3.url, target = _ref3.target, body = _ref3.body, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? "post" : _ref3$method; var form = document.createElement("form"); form.setAttribute("target", target); form.setAttribute("method", method); form.setAttribute("action", url); form.style.display = "none"; if (body) for (var _i24 = 0, _Object$keys4 = Object.keys(body); _i24 < _Object$keys4.length; _i24++) { var _body$key; var key = _Object$keys4[_i24]; var input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", null == (_body$key = body[key]) ? void 0 : _body$key.toString()); form.appendChild(input); } getBody().appendChild(form); form.submit(); getBody().removeChild(form); }({ url: href, target: name, method: method, body: body }); })); if ("get" !== method) throw new Error("Unsupported method: " + method); if (isSameDomain(win)) try { if (win.location && "function" == typeof win.location.replace) { win.location.replace(href); return; } } catch (err) {} win.location = href; })); }, setName: function(name) { return winPromise.then((function(win) { linkWindow({ win: win, name: name }); var sameDomain = isSameDomain(win); var frame = getFrameForWindow(win); if (!sameDomain) throw new Error("Can not set name for cross-domain window: " + name); assertSameDomain(win).name = name; frame && frame.setAttribute("name", name); windowNamePromise = promise_ZalgoPromise.resolve(name); })); } }; } var window_ProxyWindow = function() { function ProxyWindow(_ref2) { var send = _ref2.send, win = _ref2.win, serializedWindow = _ref2.serializedWindow; this.id = void 0; this.isProxyWindow = !0; this.serializedWindow = void 0; this.actualWindow = void 0; this.actualWindowPromise = void 0; this.send = void 0; this.name = void 0; this.actualWindowPromise = new promise_ZalgoPromise; this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, { send: send }); globalStore("idToProxyWindow").set(this.getID(), this); win && this.setWindow(win, { send: send }); } var _proto = ProxyWindow.prototype; _proto.getID = function() { return this.serializedWindow.id; }; _proto.getType = function() { return this.serializedWindow.getType(); }; _proto.isPopup = function() { return this.getType().then((function(type) { return "popup" === type; })); }; _proto.setLocation = function(href, opts) { var _this = this; return this.serializedWindow.setLocation(href, opts).then((function() { return _this; })); }; _proto.getName = function() { return this.serializedWindow.getName(); }; _proto.setName = function(name) { var _this2 = this; return this.serializedWindow.setName(name).then((function() { return _this2; })); }; _proto.close = function() { var _this3 = this; return this.serializedWindow.close().then((function() { return _this3; })); }; _proto.focus = function() { var _this4 = this; var isPopupPromise = this.isPopup(); var getNamePromise = this.getName(); var reopenPromise = promise_ZalgoPromise.hash({ isPopup: isPopupPromise, name: getNamePromise }).then((function(_ref3) { var name = _ref3.name; _ref3.isPopup && name && window.open("", name, "noopener"); })); var focusPromise = this.serializedWindow.focus(); return promise_ZalgoPromise.all([ reopenPromise, focusPromise ]).then((function() { return _this4; })); }; _proto.isClosed = function() { return this.serializedWindow.isClosed(); }; _proto.getWindow = function() { return this.actualWindow; }; _proto.setWindow = function(win, _ref4) { var send = _ref4.send; this.actualWindow = win; this.actualWindowPromise.resolve(this.actualWindow); this.serializedWindow = getSerializedWindow(this.actualWindowPromise, { send: send, id: this.getID() }); windowStore("winToProxyWindow").set(win, this); }; _proto.awaitWindow = function() { return this.actualWindowPromise; }; _proto.matchWindow = function(win, _ref5) { var _this5 = this; var send = _ref5.send; return promise_ZalgoPromise.try((function() { return _this5.actualWindow ? win === _this5.actualWindow : promise_ZalgoPromise.hash({ proxyInstanceID: _this5.getInstanceID(), knownWindowInstanceID: getWindowInstanceID(win, { send: send }) }).then((function(_ref6) { var match = _ref6.proxyInstanceID === _ref6.knownWindowInstanceID; match && _this5.setWindow(win, { send: send }); return match; })); })); }; _proto.unwrap = function() { return this.actualWindow || this; }; _proto.getInstanceID = function() { return this.serializedWindow.getInstanceID(); }; _proto.shouldClean = function() { return Boolean(this.actualWindow && isWindowClosed(this.actualWindow)); }; _proto.serialize = function() { return this.serializedWindow; }; ProxyWindow.unwrap = function(win) { return ProxyWindow.isProxyWindow(win) ? win.unwrap() : win; }; ProxyWindow.serialize = function(win, _ref7) { var send = _ref7.send; cleanupProxyWindows(); return ProxyWindow.toProxyWindow(win, { send: send }).serialize(); }; ProxyWindow.deserialize = function(serializedWindow, _ref8) { var send = _ref8.send; cleanupProxyWindows(); return globalStore("idToProxyWindow").get(serializedWindow.id) || new ProxyWindow({ serializedWindow: serializedWindow, send: send }); }; ProxyWindow.isProxyWindow = function(obj) { return Boolean(obj && !isWindow(obj) && obj.isProxyWindow); }; ProxyWindow.toProxyWindow = function(win, _ref9) { var send = _ref9.send; cleanupProxyWindows(); if (ProxyWindow.isProxyWindow(win)) return win; var actualWindow = win; return windowStore("winToProxyWindow").get(actualWindow) || new ProxyWindow({ win: actualWindow, send: send }); }; return ProxyWindow; }(); function addMethod(id, val, name, source, domain) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); if (window_ProxyWindow.isProxyWindow(source)) proxyWindowMethods.set(id, { val: val, name: name, domain: domain, source: source }); else { proxyWindowMethods.del(id); methodStore.getOrSet(source, (function() { return {}; }))[id] = { domain: domain, name: name, val: val, source: source }; } } function lookupMethod(source, id) { var methodStore = windowStore("methodStore"); var proxyWindowMethods = globalStore("proxyWindowMethods"); return methodStore.getOrSet(source, (function() { return {}; }))[id] || proxyWindowMethods.get(id); } function function_serializeFunction(destination, domain, val, key, _ref3) { on = (_ref = { on: _ref3.on, send: _ref3.send }).on, send = _ref.send, globalStore("builtinListeners").getOrSet("functionCalls", (function() { return on("postrobot_method", { domain: "*" }, (function(_ref2) { var source = _ref2.source, origin = _ref2.origin, data = _ref2.data; var id = data.id, name = data.name; var meth = lookupMethod(source, id); if (!meth) throw new Error("Could not find method '" + name + "' with id: " + data.id + " in " + getDomain(window)); var methodSource = meth.source, domain = meth.domain, val = meth.val; return promise_ZalgoPromise.try((function() { if (!matchDomain(domain, origin)) throw new Error("Method '" + data.name + "' domain " + JSON.stringify(util_isRegex(meth.domain) ? meth.domain.source : meth.domain) + " does not match origin " + origin + " in " + getDomain(window)); if (window_ProxyWindow.isProxyWindow(methodSource)) return methodSource.matchWindow(source, { send: send }).then((function(match) { if (!match) throw new Error("Method call '" + data.name + "' failed - proxy window does not match source in " + getDomain(window)); })); })).then((function() { return val.apply({ source: source, origin: origin }, data.args); }), (function(err) { return promise_ZalgoPromise.try((function() { if (val.onError) return val.onError(err); })).then((function() { err.stack && (err.stack = "Remote call to " + name + "(" + function(args) { void 0 === args && (args = []); return arrayFrom(args).map((function(arg) { return "string" == typeof arg ? "'" + arg + "'" : void 0 === arg ? "undefined" : null === arg ? "null" : "boolean" == typeof arg ? arg.toString() : Array.isArray(arg) ? "[ ... ]" : "object" == typeof arg ? "{ ... }" : "function" == typeof arg ? "() => { ... }" : "<" + typeof arg + ">"; })).join(", "); }(data.args) + ") failed\n\n" + err.stack); throw err; })); })).then((function(result) { return { result: result, id: id, name: name }; })); })); })); var _ref, on, send; var id = val.__id__ || uniqueID(); destination = window_ProxyWindow.unwrap(destination); var name = val.__name__ || val.name || key; "string" == typeof name && "function" == typeof name.indexOf && 0 === name.indexOf("anonymous::") && (name = name.replace("anonymous::", key + "::")); if (window_ProxyWindow.isProxyWindow(destination)) { addMethod(id, val, name, destination, domain); destination.awaitWindow().then((function(win) { addMethod(id, val, name, win, domain); })); } else addMethod(id, val, name, destination, domain); return serializeType("cross_domain_function", { id: id, name: name }); } function serializeMessage(destination, domain, obj, _ref) { var _serialize; var on = _ref.on, send = _ref.send; return function(obj, serializers) { void 0 === serializers && (serializers = defaultSerializers); var result = JSON.stringify(obj, (function(key) { var val = this[key]; if (isSerializedType(this)) return val; var type = determineType(val); if (!type) return val; var serializer = serializers[type] || SERIALIZER[type]; return serializer ? serializer(val, key) : val; })); return void 0 === result ? "undefined" : result; }(obj, ((_serialize = {}).promise = function(val, key) { return function(destination, domain, val, key, _ref) { return serializeType("cross_domain_zalgo_promise", { then: function_serializeFunction(destination, domain, (function(resolve, reject) { return val.then(resolve, reject); }), key, { on: _ref.on, send: _ref.send }) }); }(destination, domain, val, key, { on: on, send: send }); }, _serialize.function = function(val, key) { return function_serializeFunction(destination, domain, val, key, { on: on, send: send }); }, _serialize.object = function(val) { return isWindow(val) || window_ProxyWindow.isProxyWindow(val) ? serializeType("cross_domain_window", window_ProxyWindow.serialize(val, { send: send })) : val; }, _serialize)); } function deserializeMessage(source, origin, message, _ref2) { var _deserialize; var send = _ref2.send; return function(str, deserializers) { void 0 === deserializers && (deserializers = defaultDeserializers); if ("undefined" !== str) return JSON.parse(str, (function(key, val) { if (isSerializedType(this)) return val; var type; var value; if (isSerializedType(val)) { type = val.__type__; value = val.__val__; } else { type = determineType(val); value = val; } if (!type) return value; var deserializer = deserializers[type] || DESERIALIZER[type]; return deserializer ? deserializer(value, key) : value; })); }(message, ((_deserialize = {}).cross_domain_zalgo_promise = function(serializedPromise) { return function(source, origin, _ref2) { return new promise_ZalgoPromise(_ref2.then); }(0, 0, serializedPromise); }, _deserialize.cross_domain_function = function(serializedFunction) { return function(source, origin, _ref4, _ref5) { var id = _ref4.id, name = _ref4.name; var send = _ref5.send; var getDeserializedFunction = function(opts) { void 0 === opts && (opts = {}); function crossDomainFunctionWrapper() { var _arguments = arguments; return window_ProxyWindow.toProxyWindow(source, { send: send }).awaitWindow().then((function(win) { var meth = lookupMethod(win, id); if (meth && meth.val !== crossDomainFunctionWrapper) return meth.val.apply({ source: window, origin: getDomain() }, _arguments); var _args = [].slice.call(_arguments); return opts.fireAndForget ? send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !0 }) : send(win, "postrobot_method", { id: id, name: name, args: _args }, { domain: origin, fireAndForget: !1 }).then((function(res) { return res.data.result; })); })).catch((function(err) { throw err; })); } crossDomainFunctionWrapper.__name__ = name; crossDomainFunctionWrapper.__origin__ = origin; crossDomainFunctionWrapper.__source__ = source; crossDomainFunctionWrapper.__id__ = id; crossDomainFunctionWrapper.origin = origin; return crossDomainFunctionWrapper; }; var crossDomainFunctionWrapper = getDeserializedFunction(); crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({ fireAndForget: !0 }); return crossDomainFunctionWrapper; }(source, origin, serializedFunction, { send: send }); }, _deserialize.cross_domain_window = function(serializedWindow) { return window_ProxyWindow.deserialize(serializedWindow, { send: send }); }, _deserialize)); } var SEND_MESSAGE_STRATEGIES = {}; SEND_MESSAGE_STRATEGIES.postrobot_post_message = function(win, serializedMessage, domain) { 0 === domain.indexOf("file:") && (domain = "*"); win.postMessage(serializedMessage, domain); }; SEND_MESSAGE_STRATEGIES.postrobot_bridge = function(win, serializedMessage, domain) { if (!needsBridgeForBrowser() && !isBridge()) throw new Error("Bridge not needed for browser"); if (isSameDomain(win)) throw new Error("Post message through bridge disabled between same domain windows"); if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use bridge to communicate between two different windows, not between frames"); !function(win, domain, message) { var messagingChild = isOpener(window, win); var messagingParent = isOpener(win, window); if (!messagingChild && !messagingParent) throw new Error("Can only send messages to and from parent and popup windows"); findRemoteWindow(win).then((function(sendMessage) { return sendMessage(win, domain, message); })); }(win, domain, serializedMessage); }; SEND_MESSAGE_STRATEGIES.postrobot_global = function(win, serializedMessage) { if (!utils_getUserAgent(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) throw new Error("Global messaging not needed for browser"); if (!isSameDomain(win)) throw new Error("Post message through global disabled between different domain windows"); if (!1 !== isSameTopWindow(window, win)) throw new Error("Can only use global to communicate between two different windows, not between frames"); var foreignGlobal = global_getGlobal(win); if (!foreignGlobal) throw new Error("Can not find postRobot global on foreign window"); foreignGlobal.receiveMessage({ source: window, origin: getDomain(), data: serializedMessage }); }; function send_sendMessage(win, domain, message, _ref2) { var on = _ref2.on, send = _ref2.send; return promise_ZalgoPromise.try((function() { var domainBuffer = windowStore().getOrSet(win, (function() { return {}; })); domainBuffer.buffer = domainBuffer.buffer || []; domainBuffer.buffer.push(message); domainBuffer.flush = domainBuffer.flush || promise_ZalgoPromise.flush().then((function() { if (isWindowClosed(win)) throw new Error("Window is closed"); var serializedMessage = serializeMessage(win, domain, ((_ref = {}).__post_robot_10_0_46__ = domainBuffer.buffer || [], _ref), { on: on, send: send }); var _ref; delete domainBuffer.buffer; var strategies = Object.keys(SEND_MESSAGE_STRATEGIES); var errors = []; for (var _i2 = 0; _i2 < strategies.length; _i2++) { var strategyName = strategies[_i2]; try { SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain); } catch (err) { errors.push(err); } } if (errors.length === strategies.length) throw new Error("All post-robot messaging strategies failed:\n\n" + errors.map((function(err, i) { return i + ". " + stringifyError(err); })).join("\n\n")); })); return domainBuffer.flush.then((function() { delete domainBuffer.flush; })); })).then(src_util_noop); } function getResponseListener(hash) { return globalStore("responseListeners").get(hash); } function deleteResponseListener(hash) { globalStore("responseListeners").del(hash); } function isResponseListenerErrored(hash) { return globalStore("erroredResponseListeners").has(hash); } function getRequestListener(_ref) { var name = _ref.name, win = _ref.win, domain = _ref.domain; var requestListeners = windowStore("requestListeners"); "*" === win && (win = null); "*" === domain && (domain = null); if (!name) throw new Error("Name required to get request listener"); for (var _i4 = 0, _ref3 = [ win, getWildcard() ]; _i4 < _ref3.length; _i4++) { var winQualifier = _ref3[_i4]; if (winQualifier) { var nameListeners = requestListeners.get(winQualifier); if (nameListeners) { var domainListeners = nameListeners[name]; if (domainListeners) { if (domain && "string" == typeof domain) { if (domainListeners[domain]) return domainListeners[domain]; if (domainListeners.__domain_regex__) for (var _i6 = 0, _domainListeners$__DO2 = domainListeners.__domain_regex__; _i6 < _domainListeners$__DO2.length; _i6++) { var _domainListeners$__DO3 = _domainListeners$__DO2[_i6], listener = _domainListeners$__DO3.listener; if (matchDomain(_domainListeners$__DO3.regex, domain)) return listener; } } if (domainListeners["*"]) return domainListeners["*"]; } } } } } function handleRequest(source, origin, message, _ref) { var on = _ref.on, send = _ref.send; var options = getRequestListener({ name: message.name, win: source, domain: origin }); var logName = "postrobot_method" === message.name && message.data && "string" == typeof message.data.name ? message.data.name + "()" : message.name; function sendResponse(ack, data, error) { return promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_response", hash: message.hash, name: message.name, ack: ack, data: data, error: error }, { on: on, send: send }); } catch (err) { throw new Error("Send response message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })); } return promise_ZalgoPromise.all([ promise_ZalgoPromise.flush().then((function() { if (!message.fireAndForget && !isWindowClosed(source)) try { return send_sendMessage(source, origin, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_ack", hash: message.hash, name: message.name }, { on: on, send: send }); } catch (err) { throw new Error("Send ack message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); } })), promise_ZalgoPromise.try((function() { if (!options) throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); return options.handler({ source: source, origin: origin, data: message.data }); })).then((function(data) { return sendResponse("success", data); }), (function(error) { return sendResponse("error", null, error); })) ]).then(src_util_noop).catch((function(err) { if (options && options.handleError) return options.handleError(err); throw err; })); } function handleAck(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); try { if (!matchDomain(options.domain, origin)) throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString()); if (source !== options.win) throw new Error("Ack source does not match registered window"); } catch (err) { options.promise.reject(err); } options.ack = !0; } } function handleResponse(source, origin, message) { if (!isResponseListenerErrored(message.hash)) { var options = getResponseListener(message.hash); if (!options) throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname); if (!matchDomain(options.domain, origin)) throw new Error("Response origin " + origin + " does not match domain " + (pattern = options.domain, Array.isArray(pattern) ? "(" + pattern.join(" | ") + ")" : isRegex(pattern) ? "RegExp(" + pattern.toString() + ")" : pattern.toString())); var pattern; if (source !== options.win) throw new Error("Response source does not match registered window"); deleteResponseListener(message.hash); "error" === message.ack ? options.promise.reject(message.error) : "success" === message.ack && options.promise.resolve({ source: source, origin: origin, data: message.data }); } } function receive_receiveMessage(event, _ref2) { var on = _ref2.on, send = _ref2.send; var receivedMessages = globalStore("receivedMessages"); try { if (!window || window.closed || !event.source) return; } catch (err) { return; } var source = event.source, origin = event.origin; var messages = function(message, source, origin, _ref) { var on = _ref.on, send = _ref.send; var parsedMessage; try { parsedMessage = deserializeMessage(source, origin, message, { on: on, send: send }); } catch (err) { return; } if (parsedMessage && "object" == typeof parsedMessage && null !== parsedMessage) { var parseMessages = parsedMessage.__post_robot_10_0_46__; if (Array.isArray(parseMessages)) return parseMessages; } }(event.data, source, origin, { on: on, send: send }); if (messages) { markWindowKnown(source); for (var _i2 = 0; _i2 < messages.length; _i2++) { var message = messages[_i2]; if (receivedMessages.has(message.id)) return; receivedMessages.set(message.id, !0); if (isWindowClosed(source) && !message.fireAndForget) return; 0 === message.origin.indexOf("file:") && (origin = "file://"); try { "postrobot_message_request" === message.type ? handleRequest(source, origin, message, { on: on, send: send }) : "postrobot_message_response" === message.type ? handleResponse(source, origin, message) : "postrobot_message_ack" === message.type && handleAck(source, origin, message); } catch (err) { setTimeout((function() { throw err; }), 0); } } } } function on_on(name, options, handler) { if (!name) throw new Error("Expected name"); if ("function" == typeof (options = options || {})) { handler = options; options = {}; } if (!handler) throw new Error("Expected handler"); var requestListener = function addRequestListener(_ref4, listener) { var name = _ref4.name, winCandidate = _ref4.win, domain = _ref4.domain; var requestListeners = windowStore("requestListeners"); if (!name || "string" != typeof name) throw new Error("Name required to add request listener"); if (winCandidate && "*" !== winCandidate && window_ProxyWindow.isProxyWindow(winCandidate)) { var requestListenerPromise = winCandidate.awaitWindow().then((function(actualWin) { return addRequestListener({ name: name, win: actualWin, domain: domain }, listener); })); return { cancel: function() { requestListenerPromise.then((function(requestListener) { return requestListener.cancel(); }), src_util_noop); } }; } var win = winCandidate; if (Array.isArray(win)) { var listenersCollection = []; for (var _i8 = 0, _win2 = win; _i8 < _win2.length; _i8++) listenersCollection.push(addRequestListener({ name: name, domain: domain, win: _win2[_i8] }, listener)); return { cancel: function() { for (var _i10 = 0; _i10 < listenersCollection.length; _i10++) listenersCollection[_i10].cancel(); } }; } if (Array.isArray(domain)) { var _listenersCollection = []; for (var _i12 = 0, _domain2 = domain; _i12 < _domain2.length; _i12++) _listenersCollection.push(addRequestListener({ name: name, win: win, domain: _domain2[_i12] }, listener)); return { cancel: function() { for (var _i14 = 0; _i14 < _listenersCollection.length; _i14++) _listenersCollection[_i14].cancel(); } }; } var existingListener = getRequestListener({ name: name, win: win, domain: domain }); win && "*" !== win || (win = getWildcard()); var strDomain = (domain = domain || "*").toString(); if (existingListener) throw win && domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : win ? new Error("Request listener already exists for " + name + " for " + (win === getWildcard() ? "wildcard" : "specified") + " window") : domain ? new Error("Request listener already exists for " + name + " on domain " + domain.toString()) : new Error("Request listener already exists for " + name); var winNameListeners = requestListeners.getOrSet(win, (function() { return {}; })); var winNameDomainListeners = util_getOrSet(winNameListeners, name, (function() { return {}; })); var winNameDomainRegexListeners; var winNameDomainRegexListener; util_isRegex(domain) ? (winNameDomainRegexListeners = util_getOrSet(winNameDomainListeners, "__domain_regex__", (function() { return []; }))).push(winNameDomainRegexListener = { regex: domain, listener: listener }) : winNameDomainListeners[strDomain] = listener; return { cancel: function() { delete winNameDomainListeners[strDomain]; if (winNameDomainRegexListener) { winNameDomainRegexListeners.splice(winNameDomainRegexListeners.indexOf(winNameDomainRegexListener, 1)); winNameDomainRegexListeners.length || delete winNameDomainListeners.__domain_regex__; } Object.keys(winNameDomainListeners).length || delete winNameListeners[name]; win && !Object.keys(winNameListeners).length && requestListeners.del(win); } }; }({ name: name, win: options.window, domain: options.domain || "*" }, { handler: handler || options.handler, handleError: options.errorHandler || function(err) { throw err; } }); return { cancel: function() { requestListener.cancel(); } }; } var send_send = function send(winOrProxyWin, name, data, options) { var domainMatcher = (options = options || {}).domain || "*"; var responseTimeout = options.timeout || -1; var childTimeout = options.timeout || 5e3; var fireAndForget = options.fireAndForget || !1; return window_ProxyWindow.toProxyWindow(winOrProxyWin, { send: send }).awaitWindow().then((function(win) { return promise_ZalgoPromise.try((function() { !function(name, win, domain) { if (!name) throw new Error("Expected name"); if (domain && "string" != typeof domain && !Array.isArray(domain) && !util_isRegex(domain)) throw new TypeError("Can not send " + name + ". Expected domain " + JSON.stringify(domain) + " to be a string, array, or regex"); if (isWindowClosed(win)) throw new Error("Can not send " + name + ". Target window is closed"); }(name, win, domainMatcher); if (function(parent, child) { var actualParent = getAncestor(child); if (actualParent) return actualParent === parent; if (child === parent) return !1; if (getTop(child) === child) return !1; for (var _i15 = 0, _getFrames8 = getFrames(parent); _i15 < _getFrames8.length; _i15++) if (_getFrames8[_i15] === child) return !0; return !1; }(window, win)) return awaitWindowHello(win, childTimeout); })).then((function(_temp) { return function(win, targetDomain, actualDomain, _ref) { var send = _ref.send; return promise_ZalgoPromise.try((function() { return "string" == typeof targetDomain ? targetDomain : promise_ZalgoPromise.try((function() { return actualDomain || sayHello(win, { send: send }).then((function(_ref2) { return _ref2.domain; })); })).then((function(normalizedDomain) { if (!matchDomain(targetDomain, targetDomain)) throw new Error("Domain " + stringify(targetDomain) + " does not match " + stringify(targetDomain)); return normalizedDomain; })); })); }(win, domainMatcher, (void 0 === _temp ? {} : _temp).domain, { send: send }); })).then((function(targetDomain) { var domain = targetDomain; var logName = "postrobot_method" === name && data && "string" == typeof data.name ? data.name + "()" : name; var promise = new promise_ZalgoPromise; var hash = name + "_" + uniqueID(); if (!fireAndForget) { var responseListener = { name: name, win: win, domain: domain, promise: promise }; !function(hash, listener) { globalStore("responseListeners").set(hash, listener); }(hash, responseListener); var reqPromises = windowStore("requestPromises").getOrSet(win, (function() { return []; })); reqPromises.push(promise); promise.catch((function() { !function(hash) { globalStore("erroredResponseListeners").set(hash, !0); }(hash); deleteResponseListener(hash); })); var totalAckTimeout = function(win) { return windowStore("knownWindows").get(win, !1); }(win) ? 1e4 : 2e3; var totalResTimeout = responseTimeout; var ackTimeout = totalAckTimeout; var resTimeout = totalResTimeout; var interval = safeInterval((function() { if (isWindowClosed(win)) return promise.reject(new Error("Window closed for " + name + " before " + (responseListener.ack ? "response" : "ack"))); if (responseListener.cancelled) return promise.reject(new Error("Response listener was cancelled for " + name)); ackTimeout = Math.max(ackTimeout - 500, 0); -1 !== resTimeout && (resTimeout = Math.max(resTimeout - 500, 0)); return responseListener.ack || 0 !== ackTimeout ? 0 === resTimeout ? promise.reject(new Error("No response for postMessage " + logName + " in " + getDomain() + " in " + totalResTimeout + "ms")) : void 0 : promise.reject(new Error("No ack for postMessage " + logName + " in " + getDomain() + " in " + totalAckTimeout + "ms")); }), 500); promise.finally((function() { interval.cancel(); reqPromises.splice(reqPromises.indexOf(promise, 1)); })).catch(src_util_noop); } return send_sendMessage(win, domain, { id: uniqueID(), origin: getDomain(window), type: "postrobot_message_request", hash: hash, name: name, data: data, fireAndForget: fireAndForget }, { on: on_on, send: send }).then((function() { return fireAndForget ? promise.resolve() : promise; }), (function(err) { throw new Error("Send request message failed for " + logName + " in " + getDomain() + "\n\n" + stringifyError(err)); })); })); })); }; function setup_toProxyWindow(win) { return window_ProxyWindow.toProxyWindow(win, { send: send_send }); } function cleanUpWindow(win) { for (var _i2 = 0, _requestPromises$get2 = windowStore("requestPromises").get(win, []); _i2 < _requestPromises$get2.length; _i2++) _requestPromises$get2[_i2].reject(new Error("Window " + (isWindowClosed(win) ? "closed" : "cleaned up") + " before response")).catch(src_util_noop); } var src_bridge; src_bridge = { setupBridge: setupBridge, openBridge: function(url, domain) { var bridges = globalStore("bridges"); var bridgeFrames = globalStore("bridgeFrames"); domain = domain || getDomainFromUrl(url); return bridges.getOrSet(domain, (function() { return promise_ZalgoPromise.try((function() { if (getDomain() === domain) throw new Error("Can not open bridge on the same domain as current domain: " + domain); var name = getBridgeName(domain); if (getFrameByName(window, name)) throw new Error("Frame with name " + name + " already exists on page"); var iframe = function(name, url) { var iframe = document.createElement("iframe"); iframe.setAttribute("name", name); iframe.setAttribute("id", name); iframe.setAttribute("style", "display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;"); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("border", "0"); iframe.setAttribute("scrolling", "no"); iframe.setAttribute("allowTransparency", "true"); iframe.setAttribute("tabindex", "-1"); iframe.setAttribute("hidden", "true"); iframe.setAttribute("title", ""); iframe.setAttribute("role", "presentation"); iframe.src = url; return iframe; }(name, url); bridgeFrames.set(domain, iframe); return documentBodyReady.then((function(body) { body.appendChild(iframe); var bridge = iframe.contentWindow; return new promise_ZalgoPromise((function(resolve, reject) { iframe.addEventListener("load", resolve); iframe.addEventListener("error", reject); })).then((function() { return awaitWindowHello(bridge, 5e3, "Bridge " + url); })).then((function() { return bridge; })); })); })); })); }, linkWindow: linkWindow, linkUrl: function(win, url) { linkWindow({ win: win, domain: getDomainFromUrl(url) }); }, isBridge: isBridge, needsBridge: needsBridge, needsBridgeForBrowser: needsBridgeForBrowser, hasBridge: function(url, domain) { return globalStore("bridges").has(domain || getDomainFromUrl(url)); }, needsBridgeForWin: needsBridgeForWin, needsBridgeForDomain: needsBridgeForDomain, destroyBridges: function() { var bridges = globalStore("bridges"); var bridgeFrames = globalStore("bridgeFrames"); for (var _i4 = 0, _bridgeFrames$keys2 = bridgeFrames.keys(); _i4 < _bridgeFrames$keys2.length; _i4++) { var frame = bridgeFrames.get(_bridgeFrames$keys2[_i4]); frame && frame.parentNode && frame.parentNode.removeChild(frame); } bridgeFrames.reset(); bridges.reset(); } }; function src_util_isRegex(item) { return "[object RegExp]" === {}.toString.call(item); } function utils_getActualProtocol(win) { void 0 === win && (win = window); return win.location.protocol; } function utils_getProtocol(win) { void 0 === win && (win = window); if (win.mockDomain) { var protocol = win.mockDomain.split("//")[0]; if (protocol) return protocol; } return utils_getActualProtocol(win); } function utils_isAboutProtocol(win) { void 0 === win && (win = window); return "about:" === utils_getProtocol(win); } function src_utils_getParent(win) { void 0 === win && (win = window); if (win) try { if (win.parent && win.parent !== win) return win.parent; } catch (err) {} } function utils_getOpener(win) { void 0 === win && (win = window); if (win && !src_utils_getParent(win)) try { return win.opener; } catch (err) {} } function utils_canReadFromWindow(win) { try { return !0; } catch (err) {} return !1; } function utils_getActualDomain(win) { void 0 === win && (win = window); var location = win.location; if (!location) throw new Error("Can not read window location"); var protocol = utils_getActualProtocol(win); if (!protocol) throw new Error("Can not read window protocol"); if ("file:" === protocol) return "file://"; if ("about:" === protocol) { var parent = src_utils_getParent(win); return parent && utils_canReadFromWindow() ? utils_getActualDomain(parent) : "about://"; } var host = location.host; if (!host) throw new Error("Can not read window host"); return protocol + "//" + host; } function utils_getDomain(win) { void 0 === win && (win = window); var domain = utils_getActualDomain(win); return domain && win.mockDomain && 0 === win.mockDomain.indexOf("mock:") ? win.mockDomain : domain; } function utils_isSameDomain(win) { if (!function(win) { try { if (win === window) return !0; } catch (err) {} try { var desc = Object.getOwnPropertyDescriptor(win, "location"); if (desc && !1 === desc.enumerable) return !1; } catch (err) {} try { if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (function(win) { void 0 === win && (win = window); return "mock:" === utils_getProtocol(win); }(win) && utils_canReadFromWindow()) return !0; } catch (err) {} try { if (utils_getActualDomain(win) === utils_getActualDomain(window)) return !0; } catch (err) {} return !1; }(win)) return !1; try { if (win === window) return !0; if (utils_isAboutProtocol(win) && utils_canReadFromWindow()) return !0; if (utils_getDomain(window) === utils_getDomain(win)) return !0; } catch (err) {} return !1; } function utils_assertSameDomain(win) { if (!utils_isSameDomain(win)) throw new Error("Expected window to be same domain"); return win; } function utils_isAncestorParent(parent, child) { if (!parent || !child) return !1; var childParent = src_utils_getParent(child); return childParent ? childParent === parent : -1 !== function(win) { var result = []; try { for (;win.parent !== win; ) { result.push(win.parent); win = win.parent; } } catch (err) {} return result; }(child).indexOf(parent); } function utils_getFrames(win) { var result = []; var frames; try { frames = win.frames; } catch (err) { frames = win; } var len; try { len = frames.length; } catch (err) {} if (0 === len) return result; if (len) { for (var i = 0; i < len; i++) { var frame = void 0; try { frame = frames[i]; } catch (err) { continue; } result.push(frame); } return result; } for (var _i = 0; _i < 100; _i++) { var _frame = void 0; try { _frame = frames[_i]; } catch (err) { return result; } if (!_frame) return result; result.push(_frame); } return result; } function utils_getAllChildFrames(win) { var result = []; for (var _i3 = 0, _getFrames2 = utils_getFrames(win); _i3 < _getFrames2.length; _i3++) { var frame = _getFrames2[_i3]; result.push(frame); for (var _i5 = 0, _getAllChildFrames2 = utils_getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]); } return result; } function utils_getTop(win) { void 0 === win && (win = window); try { if (win.top) return win.top; } catch (err) {} if (src_utils_getParent(win) === win) return win; try { if (utils_isAncestorParent(window, win) && window.top) return window.top; } catch (err) {} try { if (utils_isAncestorParent(win, window) && window.top) return window.top; } catch (err) {} for (var _i7 = 0, _getAllChildFrames4 = utils_getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) { var frame = _getAllChildFrames4[_i7]; try { if (frame.top) return frame.top; } catch (err) {} if (src_utils_getParent(frame) === frame) return frame; } } function utils_getAllFramesInWindow(win) { var top = utils_getTop(win); if (!top) throw new Error("Can not determine top window"); var result = [].concat(utils_getAllChildFrames(top), [ top ]); -1 === result.indexOf(win) && (result = [].concat(result, [ win ], utils_getAllChildFrames(win))); return result; } var utils_iframeWindows = []; var utils_iframeFrames = []; function utils_isWindowClosed(win, allowMock) { void 0 === allowMock && (allowMock = !0); try { if (win === window) return !1; } catch (err) { return !0; } try { if (!win) return !0; } catch (err) { return !0; } try { if (win.closed) return !0; } catch (err) { return !err || "Call was rejected by callee.\r\n" !== err.message; } if (allowMock && utils_isSameDomain(win)) try { if (win.mockclosed) return !0; } catch (err) {} try { if (!win.parent || !win.top) return !0; } catch (err) {} var iframeIndex = function(collection, item) { for (var i = 0; i < collection.length; i++) try { if (collection[i] === item) return i; } catch (err) {} return -1; }(utils_iframeWindows, win); if (-1 !== iframeIndex) { var frame = utils_iframeFrames[iframeIndex]; if (frame && function(frame) { if (!frame.contentWindow) return !0; if (!frame.parentNode) return !0; var doc = frame.ownerDocument; if (doc && doc.documentElement && !doc.documentElement.contains(frame)) { var parent = frame; for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode; if (!parent.host || !doc.documentElement.contains(parent.host)) return !0; } return !1; }(frame)) return !0; } return !1; } function utils_getFrameByName(win, name) { var winFrames = utils_getFrames(win); for (var _i9 = 0; _i9 < winFrames.length; _i9++) { var childFrame = winFrames[_i9]; try { if (utils_isSameDomain(childFrame) && childFrame.name === name && -1 !== winFrames.indexOf(childFrame)) return childFrame; } catch (err) {} } try { if (-1 !== winFrames.indexOf(win.frames[name])) return win.frames[name]; } catch (err) {} try { if (-1 !== winFrames.indexOf(win[name])) return win[name]; } catch (err) {} } function utils_getAncestor(win) { void 0 === win && (win = window); return utils_getOpener(win = win || window) || src_utils_getParent(win) || void 0; } function utils_anyMatch(collection1, collection2) { for (var _i17 = 0; _i17 < collection1.length; _i17++) { var item1 = collection1[_i17]; for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0; } return !1; } function utils_getDistanceFromTop(win) { void 0 === win && (win = window); var distance = 0; var parent = win; for (;parent; ) (parent = src_utils_getParent(parent)) && (distance += 1); return distance; } function utils_matchDomain(pattern, origin) { if ("string" == typeof pattern) { if ("string" == typeof origin) return "*" === pattern || origin === pattern; if (src_util_isRegex(origin)) return !1; if (Array.isArray(origin)) return !1; } return src_util_isRegex(pattern) ? src_util_isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !src_util_isRegex(origin) && pattern.some((function(subpattern) { return utils_matchDomain(subpattern, origin); }))); } function utils_getDomainFromUrl(url) { return url.match(/^(https?|mock|file):\/\//) ? url.split("/").slice(0, 3).join("/") : utils_getDomain(); } function utils_onCloseWindow(win, callback, delay, maxtime) { void 0 === delay && (delay = 1e3); void 0 === maxtime && (maxtime = 1 / 0); var timeout; !function check() { if (utils_isWindowClosed(win)) { timeout && clearTimeout(timeout); return callback(); } if (maxtime <= 0) clearTimeout(timeout); else { maxtime -= delay; timeout = setTimeout(check, delay); } }(); return { cancel: function() { timeout && clearTimeout(timeout); } }; } function utils_isWindow(obj) { try { if (obj === window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if ("[object Window]" === {}.toString.call(obj)) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (window.Window && obj instanceof window.Window) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.self === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.parent === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && obj.top === obj) return !0; } catch (err) { if (err && "Call was rejected by callee.\r\n" === err.message) return !0; } try { if (obj && "__unlikely_value__" === obj.__cross_domain_utils_window_check__) return !1; } catch (err) { return !0; } try { if ("postMessage" in obj && "self" in obj && "location" in obj) return !0; } catch (err) {} return !1; } function utils_normalizeMockUrl(url) { if (!(domain = utils_getDomainFromUrl(url), 0 === domain.indexOf("mock:"))) return url; var domain; throw new Error("Mock urls not supported out of test mode"); } function lib_global_getGlobal(win) { if (!utils_isSameDomain(win)) throw new Error("Can not get global for window on different domain"); win.__zoid_9_0_87__ || (win.__zoid_9_0_87__ = {}); return win.__zoid_9_0_87__; } function tryGlobal(win, handler) { try { return handler(lib_global_getGlobal(win)); } catch (err) {} } function getProxyObject(obj) { return { get: function() { var _this = this; return promise_ZalgoPromise.try((function() { if (_this.source && _this.source !== window) throw new Error("Can not call get on proxy object from a remote window"); return obj; })); } }; } function basicSerialize(data) { return base64encode(JSON.stringify(data)); } function getUIDRefStore(win) { var global = lib_global_getGlobal(win); global.references = global.references || {}; return global.references; } function crossDomainSerialize(_ref) { var data = _ref.data, metaData = _ref.metaData, sender = _ref.sender, receiver = _ref.receiver, _ref$passByReference = _ref.passByReference, passByReference = void 0 !== _ref$passByReference && _ref$passByReference, _ref$basic = _ref.basic, basic = void 0 !== _ref$basic && _ref$basic; var proxyWin = setup_toProxyWindow(receiver.win); var serializedMessage = basic ? JSON.stringify(data) : serializeMessage(proxyWin, receiver.domain, data, { on: on_on, send: send_send }); var reference = passByReference ? function(val) { var uid = uniqueID(); getUIDRefStore(window)[uid] = val; return { type: "uid", uid: uid }; }(serializedMessage) : { type: "raw", val: serializedMessage }; return { serializedData: basicSerialize({ sender: { domain: sender.domain }, metaData: metaData, reference: reference }), cleanReference: function() { win = window, "uid" === (ref = reference).type && delete getUIDRefStore(win)[ref.uid]; var win, ref; } }; } function crossDomainDeserialize(_ref2) { var sender = _ref2.sender, _ref2$basic = _ref2.basic, basic = void 0 !== _ref2$basic && _ref2$basic; var message = function(serializedData) { return JSON.parse(function(str) { if ("function" == typeof atob) return decodeURIComponent([].map.call(atob(str), (function(c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); })).join("")); if ("undefined" != typeof Buffer) return Buffer.from(str, "base64").toString("utf8"); throw new Error("Can not find window.atob or Buffer"); }(serializedData)); }(_ref2.data); var reference = message.reference, metaData = message.metaData; var win; win = "function" == typeof sender.win ? sender.win({ metaData: metaData }) : sender.win; var domain; domain = "function" == typeof sender.domain ? sender.domain({ metaData: metaData }) : "string" == typeof sender.domain ? sender.domain : message.sender.domain; var serializedData = function(win, ref) { if ("raw" === ref.type) return ref.val; if ("uid" === ref.type) return getUIDRefStore(win)[ref.uid]; throw new Error("Unsupported ref type: " + ref.type); }(win, reference); return { data: basic ? JSON.parse(serializedData) : function(source, origin, message) { return deserializeMessage(source, origin, message, { on: on_on, send: send_send }); }(win, domain, serializedData), metaData: metaData, sender: { win: win, domain: domain }, reference: reference }; } var PROP_TYPE = { STRING: "string", OBJECT: "object", FUNCTION: "function", BOOLEAN: "boolean", NUMBER: "number", ARRAY: "array" }; var PROP_SERIALIZATION = { JSON: "json", DOTIFY: "dotify", BASE64: "base64" }; var CONTEXT = { IFRAME: "iframe", POPUP: "popup" }; var EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", DISPLAY: "zoid-display", ERROR: "zoid-error", CLOSE: "zoid-close", DESTROY: "zoid-destroy", PROPS: "zoid-props", RESIZE: "zoid-resize", FOCUS: "zoid-focus" }; function buildChildWindowName(_ref) { return "__zoid__" + _ref.name + "__" + _ref.serializedPayload + "__"; } function parseWindowName(windowName) { if (!windowName) throw new Error("No window name"); var _windowName$split = windowName.split("__"), zoidcomp = _windowName$split[1], name = _windowName$split[2], serializedInitialPayload = _windowName$split[3]; if ("zoid" !== zoidcomp) throw new Error("Window not rendered by zoid - got " + zoidcomp); if (!name) throw new Error("Expected component name"); if (!serializedInitialPayload) throw new Error("Expected serialized payload ref"); return { name: name, serializedInitialPayload: serializedInitialPayload }; } var parseInitialParentPayload = memoize((function(windowName) { var _crossDomainDeseriali = crossDomainDeserialize({ data: parseWindowName(windowName).serializedInitialPayload, sender: { win: function(_ref2) { return function(windowRef) { if ("opener" === windowRef.type) return assertExists("opener", utils_getOpener(window)); if ("parent" === windowRef.type && "number" == typeof windowRef.distance) return assertExists("parent", function(win, n) { void 0 === n && (n = 1); return function(win, n) { void 0 === n && (n = 1); var parent = win; for (var i = 0; i < n; i++) { if (!parent) return; parent = src_utils_getParent(parent); } return parent; }(win, utils_getDistanceFromTop(win) - n); }(window, windowRef.distance)); if ("global" === windowRef.type && windowRef.uid && "string" == typeof windowRef.uid) { var _ret = function() { var uid = windowRef.uid; var ancestor = utils_getAncestor(window); if (!ancestor) throw new Error("Can not find ancestor window"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) { var frame = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(frame)) { var win = tryGlobal(frame, (function(global) { return global.windows && global.windows[uid]; })); if (win) return { v: win }; } } }(); if ("object" == typeof _ret) return _ret.v; } else if ("name" === windowRef.type) { var name = windowRef.name; return assertExists("namedWindow", function(win, name) { return utils_getFrameByName(win, name) || function utils_findChildFrameByName(win, name) { var frame = utils_getFrameByName(win, name); if (frame) return frame; for (var _i11 = 0, _getFrames4 = utils_getFrames(win); _i11 < _getFrames4.length; _i11++) { var namedFrame = utils_findChildFrameByName(_getFrames4[_i11], name); if (namedFrame) return namedFrame; } }(utils_getTop(win) || win, name); }(assertExists("ancestor", utils_getAncestor(window)), name)); } throw new Error("Unable to find " + windowRef.type + " parent component window"); }(_ref2.metaData.windowRef); } } }); return { parent: _crossDomainDeseriali.sender, payload: _crossDomainDeseriali.data, reference: _crossDomainDeseriali.reference }; })); function getInitialParentPayload() { return parseInitialParentPayload(window.name); } function window_getWindowRef(targetWindow, currentWindow) { void 0 === currentWindow && (currentWindow = window); if (targetWindow === src_utils_getParent(currentWindow)) return { type: "parent", distance: utils_getDistanceFromTop(targetWindow) }; if (targetWindow === utils_getOpener(currentWindow)) return { type: "opener" }; if (utils_isSameDomain(targetWindow) && !(win = targetWindow, win === utils_getTop(win))) { var windowName = utils_assertSameDomain(targetWindow).name; if (windowName) return { type: "name", name: windowName }; } var win; } function normalizeChildProp(propsDef, props, key, value, helpers) { if (!propsDef.hasOwnProperty(key)) return value; var prop = propsDef[key]; return "function" == typeof prop.childDecorate ? prop.childDecorate({ value: value, uid: helpers.uid, tag: helpers.tag, close: helpers.close, focus: helpers.focus, onError: helpers.onError, onProps: helpers.onProps, resize: helpers.resize, getParent: helpers.getParent, getParentDomain: helpers.getParentDomain, show: helpers.show, hide: helpers.hide, export: helpers.export, getSiblings: helpers.getSiblings }) : value; } function child_focus() { return promise_ZalgoPromise.try((function() { window.focus(); })); } function child_destroy() { return promise_ZalgoPromise.try((function() { window.close(); })); } var props_defaultNoop = function() { return src_util_noop; }; var props_decorateOnce = function(_ref) { return once(_ref.value); }; function eachProp(props, propsDef, handler) { for (var _i2 = 0, _Object$keys2 = Object.keys(_extends({}, props, propsDef)); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; handler(key, propsDef[key], props[key]); } } function serializeProps(propsDef, props, method) { var params = {}; return promise_ZalgoPromise.all(function(props, propsDef, handler) { var results = []; eachProp(props, propsDef, (function(key, propDef, value) { var result = function(key, propDef, value) { return promise_ZalgoPromise.resolve().then((function() { var _METHOD$GET$METHOD$PO, _METHOD$GET$METHOD$PO2; if (null != value && propDef) { var getParam = (_METHOD$GET$METHOD$PO = {}, _METHOD$GET$METHOD$PO.get = propDef.queryParam, _METHOD$GET$METHOD$PO.post = propDef.bodyParam, _METHOD$GET$METHOD$PO)[method]; var getValue = (_METHOD$GET$METHOD$PO2 = {}, _METHOD$GET$METHOD$PO2.get = propDef.queryValue, _METHOD$GET$METHOD$PO2.post = propDef.bodyValue, _METHOD$GET$METHOD$PO2)[method]; if (getParam) return promise_ZalgoPromise.hash({ finalParam: promise_ZalgoPromise.try((function() { return "function" == typeof getParam ? getParam({ value: value }) : "string" == typeof getParam ? getParam : key; })), finalValue: promise_ZalgoPromise.try((function() { return "function" == typeof getValue && isDefined(value) ? getValue({ value: value }) : value; })) }).then((function(_ref) { var finalParam = _ref.finalParam, finalValue = _ref.finalValue; var result; if ("boolean" == typeof finalValue) result = finalValue.toString(); else if ("string" == typeof finalValue) result = finalValue.toString(); else if ("object" == typeof finalValue && null !== finalValue) { if (propDef.serialization === PROP_SERIALIZATION.JSON) result = JSON.stringify(finalValue); else if (propDef.serialization === PROP_SERIALIZATION.BASE64) result = base64encode(JSON.stringify(finalValue)); else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) { result = function dotify(obj, prefix, newobj) { void 0 === prefix && (prefix = ""); void 0 === newobj && (newobj = {}); prefix = prefix ? prefix + "." : prefix; for (var key in obj) obj.hasOwnProperty(key) && null != obj[key] && "function" != typeof obj[key] && (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every((function(val) { return "object" != typeof val; })) ? newobj["" + prefix + key + "[]"] = obj[key].join(",") : obj[key] && "object" == typeof obj[key] ? newobj = dotify(obj[key], "" + prefix + key, newobj) : newobj["" + prefix + key] = obj[key].toString()); return newobj; }(finalValue, key); for (var _i2 = 0, _Object$keys2 = Object.keys(result); _i2 < _Object$keys2.length; _i2++) { var dotkey = _Object$keys2[_i2]; params[dotkey] = result[dotkey]; } return; } } else "number" == typeof finalValue && (result = finalValue.toString()); params[finalParam] = result; })); } })); }(key, propDef, value); results.push(result); })); return results; }(props, propsDef)).then((function() { return params; })); } function parentComponent(_ref) { var uid = _ref.uid, options = _ref.options, _ref$overrides = _ref.overrides, overrides = void 0 === _ref$overrides ? {} : _ref$overrides, _ref$parentWin = _ref.parentWin, parentWin = void 0 === _ref$parentWin ? window : _ref$parentWin; var propsDef = options.propsDef, containerTemplate = options.containerTemplate, prerenderTemplate = options.prerenderTemplate, tag = options.tag, name = options.name, attributes = options.attributes, dimensions = options.dimensions, autoResize = options.autoResize, url = options.url, domainMatch = options.domain, xports = options.exports; var initPromise = new promise_ZalgoPromise; var handledErrors = []; var clean = cleanup(); var state = {}; var inputProps = {}; var internalState = { visible: !0 }; var event = overrides.event ? overrides.event : (triggered = {}, handlers = {}, emitter = { on: function(eventName, handler) { var handlerList = handlers[eventName] = handlers[eventName] || []; handlerList.push(handler); var cancelled = !1; return { cancel: function() { if (!cancelled) { cancelled = !0; handlerList.splice(handlerList.indexOf(handler), 1); } } }; }, once: function(eventName, handler) { var listener = emitter.on(eventName, (function() { listener.cancel(); handler(); })); return listener; }, trigger: function(eventName) { for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3]; var handlerList = handlers[eventName]; var promises = []; if (handlerList) { var _loop = function(_i2) { var handler = handlerList[_i2]; promises.push(promise_ZalgoPromise.try((function() { return handler.apply(void 0, args); }))); }; for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(_i2); } return promise_ZalgoPromise.all(promises).then(src_util_noop); }, triggerOnce: function(eventName) { if (triggered[eventName]) return promise_ZalgoPromise.resolve(); triggered[eventName] = !0; for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) args[_key4 - 1] = arguments[_key4]; return emitter.trigger.apply(emitter, [ eventName ].concat(args)); }, reset: function() { handlers = {}; } }); var triggered, handlers, emitter; var props = overrides.props ? overrides.props : {}; var currentProxyWin; var currentProxyContainer; var childComponent; var currentChildDomain; var currentContainer; var onErrorOverride = overrides.onError; var getProxyContainerOverride = overrides.getProxyContainer; var showOverride = overrides.show; var hideOverride = overrides.hide; var closeOverride = overrides.close; var renderContainerOverride = overrides.renderContainer; var getProxyWindowOverride = overrides.getProxyWindow; var setProxyWinOverride = overrides.setProxyWin; var openFrameOverride = overrides.openFrame; var openPrerenderFrameOverride = overrides.openPrerenderFrame; var prerenderOverride = overrides.prerender; var openOverride = overrides.open; var openPrerenderOverride = overrides.openPrerender; var watchForUnloadOverride = overrides.watchForUnload; var getInternalStateOverride = overrides.getInternalState; var setInternalStateOverride = overrides.setInternalState; var getDimensions = function() { return "function" == typeof dimensions ? dimensions({ props: props }) : dimensions; }; var resolveInitPromise = function() { return promise_ZalgoPromise.try((function() { return overrides.resolveInitPromise ? overrides.resolveInitPromise() : initPromise.resolve(); })); }; var rejectInitPromise = function(err) { return promise_ZalgoPromise.try((function() { return overrides.rejectInitPromise ? overrides.rejectInitPromise(err) : initPromise.reject(err); })); }; var getPropsForChild = function(initialChildDomain) { var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; prop && !1 === prop.sendToChild || prop && prop.sameDomain && !utils_matchDomain(initialChildDomain, utils_getDomain(window)) || (result[key] = props[key]); } return promise_ZalgoPromise.hash(result); }; var getInternalState = function() { return promise_ZalgoPromise.try((function() { return getInternalStateOverride ? getInternalStateOverride() : internalState; })); }; var setInternalState = function(newInternalState) { return promise_ZalgoPromise.try((function() { return setInternalStateOverride ? setInternalStateOverride(newInternalState) : internalState = _extends({}, internalState, newInternalState); })); }; var getProxyWindow = function() { return getProxyWindowOverride ? getProxyWindowOverride() : promise_ZalgoPromise.try((function() { var windowProp = props.window; if (windowProp) { var _proxyWin = setup_toProxyWindow(windowProp); clean.register((function() { return windowProp.close(); })); return _proxyWin; } return new window_ProxyWindow({ send: send_send }); })); }; var setProxyWin = function(proxyWin) { return setProxyWinOverride ? setProxyWinOverride(proxyWin) : promise_ZalgoPromise.try((function() { currentProxyWin = proxyWin; })); }; var show = function() { return showOverride ? showOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !0 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null }).then(src_util_noop); }; var hide = function() { return hideOverride ? hideOverride() : promise_ZalgoPromise.hash({ setState: setInternalState({ visible: !1 }), showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null }).then(src_util_noop); }; var getUrl = function() { return "function" == typeof url ? url({ props: props }) : url; }; var getAttributes = function() { return "function" == typeof attributes ? attributes({ props: props }) : attributes; }; var getInitialChildDomain = function() { return utils_getDomainFromUrl(getUrl()); }; var openFrame = function(context, _ref2) { var windowName = _ref2.windowName; return openFrameOverride ? openFrameOverride(context, { windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: windowName, title: name }, getAttributes().iframe) })); })); }; var openPrerenderFrame = function(context) { return openPrerenderFrameOverride ? openPrerenderFrameOverride(context) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({ attributes: _extends({ name: "__zoid_prerender_frame__" + name + "_" + uniqueID() + "__", title: "prerender__" + name }, getAttributes().iframe) })); })); }; var openPrerender = function(context, proxyWin, proxyPrerenderFrame) { return openPrerenderOverride ? openPrerenderOverride(context, proxyWin, proxyPrerenderFrame) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyPrerenderFrame) throw new Error("Expected proxy frame to be passed"); return proxyPrerenderFrame.get().then((function(prerenderFrame) { clean.register((function() { return destroyElement(prerenderFrame); })); return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) { return utils_assertSameDomain(prerenderFrameWindow); })).then((function(win) { return setup_toProxyWindow(win); })); })); } if (context === CONTEXT.POPUP) return proxyWin; throw new Error("No render context available for " + context); })); }; var focus = function() { return promise_ZalgoPromise.try((function() { if (currentProxyWin) return promise_ZalgoPromise.all([ event.trigger(EVENT.FOCUS), currentProxyWin.focus() ]).then(src_util_noop); })); }; var getCurrentWindowReferenceUID = function() { var global = lib_global_getGlobal(window); global.windows = global.windows || {}; global.windows[uid] = window; clean.register((function() { delete global.windows[uid]; })); return uid; }; var getWindowRef = function(target, initialChildDomain, context, proxyWin) { if (initialChildDomain === utils_getDomain(window)) return { type: "global", uid: getCurrentWindowReferenceUID() }; if (target !== window) throw new Error("Can not construct cross-domain window reference for different target window"); if (props.window) { var actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) throw new Error("Can not construct cross-domain window reference for lazy window prop"); if (utils_getAncestor(actualComponentWindow) !== window) throw new Error("Can not construct cross-domain window reference for window prop with different ancestor"); } if (context === CONTEXT.POPUP) return { type: "opener" }; if (context === CONTEXT.IFRAME) return { type: "parent", distance: utils_getDistanceFromTop(window) }; throw new Error("Can not construct window reference for child"); }; var initChild = function(childDomain, childExports) { return promise_ZalgoPromise.try((function() { currentChildDomain = childDomain; childComponent = childExports; resolveInitPromise(); clean.register((function() { return childExports.close.fireAndForget().catch(src_util_noop); })); })); }; var resize = function(_ref3) { var width = _ref3.width, height = _ref3.height; return promise_ZalgoPromise.try((function() { event.trigger(EVENT.RESIZE, { width: width, height: height }); })); }; var destroy = function(err) { return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.DESTROY); })).catch(src_util_noop).then((function() { return clean.all(err); })).then((function() { initPromise.asyncReject(err || new Error("Component destroyed")); })); }; var close = memoize((function(err) { return promise_ZalgoPromise.try((function() { if (closeOverride) { if (utils_isWindowClosed(closeOverride.__source__)) return; return closeOverride(); } return promise_ZalgoPromise.try((function() { return event.trigger(EVENT.CLOSE); })).then((function() { return destroy(err || new Error("Component closed")); })); })); })); var open = function(context, _ref4) { var proxyWin = _ref4.proxyWin, proxyFrame = _ref4.proxyFrame, windowName = _ref4.windowName; return openOverride ? openOverride(context, { proxyWin: proxyWin, proxyFrame: proxyFrame, windowName: windowName }) : promise_ZalgoPromise.try((function() { if (context === CONTEXT.IFRAME) { if (!proxyFrame) throw new Error("Expected proxy frame to be passed"); return proxyFrame.get().then((function(frame) { return awaitFrameWindow(frame).then((function(win) { clean.register((function() { return destroyElement(frame); })); clean.register((function() { return cleanUpWindow(win); })); return win; })); })); } if (context === CONTEXT.POPUP) { var _getDimensions = getDimensions(), _getDimensions$width = _getDimensions.width, width = void 0 === _getDimensions$width ? "300px" : _getDimensions$width, _getDimensions$height = _getDimensions.height, height = void 0 === _getDimensions$height ? "150px" : _getDimensions$height; width = normalizeDimension(width, window.outerWidth); height = normalizeDimension(height, window.outerWidth); var win = function(url, options) { var _options$closeOnUnloa = (options = options || {}).closeOnUnload, closeOnUnload = void 0 === _options$closeOnUnloa ? 1 : _options$closeOnUnloa, _options$name = options.name, name = void 0 === _options$name ? "" : _options$name, width = options.width, height = options.height; var top = 0; var left = 0; width && (window.outerWidth ? left = Math.round((window.outerWidth - width) / 2) + window.screenX : window.screen.width && (left = Math.round((window.screen.width - width) / 2))); height && (window.outerHeight ? top = Math.round((window.outerHeight - height) / 2) + window.screenY : window.screen.height && (top = Math.round((window.screen.height - height) / 2))); delete options.closeOnUnload; delete options.name; width && height && (options = _extends({ top: top, left: left, width: width, height: height, status: 1, toolbar: 0, menubar: 0, resizable: 1, scrollbars: 1 }, options)); var params = Object.keys(options).map((function(key) { if (null != options[key]) return key + "=" + stringify(options[key]); })).filter(Boolean).join(","); var win; try { win = window.open("", name, params); } catch (err) { throw new dom_PopupOpenError("Can not open popup window - " + (err.stack || err.message)); } if (isWindowClosed(win)) { var err; throw new dom_PopupOpenError("Can not open popup window - blocked"); } closeOnUnload && window.addEventListener("unload", (function() { return win.close(); })); return win; }(0, _extends({ name: windowName, width: width, height: height }, getAttributes().popup)); clean.register((function() { return function(win) { if (function(win) { void 0 === win && (win = window); return Boolean(src_utils_getParent(win)); }(win)) { var frame = function(win) { if (utils_isSameDomain(win)) return utils_assertSameDomain(win).frameElement; for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll("iframe"); _i21 < _document$querySelect2.length; _i21++) { var frame = _document$querySelect2[_i21]; if (frame && frame.contentWindow && frame.contentWindow === win) return frame; } }(win); if (frame && frame.parentElement) { frame.parentElement.removeChild(frame); return; } } try { win.close(); } catch (err) {} }(win); })); clean.register((function() { return cleanUpWindow(win); })); return win; } throw new Error("No render context available for " + context); })).then((function(win) { proxyWin.setWindow(win, { send: send_send }); return proxyWin.setName(windowName).then((function() { return proxyWin; })); })); }; var watchForUnload = function() { return promise_ZalgoPromise.try((function() { var unloadWindowListener = addEventListener(window, "unload", once((function() { destroy(new Error("Window navigated away")); }))); var closeParentWindowListener = utils_onCloseWindow(parentWin, destroy, 3e3); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) return watchForUnloadOverride(); })); }; var checkWindowClose = function(proxyWin) { var closed = !1; return proxyWin.isClosed().then((function(isClosed) { if (isClosed) { closed = !0; return close(new Error("Detected component window close")); } return promise_ZalgoPromise.delay(200).then((function() { return proxyWin.isClosed(); })).then((function(secondIsClosed) { if (secondIsClosed) { closed = !0; return close(new Error("Detected component window close")); } })); })).then((function() { return closed; })); }; var onError = function(err) { return onErrorOverride ? onErrorOverride(err) : promise_ZalgoPromise.try((function() { if (-1 === handledErrors.indexOf(err)) { handledErrors.push(err); initPromise.asyncReject(err); return event.trigger(EVENT.ERROR, err); } })); }; var exportsPromise = new promise_ZalgoPromise; var xport = function(actualExports) { return promise_ZalgoPromise.try((function() { exportsPromise.resolve(actualExports); })); }; initChild.onError = onError; var renderTemplate = function(renderer, _ref8) { return renderer({ uid: uid, container: _ref8.container, context: _ref8.context, doc: _ref8.doc, frame: _ref8.frame, prerenderFrame: _ref8.prerenderFrame, focus: focus, close: close, state: state, props: props, tag: tag, dimensions: getDimensions(), event: event }); }; var prerender = function(proxyPrerenderWin, _ref9) { var context = _ref9.context; return prerenderOverride ? prerenderOverride(proxyPrerenderWin, { context: context }) : promise_ZalgoPromise.try((function() { if (prerenderTemplate) { var prerenderWindow = proxyPrerenderWin.getWindow(); if (prerenderWindow && utils_isSameDomain(prerenderWindow) && function(win) { try { if (!win.location.href) return !0; if ("about:blank" === win.location.href) return !0; } catch (err) {} return !1; }(prerenderWindow)) { var doc = (prerenderWindow = utils_assertSameDomain(prerenderWindow)).document; var el = renderTemplate(prerenderTemplate, { context: context, doc: doc }); if (el) { if (el.ownerDocument !== doc) throw new Error("Expected prerender template to have been created with document from child window"); !function(win, el) { var tag = el.tagName.toLowerCase(); if ("html" !== tag) throw new Error("Expected element to be html, got " + tag); var documentElement = win.document.documentElement; for (var _i6 = 0, _arrayFrom2 = arrayFrom(documentElement.children); _i6 < _arrayFrom2.length; _i6++) documentElement.removeChild(_arrayFrom2[_i6]); for (var _i8 = 0, _arrayFrom4 = arrayFrom(el.children); _i8 < _arrayFrom4.length; _i8++) documentElement.appendChild(_arrayFrom4[_i8]); }(prerenderWindow, el); var _autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, element = void 0 === _autoResize$element ? "body" : _autoResize$element; if ((element = getElementSafe(element, doc)) && (width || height)) { var prerenderResizeListener = onResize(element, (function(_ref10) { resize({ width: width ? _ref10.width : void 0, height: height ? _ref10.height : void 0 }); }), { width: width, height: height, win: prerenderWindow }); event.on(EVENT.RENDERED, prerenderResizeListener.cancel); } } } } })); }; var renderContainer = function(proxyContainer, _ref11) { var proxyFrame = _ref11.proxyFrame, proxyPrerenderFrame = _ref11.proxyPrerenderFrame, context = _ref11.context, rerender = _ref11.rerender; return renderContainerOverride ? renderContainerOverride(proxyContainer, { proxyFrame: proxyFrame, proxyPrerenderFrame: proxyPrerenderFrame, context: context, rerender: rerender }) : promise_ZalgoPromise.hash({ container: proxyContainer.get(), frame: proxyFrame ? proxyFrame.get() : null, prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null, internalState: getInternalState() }).then((function(_ref12) { var container = _ref12.container, visible = _ref12.internalState.visible; var innerContainer = renderTemplate(containerTemplate, { context: context, container: container, frame: _ref12.frame, prerenderFrame: _ref12.prerenderFrame, doc: document }); if (innerContainer) { visible || hideElement(innerContainer); appendChild(container, innerContainer); var containerWatcher = function(element, handler) { handler = once(handler); var cancelled = !1; var mutationObservers = []; var interval; var sacrificialFrame; var sacrificialFrameWin; var cancel = function() { cancelled = !0; for (var _i18 = 0; _i18 < mutationObservers.length; _i18++) mutationObservers[_i18].disconnect(); interval && interval.cancel(); sacrificialFrameWin && sacrificialFrameWin.removeEventListener("unload", elementClosed); sacrificialFrame && destroyElement(sacrificialFrame); }; var elementClosed = function() { if (!cancelled) { handler(); cancel(); } }; if (isElementClosed(element)) { elementClosed(); return { cancel: cancel }; } if (window.MutationObserver) { var mutationElement = element.parentElement; for (;mutationElement; ) { var mutationObserver = new window.MutationObserver((function() { isElementClosed(element) && elementClosed(); })); mutationObserver.observe(mutationElement, { childList: !0 }); mutationObservers.push(mutationObserver); mutationElement = mutationElement.parentElement; } } (sacrificialFrame = document.createElement("iframe")).setAttribute("name", "__detect_close_" + uniqueID() + "__"); sacrificialFrame.style.display = "none"; awaitFrameWindow(sacrificialFrame).then((function(frameWin) { (sacrificialFrameWin = assertSameDomain(frameWin)).addEventListener("unload", elementClosed); })); element.appendChild(sacrificialFrame); interval = safeInterval((function() { isElementClosed(element) && elementClosed(); }), 1e3); return { cancel: cancel }; }(innerContainer, (function() { var removeError = new Error("Detected container element removed from DOM"); return promise_ZalgoPromise.delay(1).then((function() { if (!isElementClosed(innerContainer)) { clean.all(removeError); return rerender().then(resolveInitPromise, rejectInitPromise); } close(removeError); })); })); clean.register((function() { return containerWatcher.cancel(); })); clean.register((function() { return destroyElement(innerContainer); })); return currentProxyContainer = getProxyObject(innerContainer); } })); }; var getHelpers = function() { return { state: state, event: event, close: close, focus: focus, resize: resize, onError: onError, updateProps: updateProps, show: show, hide: hide }; }; var setProps = function(newInputProps) { void 0 === newInputProps && (newInputProps = {}); var container = currentContainer; var helpers = getHelpers(); extend(inputProps, newInputProps); !function(propsDef, existingProps, inputProps, helpers, container) { var state = helpers.state, close = helpers.close, focus = helpers.focus, event = helpers.event, onError = helpers.onError; eachProp(inputProps, propsDef, (function(key, propDef, val) { var valueDetermined = !1; var value = val; Object.defineProperty(existingProps, key, { configurable: !0, enumerable: !0, get: function() { if (valueDetermined) return value; valueDetermined = !0; return function() { if (!propDef) return value; var alias = propDef.alias; alias && !isDefined(val) && isDefined(inputProps[alias]) && (value = inputProps[alias]); propDef.value && (value = propDef.value({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); !propDef.default || isDefined(value) || isDefined(inputProps[key]) || (value = propDef.default({ props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); if (isDefined(value)) { if (propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : typeof value !== propDef.type) throw new TypeError("Prop is not of type " + propDef.type + ": " + key); } else if (!1 !== propDef.required && !isDefined(inputProps[key])) throw new Error('Expected prop "' + key + '" to be defined'); isDefined(value) && propDef.decorate && (value = propDef.decorate({ value: value, props: existingProps, state: state, close: close, focus: focus, event: event, onError: onError, container: container })); return value; }(); } }); })); eachProp(existingProps, propsDef, src_util_noop); }(propsDef, props, inputProps, helpers, container); }; var updateProps = function(newProps) { setProps(newProps); return initPromise.then((function() { var child = childComponent; var proxyWin = currentProxyWin; if (child && proxyWin && currentChildDomain) return getPropsForChild(currentChildDomain).then((function(childProps) { return child.updateProps(childProps).catch((function(err) { return checkWindowClose(proxyWin).then((function(closed) { if (!closed) throw err; })); })); })); })); }; var getProxyContainer = function(container) { return getProxyContainerOverride ? getProxyContainerOverride(container) : promise_ZalgoPromise.try((function() { return elementReady(container); })).then((function(containerElement) { isShadowElement(containerElement) && (containerElement = function insertShadowSlot(element) { var shadowHost = function(element) { var shadowRoot = function(element) { for (;element.parentNode; ) element = element.parentNode; if (isShadowElement(element)) return element; }(element); if (shadowRoot && shadowRoot.host) return shadowRoot.host; }(element); if (!shadowHost) throw new Error("Element is not in shadow dom"); var slotName = "shadow-slot-" + uniqueID(); var slot = document.createElement("slot"); slot.setAttribute("name", slotName); element.appendChild(slot); var slotProvider = document.createElement("div"); slotProvider.setAttribute("slot", slotName); shadowHost.appendChild(slotProvider); return isShadowElement(shadowHost) ? insertShadowSlot(slotProvider) : slotProvider; }(containerElement)); currentContainer = containerElement; return getProxyObject(containerElement); })); }; return { init: function() { !function() { event.on(EVENT.RENDER, (function() { return props.onRender(); })); event.on(EVENT.DISPLAY, (function() { return props.onDisplay(); })); event.on(EVENT.RENDERED, (function() { return props.onRendered(); })); event.on(EVENT.CLOSE, (function() { return props.onClose(); })); event.on(EVENT.DESTROY, (function() { return props.onDestroy(); })); event.on(EVENT.RESIZE, (function() { return props.onResize(); })); event.on(EVENT.FOCUS, (function() { return props.onFocus(); })); event.on(EVENT.PROPS, (function(newProps) { return props.onProps(newProps); })); event.on(EVENT.ERROR, (function(err) { return props && props.onError ? props.onError(err) : rejectInitPromise(err).then((function() { setTimeout((function() { throw err; }), 1); })); })); clean.register(event.reset); }(); }, render: function(_ref14) { var target = _ref14.target, container = _ref14.container, context = _ref14.context, rerender = _ref14.rerender; return promise_ZalgoPromise.try((function() { var initialChildDomain = getInitialChildDomain(); var childDomainMatch = domainMatch || getInitialChildDomain(); !function(target, childDomainMatch, container) { if (target !== window) { if (!function(win1, win2) { var top1 = utils_getTop(win1) || win1; var top2 = utils_getTop(win2) || win2; try { if (top1 && top2) return top1 === top2; } catch (err) {} var allFrames1 = utils_getAllFramesInWindow(win1); var allFrames2 = utils_getAllFramesInWindow(win2); if (utils_anyMatch(allFrames1, allFrames2)) return !0; var opener1 = utils_getOpener(top1); var opener2 = utils_getOpener(top2); return opener1 && utils_anyMatch(utils_getAllFramesInWindow(opener1), allFrames2) || opener2 && utils_anyMatch(utils_getAllFramesInWindow(opener2), allFrames1), !1; }(window, target)) throw new Error("Can only renderTo an adjacent frame"); var origin = utils_getDomain(); if (!utils_matchDomain(childDomainMatch, origin) && !utils_isSameDomain(target)) throw new Error("Can not render remotely to " + childDomainMatch.toString() + " - can only render to " + origin); if (container && "string" != typeof container) throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }"); } }(target, childDomainMatch, container); var delegatePromise = promise_ZalgoPromise.try((function() { if (target !== window) return function(context, target) { var delegateProps = {}; for (var _i4 = 0, _Object$keys4 = Object.keys(props); _i4 < _Object$keys4.length; _i4++) { var propName = _Object$keys4[_i4]; var propDef = propsDef[propName]; propDef && propDef.allowDelegate && (delegateProps[propName] = props[propName]); } var childOverridesPromise = send_send(target, "zoid_delegate_" + name, { uid: uid, overrides: { props: delegateProps, event: event, close: close, onError: onError, getInternalState: getInternalState, setInternalState: setInternalState, resolveInitPromise: resolveInitPromise, rejectInitPromise: rejectInitPromise } }).then((function(_ref13) { var parentComp = _ref13.data.parent; clean.register((function(err) { if (!utils_isWindowClosed(target)) return parentComp.destroy(err); })); return parentComp.getDelegateOverrides(); })).catch((function(err) { throw new Error("Unable to delegate rendering. Possibly the component is not loaded in the target window.\n\n" + stringifyError(err)); })); getProxyContainerOverride = function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyContainer.apply(childOverrides, args); })); }; renderContainerOverride = function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.renderContainer.apply(childOverrides, args); })); }; showOverride = function() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) args[_key3] = arguments[_key3]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.show.apply(childOverrides, args); })); }; hideOverride = function() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) args[_key4] = arguments[_key4]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.hide.apply(childOverrides, args); })); }; watchForUnloadOverride = function() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) args[_key5] = arguments[_key5]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.watchForUnload.apply(childOverrides, args); })); }; if (context === CONTEXT.IFRAME) { getProxyWindowOverride = function() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) args[_key6] = arguments[_key6]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.getProxyWindow.apply(childOverrides, args); })); }; openFrameOverride = function() { for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) args[_key7] = arguments[_key7]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openFrame.apply(childOverrides, args); })); }; openPrerenderFrameOverride = function() { for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) args[_key8] = arguments[_key8]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerenderFrame.apply(childOverrides, args); })); }; prerenderOverride = function() { for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) args[_key9] = arguments[_key9]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.prerender.apply(childOverrides, args); })); }; openOverride = function() { for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) args[_key10] = arguments[_key10]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.open.apply(childOverrides, args); })); }; openPrerenderOverride = function() { for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) args[_key11] = arguments[_key11]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.openPrerender.apply(childOverrides, args); })); }; } else context === CONTEXT.POPUP && (setProxyWinOverride = function() { for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) args[_key12] = arguments[_key12]; return childOverridesPromise.then((function(childOverrides) { return childOverrides.setProxyWin.apply(childOverrides, args); })); }); return childOverridesPromise; }(context, target); })); var windowProp = props.window; var watchForUnloadPromise = watchForUnload(); var buildBodyPromise = serializeProps(propsDef, props, "post"); var onRenderPromise = event.trigger(EVENT.RENDER); var getProxyContainerPromise = getProxyContainer(container); var getProxyWindowPromise = getProxyWindow(); var finalSetPropsPromise = getProxyContainerPromise.then((function() { return setProps(); })); var buildUrlPromise = finalSetPropsPromise.then((function() { return serializeProps(propsDef, props, "get").then((function(query) { return function(url, options) { var query = options.query || {}; var hash = options.hash || {}; var originalUrl; var originalHash; var _url$split = url.split("#"); originalHash = _url$split[1]; var _originalUrl$split = (originalUrl = _url$split[0]).split("?"); originalUrl = _originalUrl$split[0]; var queryString = extendQuery(_originalUrl$split[1], query); var hashString = extendQuery(originalHash, hash); queryString && (originalUrl = originalUrl + "?" + queryString); hashString && (originalUrl = originalUrl + "#" + hashString); return originalUrl; }(utils_normalizeMockUrl(getUrl()), { query: query }); })); })); var buildWindowNamePromise = getProxyWindowPromise.then((function(proxyWin) { return function(_temp2) { var _ref6 = void 0 === _temp2 ? {} : _temp2, proxyWin = _ref6.proxyWin, initialChildDomain = _ref6.initialChildDomain, childDomainMatch = _ref6.childDomainMatch, _ref6$target = _ref6.target, target = void 0 === _ref6$target ? window : _ref6$target, context = _ref6.context; return function(_temp) { var _ref5 = void 0 === _temp ? {} : _temp, proxyWin = _ref5.proxyWin, childDomainMatch = _ref5.childDomainMatch, context = _ref5.context; return getPropsForChild(_ref5.initialChildDomain).then((function(childProps) { return { uid: uid, context: context, tag: tag, childDomainMatch: childDomainMatch, version: "9_0_87", props: childProps, exports: (win = proxyWin, { init: function(childExports) { return initChild(this.origin, childExports); }, close: close, checkClose: function() { return checkWindowClose(win); }, resize: resize, onError: onError, show: show, hide: hide, export: xport }) }; var win; })); }({ proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, context: context }).then((function(childPayload) { var _crossDomainSerialize = crossDomainSerialize({ data: childPayload, metaData: { windowRef: getWindowRef(target, initialChildDomain, context, proxyWin) }, sender: { domain: utils_getDomain(window) }, receiver: { win: proxyWin, domain: childDomainMatch }, passByReference: initialChildDomain === utils_getDomain() }), serializedData = _crossDomainSerialize.serializedData; clean.register(_crossDomainSerialize.cleanReference); return serializedData; })); }({ proxyWin: (_ref7 = { proxyWin: proxyWin, initialChildDomain: initialChildDomain, childDomainMatch: childDomainMatch, target: target, context: context }).proxyWin, initialChildDomain: _ref7.initialChildDomain, childDomainMatch: _ref7.childDomainMatch, target: _ref7.target, context: _ref7.context }).then((function(serializedPayload) { return buildChildWindowName({ name: name, serializedPayload: serializedPayload }); })); var _ref7; })); var openFramePromise = buildWindowNamePromise.then((function(windowName) { return openFrame(context, { windowName: windowName }); })); var openPrerenderFramePromise = openPrerenderFrame(context); var renderContainerPromise = promise_ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref15) { return renderContainer(_ref15.proxyContainer, { context: context, proxyFrame: _ref15.proxyFrame, proxyPrerenderFrame: _ref15.proxyPrerenderFrame, rerender: rerender }); })).then((function(proxyContainer) { return proxyContainer; })); var openPromise = promise_ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise }).then((function(_ref16) { var proxyWin = _ref16.proxyWin; return windowProp ? proxyWin : open(context, { windowName: _ref16.windowName, proxyWin: proxyWin, proxyFrame: _ref16.proxyFrame }); })); var openPrerenderPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise }).then((function(_ref17) { return openPrerender(context, _ref17.proxyWin, _ref17.proxyPrerenderFrame); })); var setStatePromise = openPromise.then((function(proxyWin) { currentProxyWin = proxyWin; return setProxyWin(proxyWin); })); var prerenderPromise = promise_ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise }).then((function(_ref18) { return prerender(_ref18.proxyPrerenderWin, { context: context }); })); var setWindowNamePromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise }).then((function(_ref19) { if (windowProp) return _ref19.proxyWin.setName(_ref19.windowName); })); var getMethodPromise = promise_ZalgoPromise.hash({ body: buildBodyPromise }).then((function(_ref20) { return options.method ? options.method : Object.keys(_ref20.body).length ? "post" : "get"; })); var loadUrlPromise = promise_ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise }).then((function(_ref21) { return _ref21.proxyWin.setLocation(_ref21.windowUrl, { method: _ref21.method, body: _ref21.body }); })); var watchForClosePromise = openPromise.then((function(proxyWin) { !function watchForClose(proxyWin, context) { var cancelled = !1; clean.register((function() { cancelled = !0; })); return promise_ZalgoPromise.delay(2e3).then((function() { return proxyWin.isClosed(); })).then((function(isClosed) { if (!cancelled) return isClosed ? close(new Error("Detected " + context + " close")) : watchForClose(proxyWin, context); })); }(proxyWin, context); })); var onDisplayPromise = promise_ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise }).then((function() { return event.trigger(EVENT.DISPLAY); })); var openBridgePromise = openPromise.then((function(proxyWin) { return function(proxyWin, initialChildDomain, context) { return promise_ZalgoPromise.try((function() { return proxyWin.awaitWindow(); })).then((function(win) { if (src_bridge && src_bridge.needsBridge({ win: win, domain: initialChildDomain }) && !src_bridge.hasBridge(initialChildDomain, initialChildDomain)) { var bridgeUrl = "function" == typeof options.bridgeUrl ? options.bridgeUrl({ props: props }) : options.bridgeUrl; if (!bridgeUrl) throw new Error("Bridge needed to render " + context); var bridgeDomain = utils_getDomainFromUrl(bridgeUrl); src_bridge.linkUrl(win, initialChildDomain); return src_bridge.openBridge(utils_normalizeMockUrl(bridgeUrl), bridgeDomain); } })); }(proxyWin, initialChildDomain, context); })); var runTimeoutPromise = loadUrlPromise.then((function() { return promise_ZalgoPromise.try((function() { var timeout = props.timeout; if (timeout) return initPromise.timeout(timeout, new Error("Loading component timed out after " + timeout + " milliseconds")); })); })); var onRenderedPromise = initPromise.then((function() { return event.trigger(EVENT.RENDERED); })); return promise_ZalgoPromise.hash({ initPromise: initPromise, buildUrlPromise: buildUrlPromise, onRenderPromise: onRenderPromise, getProxyContainerPromise: getProxyContainerPromise, openFramePromise: openFramePromise, openPrerenderFramePromise: openPrerenderFramePromise, renderContainerPromise: renderContainerPromise, openPromise: openPromise, openPrerenderPromise: openPrerenderPromise, setStatePromise: setStatePromise, prerenderPromise: prerenderPromise, loadUrlPromise: loadUrlPromise, buildWindowNamePromise: buildWindowNamePromise, setWindowNamePromise: setWindowNamePromise, watchForClosePromise: watchForClosePromise, onDisplayPromise: onDisplayPromise, openBridgePromise: openBridgePromise, runTimeoutPromise: runTimeoutPromise, onRenderedPromise: onRenderedPromise, delegatePromise: delegatePromise, watchForUnloadPromise: watchForUnloadPromise, finalSetPropsPromise: finalSetPropsPromise }); })).catch((function(err) { return promise_ZalgoPromise.all([ onError(err), destroy(err) ]).then((function() { throw err; }), (function() { throw err; })); })).then(src_util_noop); }, destroy: destroy, getProps: function() { return props; }, setProps: setProps, export: xport, getHelpers: getHelpers, getDelegateOverrides: function() { return promise_ZalgoPromise.try((function() { return { getProxyContainer: getProxyContainer, show: show, hide: hide, renderContainer: renderContainer, getProxyWindow: getProxyWindow, watchForUnload: watchForUnload, openFrame: openFrame, openPrerenderFrame: openPrerenderFrame, prerender: prerender, open: open, openPrerender: openPrerender, setProxyWin: setProxyWin }; })); }, getExports: function() { return xports({ getExports: function() { return exportsPromise; } }); } }; } function defaultContainerTemplate(_ref) { var uid = _ref.uid, frame = _ref.frame, prerenderFrame = _ref.prerenderFrame, doc = _ref.doc, props = _ref.props, event = _ref.event, dimensions = _ref.dimensions; var width = dimensions.width, height = dimensions.height; if (frame && prerenderFrame) { var div = doc.createElement("div"); div.setAttribute("id", uid); var style = doc.createElement("style"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); style.appendChild(doc.createTextNode("\n #" + uid + " {\n display: inline-block;\n position: relative;\n width: " + width + ";\n height: " + height + ";\n }\n\n #" + uid + " > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #" + uid + " > iframe.zoid-invisible {\n opacity: 0;\n }\n\n #" + uid + " > iframe.zoid-visible {\n opacity: 1;\n }\n ")); div.appendChild(frame); div.appendChild(prerenderFrame); div.appendChild(style); prerenderFrame.classList.add("zoid-visible"); frame.classList.add("zoid-invisible"); event.on(EVENT.RENDERED, (function() { prerenderFrame.classList.remove("zoid-visible"); prerenderFrame.classList.add("zoid-invisible"); frame.classList.remove("zoid-invisible"); frame.classList.add("zoid-visible"); setTimeout((function() { destroyElement(prerenderFrame); }), 1); })); event.on(EVENT.RESIZE, (function(_ref2) { var newWidth = _ref2.width, newHeight = _ref2.height; "number" == typeof newWidth && (div.style.width = toCSS(newWidth)); "number" == typeof newHeight && (div.style.height = toCSS(newHeight)); })); return div; } } function defaultPrerenderTemplate(_ref) { var doc = _ref.doc, props = _ref.props; var html = doc.createElement("html"); var body = doc.createElement("body"); var style = doc.createElement("style"); var spinner = doc.createElement("div"); spinner.classList.add("spinner"); props.cspNonce && style.setAttribute("nonce", props.cspNonce); html.appendChild(body); body.appendChild(spinner); body.appendChild(style); style.appendChild(doc.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n ")); return html; } var cleanInstances = cleanup(); var cleanZoid = cleanup(); function component(opts) { var options = function(options) { var tag = options.tag, url = options.url, domain = options.domain, bridgeUrl = options.bridgeUrl, _options$props = options.props, props = void 0 === _options$props ? {} : _options$props, _options$dimensions = options.dimensions, dimensions = void 0 === _options$dimensions ? {} : _options$dimensions, _options$autoResize = options.autoResize, autoResize = void 0 === _options$autoResize ? {} : _options$autoResize, _options$allowedParen = options.allowedParentDomains, allowedParentDomains = void 0 === _options$allowedParen ? "*" : _options$allowedParen, _options$attributes = options.attributes, attributes = void 0 === _options$attributes ? {} : _options$attributes, _options$defaultConte = options.defaultContext, defaultContext = void 0 === _options$defaultConte ? CONTEXT.IFRAME : _options$defaultConte, _options$containerTem = options.containerTemplate, containerTemplate = void 0 === _options$containerTem ? defaultContainerTemplate : _options$containerTem, _options$prerenderTem = options.prerenderTemplate, prerenderTemplate = void 0 === _options$prerenderTem ? defaultPrerenderTemplate : _options$prerenderTem, validate = options.validate, _options$eligible = options.eligible, eligible = void 0 === _options$eligible ? function() { return { eligible: !0 }; } : _options$eligible, _options$logger = options.logger, logger = void 0 === _options$logger ? { info: src_util_noop } : _options$logger, _options$exports = options.exports, xportsDefinition = void 0 === _options$exports ? src_util_noop : _options$exports, method = options.method, _options$children = options.children, children = void 0 === _options$children ? function() { return {}; } : _options$children; var name = tag.replace(/-/g, "_"); var propsDef = _extends({}, { window: { type: PROP_TYPE.OBJECT, sendToChild: !1, required: !1, allowDelegate: !0, validate: function(_ref2) { var value = _ref2.value; if (!utils_isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error("Expected Window or ProxyWindow"); if (utils_isWindow(value)) { if (utils_isWindowClosed(value)) throw new Error("Window is closed"); if (!utils_isSameDomain(value)) throw new Error("Window is not same domain"); } }, decorate: function(_ref3) { return setup_toProxyWindow(_ref3.value); } }, timeout: { type: PROP_TYPE.NUMBER, required: !1, sendToChild: !1 }, cspNonce: { type: PROP_TYPE.STRING, required: !1 }, onDisplay: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onRendered: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onRender: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, default: props_defaultNoop, decorate: props_decorateOnce }, onClose: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onDestroy: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop, decorate: props_decorateOnce }, onResize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, onFocus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, allowDelegate: !0, default: props_defaultNoop }, close: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref4) { return _ref4.close; } }, focus: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref5) { return _ref5.focus; } }, resize: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref6) { return _ref6.resize; } }, uid: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref7) { return _ref7.uid; } }, tag: { type: PROP_TYPE.STRING, required: !1, sendToChild: !1, childDecorate: function(_ref8) { return _ref8.tag; } }, getParent: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref9) { return _ref9.getParent; } }, getParentDomain: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref10) { return _ref10.getParentDomain; } }, show: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref11) { return _ref11.show; } }, hide: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref12) { return _ref12.hide; } }, export: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref13) { return _ref13.export; } }, onError: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref14) { return _ref14.onError; } }, onProps: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref15) { return _ref15.onProps; } }, getSiblings: { type: PROP_TYPE.FUNCTION, required: !1, sendToChild: !1, childDecorate: function(_ref16) { return _ref16.getSiblings; } } }, props); if (!containerTemplate) throw new Error("Container template required"); return { name: name, tag: tag, url: url, domain: domain, bridgeUrl: bridgeUrl, method: method, propsDef: propsDef, dimensions: dimensions, autoResize: autoResize, allowedParentDomains: allowedParentDomains, attributes: attributes, defaultContext: defaultContext, containerTemplate: containerTemplate, prerenderTemplate: prerenderTemplate, validate: validate, logger: logger, eligible: eligible, children: children, exports: "function" == typeof xportsDefinition ? xportsDefinition : function(_ref) { var getExports = _ref.getExports; var result = {}; var _loop = function(_i2, _Object$keys2) { var key = _Object$keys2[_i2]; var type = xportsDefinition[key].type; var valuePromise = getExports().then((function(res) { return res[key]; })); result[key] = type === PROP_TYPE.FUNCTION ? function() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key]; return valuePromise.then((function(value) { return value.apply(void 0, args); })); } : valuePromise; }; for (var _i2 = 0, _Object$keys2 = Object.keys(xportsDefinition); _i2 < _Object$keys2.length; _i2++) _loop(_i2, _Object$keys2); return result; } }; }(opts); var name = options.name, tag = options.tag, defaultContext = options.defaultContext, eligible = options.eligible, children = options.children; var global = lib_global_getGlobal(window); var instances = []; var isChild = function() { if (function(name) { try { return parseWindowName(window.name).name === name; } catch (err) {} return !1; }(name)) { var _payload = getInitialParentPayload().payload; if (_payload.tag === tag && utils_matchDomain(_payload.childDomainMatch, utils_getDomain())) return !0; } return !1; }; var registerChild = memoize((function() { if (isChild()) { if (window.xprops) { delete global.components[tag]; throw new Error("Can not register " + name + " as child - child already registered"); } var child = function(options) { var tag = options.tag, propsDef = options.propsDef, autoResize = options.autoResize, allowedParentDomains = options.allowedParentDomains; var onPropHandlers = []; var _getInitialParentPayl = getInitialParentPayload(), parent = _getInitialParentPayl.parent, payload = _getInitialParentPayl.payload; var parentComponentWindow = parent.win, parentDomain = parent.domain; var props; var exportsPromise = new promise_ZalgoPromise; var version = payload.version, uid = payload.uid, parentExports = payload.exports, context = payload.context, initialProps = payload.props; if ("9_0_87" !== version) throw new Error("Parent window has zoid version " + version + ", child window has version 9_0_87"); var show = parentExports.show, hide = parentExports.hide, close = parentExports.close, onError = parentExports.onError, checkClose = parentExports.checkClose, parentExport = parentExports.export, parentResize = parentExports.resize, parentInit = parentExports.init; var getParent = function() { return parentComponentWindow; }; var getParentDomain = function() { return parentDomain; }; var onProps = function(handler) { onPropHandlers.push(handler); return { cancel: function() { onPropHandlers.splice(onPropHandlers.indexOf(handler), 1); } }; }; var resize = function(_ref) { return parentResize.fireAndForget({ width: _ref.width, height: _ref.height }); }; var xport = function(xports) { exportsPromise.resolve(xports); return parentExport(xports); }; var getSiblings = function(_temp) { var anyParent = (void 0 === _temp ? {} : _temp).anyParent; var result = []; var currentParent = props.parent; void 0 === anyParent && (anyParent = !currentParent); if (!anyParent && !currentParent) throw new Error("No parent found for " + tag + " child"); for (var _i2 = 0, _getAllFramesInWindow2 = utils_getAllFramesInWindow(window); _i2 < _getAllFramesInWindow2.length; _i2++) { var win = _getAllFramesInWindow2[_i2]; if (utils_isSameDomain(win)) { var xprops = utils_assertSameDomain(win).xprops; if (xprops && getParent() === xprops.getParent()) { var winParent = xprops.parent; if (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) { var xports = tryGlobal(win, (function(global) { return global.exports; })); result.push({ props: xprops, exports: xports }); } } } } return result; }; var setProps = function(newProps, origin, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var normalizedProps = function(parentComponentWindow, propsDef, props, origin, helpers, isUpdate) { void 0 === isUpdate && (isUpdate = !1); var result = {}; for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) { var key = _Object$keys2[_i2]; var prop = propsDef[key]; if (!prop || !prop.sameDomain || origin === utils_getDomain(window) && utils_isSameDomain(parentComponentWindow)) { var value = normalizeChildProp(propsDef, 0, key, props[key], helpers); result[key] = value; prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value); } } if (!isUpdate) for (var _i4 = 0, _Object$keys4 = Object.keys(propsDef); _i4 < _Object$keys4.length; _i4++) { var _key = _Object$keys4[_i4]; props.hasOwnProperty(_key) || (result[_key] = normalizeChildProp(propsDef, 0, _key, void 0, helpers)); } return result; }(parentComponentWindow, propsDef, newProps, origin, { tag: tag, show: show, hide: hide, close: close, focus: child_focus, onError: onError, resize: resize, getSiblings: getSiblings, onProps: onProps, getParent: getParent, getParentDomain: getParentDomain, uid: uid, export: xport }, isUpdate); props ? extend(props, normalizedProps) : props = normalizedProps; for (var _i4 = 0; _i4 < onPropHandlers.length; _i4++) (0, onPropHandlers[_i4])(props); }; var updateProps = function(newProps) { return promise_ZalgoPromise.try((function() { return setProps(newProps, parentDomain, !0); })); }; return { init: function() { return promise_ZalgoPromise.try((function() { utils_isSameDomain(parentComponentWindow) && function(_ref3) { var componentName = _ref3.componentName, parentComponentWindow = _ref3.parentComponentWindow; var _crossDomainDeseriali2 = crossDomainDeserialize({ data: parseWindowName(window.name).serializedInitialPayload, sender: { win: parentComponentWindow }, basic: !0 }), sender = _crossDomainDeseriali2.sender; if ("uid" === _crossDomainDeseriali2.reference.type || "global" === _crossDomainDeseriali2.metaData.windowRef.type) { var _crossDomainSerialize = crossDomainSerialize({ data: _crossDomainDeseriali2.data, metaData: { windowRef: window_getWindowRef(parentComponentWindow) }, sender: { domain: sender.domain }, receiver: { win: window, domain: utils_getDomain() }, basic: !0 }); window.name = buildChildWindowName({ name: componentName, serializedPayload: _crossDomainSerialize.serializedData }); } }({ componentName: options.name, parentComponentWindow: parentComponentWindow }); lib_global_getGlobal(window).exports = options.exports({ getExports: function() { return exportsPromise; } }); !function(allowedParentDomains, domain) { if (!utils_matchDomain(allowedParentDomains, domain)) throw new Error("Can not be rendered by domain: " + domain); }(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); !function() { window.addEventListener("beforeunload", (function() { checkClose.fireAndForget(); })); window.addEventListener("unload", (function() { checkClose.fireAndForget(); })); utils_onCloseWindow(parentComponentWindow, (function() { child_destroy(); })); }(); return parentInit({ updateProps: updateProps, close: child_destroy }); })).then((function() { return (_autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, elementReady(void 0 === _autoResize$element ? "body" : _autoResize$element).catch(src_util_noop).then((function(element) { return { width: width, height: height, element: element }; }))).then((function(_ref3) { var width = _ref3.width, height = _ref3.height, element = _ref3.element; element && (width || height) && context !== CONTEXT.POPUP && onResize(element, (function(_ref4) { resize({ width: width ? _ref4.width : void 0, height: height ? _ref4.height : void 0 }); }), { width: width, height: height }); })); var _autoResize$width, width, _autoResize$height, height, _autoResize$element; })).catch((function(err) { onError(err); })); }, getProps: function() { if (props) return props; setProps(initialProps, parentDomain); return props; } }; }(options); child.init(); return child; } })); registerChild(); !function() { var allowDelegateListener = on_on("zoid_allow_delegate_" + name, (function() { return !0; })); var delegateListener = on_on("zoid_delegate_" + name, (function(_ref2) { var _ref2$data = _ref2.data; return { parent: parentComponent({ uid: _ref2$data.uid, options: options, overrides: _ref2$data.overrides, parentWin: _ref2.source }) }; })); cleanZoid.register(allowDelegateListener.cancel); cleanZoid.register(delegateListener.cancel); }(); global.components = global.components || {}; if (global.components[tag]) throw new Error("Can not register multiple components with the same tag: " + tag); global.components[tag] = !0; return { init: function init(inputProps) { var instance; var uid = "zoid-" + tag + "-" + uniqueID(); var props = inputProps || {}; var _eligible = eligible({ props: props }), eligibility = _eligible.eligible, reason = _eligible.reason; var onDestroy = props.onDestroy; props.onDestroy = function() { instance && eligibility && instances.splice(instances.indexOf(instance), 1); if (onDestroy) return onDestroy.apply(void 0, arguments); }; var parent = parentComponent({ uid: uid, options: options }); parent.init(); eligibility ? parent.setProps(props) : props.onDestroy && props.onDestroy(); cleanInstances.register((function(err) { return parent.destroy(err || new Error("zoid destroyed all components")); })); var clone = function(_temp) { var _ref4$decorate = (void 0 === _temp ? {} : _temp).decorate; return init((void 0 === _ref4$decorate ? identity : _ref4$decorate)(props)); }; var _render = function(target, container, context) { return promise_ZalgoPromise.try((function() { if (!eligibility) { var err = new Error(reason || name + " component is not eligible"); return parent.destroy(err).then((function() { throw err; })); } if (!utils_isWindow(target)) throw new Error("Must pass window to renderTo"); return function(props, context) { return promise_ZalgoPromise.try((function() { if (props.window) return setup_toProxyWindow(props.window).getType(); if (context) { if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) throw new Error("Unrecognized context: " + context); return context; } return defaultContext; })); }(props, context); })).then((function(finalContext) { container = function(context, container) { if (container) { if ("string" != typeof container && !isElement(container)) throw new TypeError("Expected string or element selector to be passed"); return container; } if (context === CONTEXT.POPUP) return "body"; throw new Error("Expected element to be passed to render iframe"); }(finalContext, container); if (target !== window && "string" != typeof container) throw new Error("Must pass string element when rendering to another window"); return parent.render({ target: target, container: container, context: finalContext, rerender: function() { var newInstance = clone(); extend(instance, newInstance); return newInstance.renderTo(target, container, context); } }); })).catch((function(err) { return parent.destroy(err).then((function() { throw err; })); })); }; instance = _extends({}, parent.getExports(), parent.getHelpers(), function() { var childComponents = children(); var result = {}; var _loop2 = function(_i4, _Object$keys4) { var childName = _Object$keys4[_i4]; var Child = childComponents[childName]; result[childName] = function(childInputProps) { var parentProps = parent.getProps(); var childProps = _extends({}, childInputProps, { parent: { uid: uid, props: parentProps, export: parent.export } }); return Child(childProps); }; }; for (var _i4 = 0, _Object$keys4 = Object.keys(childComponents); _i4 < _Object$keys4.length; _i4++) _loop2(_i4, _Object$keys4); return result; }(), { isEligible: function() { return eligibility; }, clone: clone, render: function(container, context) { return _render(window, container, context); }, renderTo: function(target, container, context) { return _render(target, container, context); } }); eligibility && instances.push(instance); return instance; }, instances: instances, driver: function(driverName, dep) { throw new Error("Driver support not enabled"); }, isChild: isChild, canRenderTo: function(win) { return send_send(win, "zoid_allow_delegate_" + name).then((function(_ref3) { return _ref3.data; })).catch((function() { return !1; })); }, registerChild: registerChild }; } var component_create = function(options) { !function() { if (!global_getGlobal().initialized) { global_getGlobal().initialized = !0; on = (_ref3 = { on: on_on, send: send_send }).on, send = _ref3.send, (global = global_getGlobal()).receiveMessage = global.receiveMessage || function(message) { return receive_receiveMessage(message, { on: on, send: send }); }; !function(_ref5) { var on = _ref5.on, send = _ref5.send; globalStore().getOrSet("postMessageListener", (function() { return addEventListener(window, "message", (function(event) { !function(event, _ref4) { var on = _ref4.on, send = _ref4.send; promise_ZalgoPromise.try((function() { var source = event.source || event.sourceElement; var origin = event.origin || event.originalEvent && event.originalEvent.origin; var data = event.data; "null" === origin && (origin = "file://"); if (source) { if (!origin) throw new Error("Post message did not have origin domain"); receive_receiveMessage({ source: source, origin: origin, data: data }, { on: on, send: send }); } })); }(event, { on: on, send: send }); })); })); }({ on: on_on, send: send_send }); setupBridge({ on: on_on, send: send_send, receiveMessage: receive_receiveMessage }); !function(_ref8) { var on = _ref8.on, send = _ref8.send; globalStore("builtinListeners").getOrSet("helloListener", (function() { var listener = on("postrobot_hello", { domain: "*" }, (function(_ref3) { resolveHelloPromise(_ref3.source, { domain: _ref3.origin }); return { instanceID: getInstanceID() }; })); var parent = getAncestor(); parent && sayHello(parent, { send: send }).catch((function(err) {})); return listener; })); }({ on: on_on, send: send_send }); } var _ref3, on, send, global; }(); var comp = component(options); var init = function(props) { return comp.init(props); }; init.driver = function(name, dep) { return comp.driver(name, dep); }; init.isChild = function() { return comp.isChild(); }; init.canRenderTo = function(win) { return comp.canRenderTo(win); }; init.instances = comp.instances; var child = comp.registerChild(); child && (window.xprops = init.xprops = child.getProps()); return init; }; function destroyComponents(err) { src_bridge && src_bridge.destroyBridges(); var destroyPromise = cleanInstances.all(err); cleanInstances = cleanup(); return destroyPromise; } var destroyAll = destroyComponents; function component_destroy(err) { destroyAll(); delete window.__zoid_9_0_87__; !function() { !function() { var responseListeners = globalStore("responseListeners"); for (var _i2 = 0, _responseListeners$ke2 = responseListeners.keys(); _i2 < _responseListeners$ke2.length; _i2++) { var hash = _responseListeners$ke2[_i2]; var listener = responseListeners.get(hash); listener && (listener.cancelled = !0); responseListeners.del(hash); } }(); (listener = globalStore().get("postMessageListener")) && listener.cancel(); var listener; delete window.__post_robot_10_0_46__; }(); return cleanZoid.all(err); } } ]); })); ================================================ FILE: docs/api/component.md ================================================ # Component ## Instantiate `(props : { [string] : any }) => ZoidComponentInstance` Instantiate a component and pass in props. ```javascript const Component = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", }); const componentInstance = Component({ foo: "bar", onSomething: () => { console.log("Something happened!"); }, }); ``` See [Component Instance](./instance.md); ## isChild `() => boolean` Returns `true` if the window you are currently in is an instance of the component, `false` if not. ```javascript const MyComponent = zoid.create({ ... }); if (MyComponent.isChild()) { console.log('We are currently in a child iframe or popup of MyComponent!') } ``` ## xprops `{ [string] : any }` Similar to `window.xprops` -- gives you access to the props passed down to the child window or iframe ```javascript const MyComponent = zoid.create({ ... }); console.log(MyComponent.xprops.message); ``` ## canRenderTo `(Window) => Promise` Returns a promise for a boolean, informing you if it is possible to remotely render the component to a different window. ```javascript const MyComponent = zoid.create({ ... }); MyComponent.canRenderTo(window.parent).then(result => { if (result) { console.log('We can render to the parent window!'); MyComponent().renderTo(window.parent, '#container'); } }); ``` ## Instances `Array` Provides an array of currently rendered instances of the zoid component ``` const MyComponent = zoid.create({ ... }); console.log(`There are currently ${ MyComponent.instances.length } active instances of MyComponent`); ``` ## driver `(frameworkName : string, dependencies : { ... }) => Driver` Register a component with your framework of choice, so it can be rendered natively in your app. ```javascript import FooFramework from 'foo-framework'; const Component = zoid.create({ ... }); const FooComponent = Component.driver('foo', { FooFramework }); // Now `FooComponent` is natively renderable inside a `FooFramework` app. ``` ### React ```javascript let MyReactZoidComponent = MyZoidComponent.driver("react", { React: React, ReactDOM: ReactDOM, }); ``` ```javascript render() { return ( ); } ``` ### Angular 1 ```javascript MyZoidComponent.driver('angular', angular);` ``` ```html ``` ### Angular 2 ```javascript @ng.core.NgModule({ imports: [ ng.platformBrowser.BrowserModule, MyZoidComponent.driver('angular2', ng.core) ] }); ``` ```html ``` ### Glimmer ```javascript import Component from "@glimmer/component"; export default MyZoidComponent.driver("glimmer", Component); ``` ```html ``` ### Vue ```javascript Vue.component('app', { components: { 'my-zoid': MyZoidComponent.driver('vue') } } ``` ```html ``` ### Vue 3 ```javascript // Create Vue application const app = Vue.createApp(...) // Define a new component called my-zoid app.component('my-zoid', MyZoidComponent.driver('vue3')) // Mount Vue application app.mount(...) ``` ```html ``` ================================================ FILE: docs/api/create.md ================================================ # Create new component ```javascript zoid.create({ ...options }); ``` Create a component definition, which will be loaded in both the parent and child windows. ## tag `string` [required] A tag-name for the component, used for: - Loading the correct component in the child window or frame - Generating framework drivers - Logging ```javascript const MyComponent = zoid.create({ tag: 'my-component-tag', ... }); ``` ## url `string | ({ props }) => string` [required] The full url that will be loaded when your component is rendered, or a function returning the url. This must include a protocol (http:, https:, or about:); it cannot be scheme-relative. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", }); url: "https://www.my-site.com/mycomponent"; ``` ```javascript const MyComponent = zoid.create({ tag: 'my-component', url: ({ props }) => { return (props.env === 'development') ? 'http://dev.my-site.com/mycomponent' : 'https://www.my-site.com/mycomponent'; }); ``` ## dimensions `{ width : string, height : string }` The dimensions for your component, in css-style units, with support for `px` or `%`. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", dimensions: { width: "300px", height: "200px", }, }); ``` ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", dimensions: { width: "80%", height: "90%", }, }); ``` ## props `{ [string] : PropDefinition }` A mapping of prop name to prop settings. Helpful for setting default values, decorating values, adding props to the query string of your component url, and more. Note: you are not required to create a prop definition for each new prop. By default, anything passed in as a prop when instantiating your component, will be automatically passed to the child window in `window.xprops`. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", props: { onLogin: { type: "function", }, prefilledEmail: { type: "string", required: false, }, }, }); ``` See [Prop Definitions](./prop-definitions.md) for all options which can be passed to prop definitions. ## containerTemplate `(opts) => HTMLElement` A function which should return a DOM element, rendered on the parent page and containing the iframe element (or rendered behind the popup window). zoid will pass `opts.frame` and `opts.prerenderFrame` to this function, which is a pre-generated element your component will be rendered into. These must be inserted somewhere into the DOM element you return, for frame-based components The `opts` parameter is [the same](#opts) as the parameter used in `prerenderTemplate` Best used with [jsx-pragmatic](https://github.com/krakenjs/jsx-pragmatic). You can use [babel](https://babeljs.io/docs/plugins/transform-react-jsx/) with a `/* @jsx node */` comment, to transpile the jsx down to regular javascript. ```javascript /* @jsx node */ import { node, dom } from "jsx-pragmatic"; var MyLoginZoidComponent = zoid.create({ tag: "my-login", url: "https://www.mysite.com/login", containerTemplate: function ({ uid, doc, frame, prerenderFrame }) { return (
).render(dom({ doc })); }, }); ``` As with React, you are also free to skip using JSX and just use `node` from `jsx-pragmatic` directly: ```javascript import { node, dom } from "jsx-pragmatic"; var MyLoginZoidComponent = zoid.create({ tag: "my-login", url: "https://www.mysite.com/login", containerTemplate: function containerTemplate({ uid, doc, frame, prerenderFrame, }) { return node( "div", { id: uid, class: "container" }, node( "style", null, ` #${uid}.container { border: 5px solid red; } ` ), node("node", { el: frame }), node("node", { el: prerenderFrame }) ).render(dom({ doc })); }, }); ``` Since `containerTemplate` requires a DOM element to be returned, you're also free to manually create the element hierarchy using built-in browser methods like `doc.createElement`: ```javascript import { node, dom } from "jsx-pragmatic"; var MyLoginZoidComponent = zoid.create({ tag: "my-login", url: "https://www.mysite.com/login", containerTemplate: function containerTemplate({ doc, uid, frame, prerenderFrame, }) { let container = doc.createElement("div"); container.id = uid; container.appendChild(frame); container.appendChild(prerenderFrame); return container; }, }); ``` If no `containerTemplate` function is defined, then a default is used. The default template can be found [here](https://github.com/krakenjs/zoid/blob/main/src/component/templates/container.js). ## prerenderTemplate `(opts) => HTMLElement` A function which should return a DOM element, rendered in place of the iframe element, or inside the popup window, as it loads. Useful if you want to display a loading spinner or pre-render some content as the component loads. Best used with [jsx-pragmatic](https://github.com/krakenjs/jsx-pragmatic). You can use [babel](https://babeljs.io/docs/plugins/transform-react-jsx/) with a `/* @jsx node */` comment, to transpile the jsx down to regular javascript. ```javascript /* @jsx node */ import { node, dom } from "jsx-pragmatic"; var MyLoginZoidComponent = zoid.create({ tag: "my-login", url: "https://www.mysite.com/login", prerenderTemplate: function ({ doc }) { return (

Please wait while the component loads...

).render( dom({ doc }) ); }, }); ``` As with React, you are also free to skip using JSX and just use `node` directly: ```javascript import { node, dom } from "jsx-pragmatic"; var MyLoginZoidComponent = zoid.create({ tag: "my-login", url: "https://www.mysite.com/login", prerenderTemplate: function containerTemplate({ doc }) { return node( "p", null, ` Please wait while the component loads... ` ).render(dom({ doc })); }, }); ``` Since `prerenderTemplate` only requires a DOM element, you're also free to manually create the element hierarchy using built-in browser methods like `doc.createElement`. **Note:** if you're using `document` method, you must use the `doc` passed to `prerenderTemplate`, so the element is created using the target document of the new iframe or popup window, **not** the document of the parent page. This is essential for browser compatibility. ```javascript import { node, dom } from "jsx-pragmatic"; var MyLoginZoidComponent = zoid.create({ tag: "my-login", url: "https://www.mysite.com/login", prerenderTemplate: function containerTemplate({ doc }) { const p = doc.createElement("p"); p.innerText = "Please wait while the component loads..."; return p; }, }); ``` ### opts Data automatically passed to `containerTemplate` and `prerenderTemplate`, used to help render and customize the template. - `uid`: Unique id automatically generated by zoid on render, unique to the instantiation of the given component - `props`: Props passed to the component in `render()` - `doc`: The appropriate document used to render dom elements - `container`: The element into which the generated element will be inserted - `dimensions`: The dimensions for the component - `tag`: Tag name of the component - `context`: Context type of the component (`iframe` or `popup`) - `frame`: Frame element that will be rendered into. Only applies to `containerTemplate` when rendering an iframe - `prerenderFrame`: Frame element that will be pre-rendered into. Only applies to `containerTemplate` when rendering an iframe using `prerenderTemplate` - `close`: Close the component. Useful if you want to render a close button outside the component - `focus`: Focus the component. Valid for popup components only. Useful if you want a clickable background overlay to re-focus the popup window. - `event`: Object that can be used to listen for the following events: `RENDER`, `RENDERED`, `DISPLAY`, `ERROR`, `CLOSED`, `PROPS`, `RESIZE` ### Listening to zoid events In the `containerTemplate` and `prerenderFunctions`, it is possible to attach functions that fire at events in the zoid lifecycle: ```javascript event.on(EVENT.RENDERED, () => { prerenderFrame.classList.remove(CLASS.VISIBLE); prerenderFrame.classList.add(CLASS.INVISIBLE); frame.classList.remove(CLASS.INVISIBLE); frame.classList.add(CLASS.VISIBLE); setTimeout(() => { destroyElement(prerenderFrame); }, 1); }); ``` ## autoResize `{ height: boolean, width: boolean, element: string }` Makes the iframe resize automatically when the child window size changes. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", autoResize: { width: false, height: true, }, }); ``` Note that by default it matches the `body` element of your content. You can override this setting by specifying a custom selector as an `element` property. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", autoResize: { width: false, height: true, element: ".my-selector", }, }); ``` Recommended to only use autoResize for height. Width has some strange effects, especially when scroll bars are present. ## allowedParentDomains `string | Array` A string, array of strings or reqular expresions to be used to validate parent domain. If parent domain doesn't match any item, communication from child to parent will be prevented. The default value is '\*' which match any domain. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", allowedParentDomains: ["http://localhost", /^http:\/\/www\.mydomain\.com$/], }); ``` ## domain `string` A string, or map of env to strings, for the domain which will be loaded in the iframe or popup. Only required if the domain which will be rendered is different to the domain specified in the `url` setting - for example, if the original url does a 302 redirect to a different domain or subdomain. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://foo.com/login", domain: "https://subdomain.foo.com", }); ``` ## defaultContext `string` Determines which should be picked by default when `render()` is called. Defaults to `iframe`. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", defaultContext: "popup", }); ``` ## validate `({ props }) => void` Function which is passed all of the props at once and may validate them. Useful for validating inter-dependant props. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", validate: function ({ props }) { if (props.name === "Batman" && props.strength < 10) { throw new Error(`Batman must have at least 10 strength`); } }, }); ``` ## eligible `({ props : { [string] : any } }) => boolean` Function which determines if the component is eligible to be rendered. ```javascript const FirefoxOnlyButton = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", eligible: () => { if (isFireFox()) { return true; } else { return false; } }, }); ``` Now anyone can check eligibility prior to rendering the component: ```javascript const myComponent = MyComponent(); if (myComponent.isEligible()) { myComponent.render("#my-container"); } ``` If the component is not eligible, calling `.render(...)` will return a rejected promise: const myComponent = MyComponent(); myComponent.render('#my-container').catch(err => { console.error(err); // This will happen if we're not in firefox }); ## exports `{ [string] : ExportDefinition }` ## exports `({ getExports : () => Promise<{ [string] : any }> }) => { [string] : Promise }` Used to map exports from the child (passed with `xprops.export(...)`) to properties on the parent component instance. ```javascript const CreatePostForm = zoid.create({ tag: "create-post-form", url: "https://my-site.com/component/create-post-form", exports: { submit: { type: "function", }, }, }); ``` Once this mapper is defined, the child window may export values up to the parent: ```javascript window.xprops.export({ submit: () => { document.querySelector("form#createPost").submit(); }, }); ``` The parent window may call these exports at any time: ```javascript const postForm = CreatePostForm(); postForm.render("#create-post-form-container"); document.querySelector("button#submitForm").addEventListener("click", () => { postForm.submit(); }); ``` ## bridgeUrl `string | ({ props }) => string` The url or a function returning the url for a [post-robot bridge](https://github.com/krakenjs/post-robot#parent-to-popup-messaging). Will be automatically loaded in a hidden iframe when a popup component is rendered, to allow communication between the parent window and the popup in IE/Edge. This is only necessary if you are creating a popup component which needs to run in IE and/or Edge. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", bridgeUrl: "https://foo.com/bridge", }); ``` ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", bridgeUrl: ({ props }) => { return props.env === "development" ? "http://foo.dev/bridge" : "https://foo.com/bridge"; }, }); ``` ## exports `({ getExports : () => Promise<{ [string] : any }> }) => { [string] : Promise }` Used to map exports from the child (passed with `xprops.export(...)`) to properties on the parent component instance. ```javascript const CreatePostForm = zoid.create({ tag: 'create-post-form', url: 'https://my-site.com/component/create-post-form', exports: ({ getExports }) => { return { submit: () => getExports().then(exports => exports.submit()) }; }; }); ``` Once this mapper is defined, the child window may export values up to the parent: ```javascript window.xprops.export({ submit: () => { document.querySelector("form#createPost").submit(); }, }); ``` The parent window may call these exports at any time: ```javascript const postForm = CreatePostForm(); postForm.render("#create-post-form-container"); document.querySelector("button#submitForm").addEventListener("click", () => { postForm.submit(); }); ``` ## children `() => { [string] : ZoidComponent }` Set up components which will be renderable as children of the current component ```javascript const CardNumberField = zoid.create({ tag: 'card-number-field', url: 'https://my-site.com/component/card-fields/number' }); const CardCVVField = zoid.create({ tag: 'card-cvv-field', url: 'https://my-site.com/component/card-fields/cvv' }); const CardExpiryField = zoid.create({ tag: 'card-expiry-field', url: 'https://my-site.com/component/card-fields/expiry' }); const CardFields = zoid.create({ tag: 'card-fields', url: 'https://my-site.com/component/card-fields', children: () => { return { NumberField: CardNumberField, CVVField: CardCVVField, ExpiryField: CardExpiryField }; }; }); ``` These children will now be renderable as children of the parent: ```javascript const cardFields = CardFields({ style: { borderColor: "red", }, }); cardFields.NumberField().render("#card-number-field-container"); cardFields.CVVField().render("#card-cvv-field-container"); cardFields.ExpiryField().render("#card-expiry-field-container"); ``` The children will inherit both `props` and `export` from the parent, in `window.xprops.parent`. ```javascript console.log("Parent style:", window.xprops.parent.style); ``` ```javascript window.xprops.parent.export({ submit: () => { document.querySelector("form#cardFields").submit(); }, }); ``` ================================================ FILE: docs/api/index.md ================================================ # API - [Create](./create.md) - [Prop Definitions](./prop-definitions.md) - [Component](./component.md) - [Instance](./instance.md) - [Render](./render.md) - [Parent Props](./parent-props.md) - [XProps](./xprops.md) ================================================ FILE: docs/api/instance.md ================================================ # Component Instance After instantiating a component, that component instance has a number of helpers. ```javascript const MyComponent = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", }); const component = MyComponent({ foo: "bar", onSomething: () => { console.log("Something happened!"); }, }); ``` ## render `(container : string | HTMLElement, context : 'iframe' | 'popup') => Promise` Render the component to a given container. - container: can be a string selector like `'#my-container'` or a DOM element like `document.body` - context: defaults to `iframe` or `defaultContainer` if set. Can be overriden to explicitly specify `'iframe'` or `'popup'`. ```javascript const component = MyComponent(); component.render("#my-container").then(() => { console.info("The component was successfully rendered"); }); ``` ```javascript const component = MyComponent(); component.render(document.body).then(() => { console.info("The component was successfully rendered"); }); ``` ```javascript const component = MyComponent(); component.render("#my-container", "popup").then(() => { console.info("The component was successfully rendered"); }); ``` ## renderTo `(window : Window, container : string | HTMLElement, context : 'iframe' | 'popup') => Promise` Render the component to a given window and given container. - window: a reference to the window which the component should be rendered to. Zoid must be loaded in that window and the component must be registered. - container: must be a string selector like `'#my-container'` (DOM element is not transferable across different windows) - context: defaults to `iframe` or `defaultContainer` if set. Can be overriden to explicitly specify `'iframe'` or `'popup'`. ```javascript const component = MyComponent(); component.renderTo(window.parent, "#my-container").then(() => { console.info("The component was successfully rendered"); }); ``` ```javascript const component = MyComponent(); component.renderTo(window.parent, "#my-container", "popup").then(() => { console.info("The component was successfully rendered"); }); ``` ## clone `() => ZoidComponentInstance` Clones the current instance with the exact same set of props ```javascript const button1 = ButtonComponent({ color: "red", }); const button2 = button1.clone(); button1.render("#first-button-container"); // First red button button2.render("#first-button-container"); // Second red button ``` ## isEligible `() => boolean` Informs if the component is eligible ```javascript const myComponent = MyComponent(); if (myComponent.isEligible()) { myComponent.render("#my-container"); } ``` To use `isEligible()` you must first define an `eligible` handler when setting up the component: ```javascript const FirefoxOnlyButton = zoid.create({ tag: "my-component", url: "https://my-site.com/my-component", eligible: () => { if (isFireFox()) { return true; } else { return false; } }, }); ``` ## close `() => Promise` Gracefully close the component ```javascript const myComponent = MyComponent(); myComponent.render("#container"); document .querySelector("button#close-component") .addEventListener("click", () => { myComponent.close().then(() => { console.log("Component is now closed"); }); }); ``` ## focus `() => Promise` Focus the component. Only works for popup windows, on a user action like a click. ```javascript const myComponent = MyComponent(); myComponent.render("#container"); document .querySelector("button#focus-component") .addEventListener("click", () => { myComponent.focus().then(() => { console.log("Component is now focused"); }); }); ``` ## resize `({ width : number, height : number }) => Promise` Resize the component. Only works for iframe windows, popups can not be resized once opened. ```javascript const myComponent = MyComponent(); myComponent.render("#container"); document .querySelector("button#resize-component") .addEventListener("click", () => { myComponent.resize({ width: 500, height: 800 }).then(() => { console.log("Component is now resized"); }); }); ``` ## show `() => Promise` Show the component. Only works for iframe windows, popups can not be hidden/shown once opened. ```javascript const myComponent = MyComponent(); myComponent.render("#container"); document .querySelector("button#show-component") .addEventListener("click", () => { myComponent.show().then(() => { console.log("Component is now visible"); }); }); ``` ## hide `() => Promise` Hide the component. Only works for iframe windows, popups can not be hidden/shown once opened. ```javascript const myComponent = MyComponent(); myComponent.render("#container"); document .querySelector("button#hide-component") .addEventListener("click", () => { myComponent.hide().then(() => { console.log("Component is now hidden"); }); }); ``` ## updateProps `({ [string ] : any }) => Promise` Update props in the child window. The child can listen for new props using `window.xprops.onProps` In the parent window: ```javascript const component = MyComponent({ color: "red", }); component.render("#container").then(() => { component.setProps({ color: "blue", }); }); ``` In the child window: ```javascript console.log("The current color is", window.xprops.color); // red window.xprops.onProps(() => { console.log("The current color is", window.xprops.color); // lue }); ``` ## onError `(Error) => Promise` Trigger an error in the component ```javascript const myComponent = MyComponent(); myComponent.render("#container"); document.querySelector("button#trigger-error").addEventListener("click", () => { myComponent.onError(new Error(`Something went wrong`)).then(() => { console.log("Error successfully triggered"); }); }); ``` ## event Event emitter that can be used to listen for the following events: `RENDER`, `RENDERED`, `PRERENDER`, `PRERENDERED`, `DISPLAY`, `ERROR`, `CLOSED`, `PROPS`, `RESIZE`. ```javascript const myComponent = MyComponent(); myComponent.render("#container"); myComponent.event.on(zoid.EVENT.RENDERED, () => { console.log("Component was rendered!"); }); ``` ## exports Any values defined in `export` and passed to `window.xprops.export()` will be available as keys on the component instance: ```javascript const CreatePostForm = zoid.create({ tag: 'create-post-form', url: 'https://my-site.com/component/create-post-form', exports: ({ getExports }) => { return { submit: () => getExports().then(exports => exports.submit()) }; }; }); ``` Once this mapper is defined, the child window may export values up to the parent: ```javascript window.xprops.export({ submit: () => { document.querySelector("form#createPost").submit(); }, }); ``` The parent window may call these exports at any time: ```javascript const postForm = CreatePostForm(); postForm.render("#create-post-form-container"); document.querySelector("button#submitForm").addEventListener("click", () => { postForm.submit(); }); ``` ================================================ FILE: docs/api/parent-props.md ================================================ # Parent Props ## window `Window | ProxyWindow` Pass in a custom window to render the zoid component to. Passing this option will suppress zoid from opening a new window. This value can also be a `ProxyWindow` type (a window serialized by `post-robot` which can be transferred via post message). ```javascript document.querySelector("button#clickme").addEventListener("click", () => { const customPopup = window.open(); MyComponent({ window: customPopup, }).render(); }); ``` ## timeout `number` A timeout after which a component render should fail/error out. ```javascript MyComponent({ timeout: 1000, }) .render("#container") .catch((err) => { console.warn("Component render errored", err); // This could be a timeout error }); ``` ## cspNonce `string` A CSP nonce that will be passed to any inline `script` or `style` tags rendered by zoid in the default `containerTemplate` or `prerenderTemplate` functions. ```javascript MyComponent({ cspNonce: "xyz12345", }).render("#container"); ``` ## onRender `() => void` Called immediately when a render is triggered ```javascript MyComponent({ onRender: () => { console.log("The component started to render!"); }, }).render("#container"); ``` ## onDisplay `() => void` Called when the component has completed its initial prerender ```javascript MyComponent({ onDisplay: () => { console.log("The component was displayed!"); }, }).render("#container"); ``` ## onRendered `() => void` Called when the component has completed its full render ```javascript MyComponent({ onRendered: () => { console.log("The component was fully rendered!"); }, }).render("#container"); ``` ## onClose `() => void` Called when the component is first closed ```javascript MyComponent({ onClose: () => { console.log("The component was closed!"); }, }).render("#container"); ``` ## onDestroy `() => void` Called when the component is fully destroyed ```javascript MyComponent({ onDestroy: () => { console.log("The component was fully destroyed!"); }, }).render("#container"); ``` ## onResize `() => void` Called when the component is resized ```javascript MyComponent({ onResize: () => { console.log("The component was resized!"); }, }).render("#container"); ``` ## onFocus `() => void` Called when the component is focused ```javascript MyComponent({ onFocus: () => { console.log("The component was focused!"); }, }).render("#container"); ``` ================================================ FILE: docs/api/prop-definitions.md ================================================ # Prop Definitions ## type `string` The data-type expected for the prop - `'string'` - `'number'` - `'boolean'` - `'object'` - `'function'` - `'array'` ## required `boolean` Whether or not the prop is mandatory. Defaults to `true`. ```javascript onLogin: { type: 'function', required: false } ``` ## default ```javascript ({ props : Props, state : Object, close : () => Promise, focus : () => Promise, onError : (mixed) => Promise, container : HTMLElement | undefined, event : Event }) => value ``` A function returning the default value for the prop, if none is passed ```javascript email: { type: 'string', required: false, default: function() { return 'a@b.com'; } } ``` ## validate `({ value, props }) => void` A function to validate the passed value. Should throw an appropriate error if invalid. ```javascript email: { type: 'string', validate: function({ value, props }) { if (!value.match(/^.+@.+\..+$/)) { throw new TypeError(`Expected email to be valid format`); } } } ``` ## queryParam `boolean | string | (value) => string` Should a prop be passed in the url. ```javascript email: { type: 'string', queryParam: true // ?email=foo@bar.com } ``` If a string is set, this specifies the url param name which will be used. ```javascript email: { type: 'string', queryParam: 'user-email' // ?user-email=foo@bar.com } ``` If a function is set, this is called to determine the url param which should be used. ```javascript email: { type: 'string', queryParam: function({ value }) { if (value.indexOf('@foo.com') !== -1) { return 'foo-email'; // ?foo-email=person@foo.com } else { return 'generic-email'; // ?generic-email=person@whatever.com } } } ``` ## value ```javascript ({ props : Props, state : Object, close : () => Promise, focus : () => Promise, onError : (mixed) => Promise, container : HTMLElement | undefined, event : Event }) => value ``` The value for the prop, if it should be statically defined at component creation time ```javascript userAgent: { type: 'string', value() { return window.navigator.userAgent; } } ``` ## decorate ```javascript ({ props : Props, state : Object, close : () => Promise, focus : () => Promise, onError : (mixed) => Promise, container : HTMLElement | undefined, event : Event, value : Value }) => value ``` A function used to decorate the prop at render-time. Called with the value of the prop, should return the new value. ```javascript onLogin: { type: 'function', decorate(original) { return function() { console.log('User logged in!'); return original.apply(this, arguments); }; } } ``` ## serialization `string` If `json`, the prop will be JSON stringified before being inserted into the url ```javascript user: { type: 'object', serialization: 'json' // ?user={"name":"Zippy","age":34} } ``` If `dotify` the prop will be converted to dot-notation. ```javascript user: { type: 'object', serialization: 'dotify' // ?user.name=Zippy&user.age=34 } ``` If `base64`, the prop will be JSON stringified then base64 encoded before being inserted into the url ```javascript user: { type: 'object', serialization: 'base64' // ?user=eyJuYW1lIjoiWmlwcHkiLCJhZ2UiOjM0fQ== } ``` ## alias `string` An aliased name for the prop ```javascript onLogin: { type: 'function', alias: 'onUserLogin' } ``` ================================================ FILE: docs/api/render.md ================================================ # Render ## Basic Render (same window) ```javacript Component(props).render(container, ?context) ``` Render the component to the given container element. ### props `{ [string] : any }` Object containing all of the props required by the given component. These can be user-defined props, or pre-defined built-in props. ```javascript MyComponent({ foo: "bar", onBaz: () => { console.log("Baz happened"); }, }).render("#container"); ``` See [Parent Props](./parent-props.md) for built-in props that can be passed to any zoid component. ### container `string | HTMLElement` Element selector, or element, into which the component should be rendered. Defaults to `document.body`. ### context `iframe | popup` The context to render to. Defaults to `defaultContext`, or if `defaultContext` is not set, `iframe`. ## Remote render (different window) ```javascript Component(props).renderTo(win, container, ?context) ``` Equivalent to `Component().render()` but allows rendering to a remote window. For example, a child component may render a new component to the parent page. - The component must have been registered on the target window - The component must be rendered from within the iframe of an existing component - The component being rendered must have the same domain as the component initiating the render ### win `Window` The target window to which the component should be rendered. Ordinarily this will be `window.parent`. ### props `{ [string] : any }` Object containing all of the props required by the given component ### container `string` Element selector, into which the component should be rendered. Must be a string for remote rendering Defaults to `document.body`. ### context `iframe | popup` The context to render to. Defaults to `defaultContext`, or if `defaultContext` is not set, `iframe`. ================================================ FILE: docs/api/xprops.md ================================================ # `xprops` By default `window.xprops` is populated in the child window/frame with any props from the parent. Some built-in props are provided and automatically populated on `window.xprops`: ## xprops.close `() => Promise` Gracefully close the component. ```javascript document.querySelector("button#close").addEventListener("click", () => { window.xprops.close(); }); ``` ## xprops.focus `() => Promise` Refocus the component. Works on popup windows only, should be triggered on a user interaction like a click, in order to be allowed by the browser. ```javascript document.querySelector("button#focus").addEventListener("click", () => { window.xprops.focus(); }); ``` ## xprops.resize `({ width : number, height : number }) => Promise` Resize the component. Works on iframe windows only, popups can not be resized after opening. ```javascript document.querySelector("button#resize").addEventListener("click", () => { window.xprops.resize({ width: 500, height: 800 }); }); ``` ## xprops.uid `string` Unique ID for the component instance ```javascript console.log("The current component uid is:", window.xprops.uid); ``` ## xprops.tag `string` Tag for the component instance ```javascript console.log("The current component is:", window.xprops.tag); ``` ## xprops.getParent `() => Window` Get a reference to the parent window ```javascript const parentWindow = window.xprops.getParent(); parentWindow.postMessage("hello!", "*"); ``` ## xprops.getParentDomain `() => string` Get the domain of the parent window ```javascript console.log( "The current parent window domain is:", window.xprops.getParentDomain() ); ``` ## xprops.show `() => Promise` Show the component. Works on iframe windows only, popups can not be shown/hidden after opening. ```javascript document.querySelector("button#show").addEventListener("click", () => { window.xprops.show(); }); ``` ## xprops.hide `() => Promise` Hide the component. Works on iframe windows only, popups can not be shown/hidden after opening. ```javascript document.querySelector("button#hide").addEventListener("click", () => { window.xprops.hide(); }); ``` ## xprops.export `({ [string] : any }) => Promise` Export data and/or functions from the child to the parent window. ```javascript window.xprops.export({ submit: () => { document.querySelector("form#createPost").submit(); }, }); ``` This export will be available on the parent window: ```javascript const postForm = CreatePostForm(); postForm.render("#create-post-form-container"); document.querySelector("button#submitForm").addEventListener("click", () => { postForm.submit(); }); ``` This assumes that when the component was first created, the author implemented the `exports` function to ensure the exports are mapped to the parent: ```javascript const CreatePostForm = zoid.create({ tag: 'create-post-form', url: 'https://my-site.com/component/create-post-form', exports: ({ getExports }) => { return { submit: () => getExports().then(exports => exports.submit()) }; }; }); ``` This mapper is necessary so that the exports are immediately available on the parent component instance, even before the component is fully rendered and before `xprops.export(...)` has been called in the child window. ## xprops.onError `(Error) => Promise` Send an error to the parent ``` window.xprops.onError(new Error(`Something went wrong!`)); ``` ## xprops.onProps `(({ [string] : any }) => void) => void` Set up a listener to receive new props as they are set by the parent window using `componentInstance.setProps(...)` In the child window: ```javascript console.log("The current color is", window.xprops.color); // red window.xprops.onProps(() => { console.log("The current color is", window.xprops.color); // blue }); ``` In the parent window: ```javascript const component = MyComponent({ color: "red", }); component.render("#container").then(() => { component.setProps({ color: "blue", }); }); ``` ## xprops.parent.props `{ [string] : any }` Props from the parent component, if the component is rendered as a child. Define the components: ```javascript const ChildComponent = zoid.create({ tag: "child-component", url: "https://my-site.com/component/child", }); const ParentComponent = zoid.create({ tag: "child-component", url: "https://my-site.com/component/child", children: () => { return { Child: ChildComponent, }; }, }); ``` In the parent window: ```javascript const parent = ParentComponent({ color: "blue", }); const child = parent.Child(); child.render("#child-container"); ``` In the child window: ```javascript console.log("The color of this component is:", window.xprops.parent.color); // Red ``` ## xprops.parent.export `({ [string] : any }) => Promise` Export values to the parent component. Define the components: ```javascript const ChildComponent = zoid.create({ tag: "child-component", url: "https://my-site.com/component/child", }); const ParentComponent = zoid.create({ tag: "child-component", url: "https://my-site.com/component/child", children: () => { return { Child: ChildComponent, }; }, exports: ({ getExports }) => { return { sayHello: () => getExports().then((exports) => exports.sayHello()), }; }, }); ``` In the parent window: ```javascript const parent = ParentComponent({ color: "blue", }); const child = parent.Child(); child.render("#child-container"); document.querySelector("button#doSomething").addEventListener("click", () => { parent.sayHello(); // Should log 'hello world!' }); ``` In the child window: ```javascript window.xprops.parent.export({ sayHello: () => { console.log("hello world!"); }, }); ``` ## xprops.getSiblings `({ anyParent : boolean }) => Array<{ tag : string, xprops : XProps, exports : Exports }>` Get an array of sibling components on the same domain ```javascript for (const sibling of window.xprops.getSiblings()) { console.log("Found sibling!", sibling.tag); } ``` ```javascript for (const sibling of window.xprops.getSiblings({ anyParent: true })) { console.log("Found sibling from any parent!", sibling.tag); } ``` ================================================ FILE: docs/example.md ================================================ # zoid example Let's create a login component. We want the user to be able to log in on our site, and to notify the parent window that the user has logged in, without exposing any of the users credentials to the parent window. Take a look at the [demos](http://krakenjs.com/zoid/demo/index.htm) to see this example in action. ### As the component creator First I'd create a spec for the component's interface. I should do this once -- once I've created the component, I can render it multiple times if I need to: ```javascript var MyLoginComponent = zoid.create({ // The html tag used to render my component tag: "my-login-component", // The url that will be loaded in the iframe or popup, when someone includes my component on their page url: "http://www.my-site.com/my-login-component", // The size of the component on their page. Only px and % strings are supported dimensions: { width: "400px", height: "200px", }, // The properties they can (or must) pass down to my component. This is optional. props: { prefilledEmail: { type: "string", required: false, }, onLogin: { type: "function", required: true, }, }, }); ``` This spec describes everything needed to render the component on the parent page, including the props the component expects. Now we need to actually implement the business logic of the component -- the code that will run inside the iframe. I just need to use `window.xprops` to get the props that are passed down. ```html
``` Now anyone can render the component we defined onto their page! ### As the component user My life is even easier. I just need to drop in your component onto my page: ```html
``` I can render a component as many times as I like on my page. This is even easier if you're using a supported framework like React, Ember or Angular -- zoid will automatically set up bindings for these frameworks: ### React / JSX Drop the component in any `render()` method: ```javascript let MyReactLoginComponent = MyLoginComponent.driver("react", { React: React, ReactDOM: ReactDOM, }); ``` ```javascript render: function() { return ( ); } ``` ### Angular Specify the component name as a dependency to your angular app: ```javascript angular.module("myapp", ["my-login-component"]); ``` Include the tag in one of your templates (don't forget to use dasherized prop names): ```html ``` --- And we're done! Notice how I never had to write any code to create an iframe, or send post messages? That's all taken care of for you. When you call `this.props.onLogin(email);` it looks like you're just calling a function, but in reality `zoid` is transparently turning that callback into a post-message and relaying it to the parent for you. - [Now try building a cross-domain React component!](https://medium.com/@bluepnume/creating-a-cross-domain-react-component-with-zoid-fbcccc4778fd#.73jnwv44c) ================================================ FILE: flow-typed/npm/@commitlint/cli_vx.x.x.js ================================================ // flow-typed signature: 5559d97aaf526bbcbabcb99b36bc5e17 // flow-typed version: <>/@commitlint/cli_v^16.2.1/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@commitlint/cli' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@commitlint/cli' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@commitlint/cli/cli' { declare module.exports: any; } declare module '@commitlint/cli/lib/cli-error' { declare module.exports: any; } declare module '@commitlint/cli/lib/cli' { declare module.exports: any; } declare module '@commitlint/cli/lib/types' { declare module.exports: any; } // Filename aliases declare module '@commitlint/cli/cli.js' { declare module.exports: $Exports<'@commitlint/cli/cli'>; } declare module '@commitlint/cli/index' { declare module.exports: $Exports<'@commitlint/cli'>; } declare module '@commitlint/cli/index.js' { declare module.exports: $Exports<'@commitlint/cli'>; } declare module '@commitlint/cli/lib/cli-error.js' { declare module.exports: $Exports<'@commitlint/cli/lib/cli-error'>; } declare module '@commitlint/cli/lib/cli.js' { declare module.exports: $Exports<'@commitlint/cli/lib/cli'>; } declare module '@commitlint/cli/lib/types.js' { declare module.exports: $Exports<'@commitlint/cli/lib/types'>; } ================================================ FILE: flow-typed/npm/@commitlint/config-conventional_vx.x.x.js ================================================ // flow-typed signature: 9962542700789a22cff26fc78989b904 // flow-typed version: <>/@commitlint/config-conventional_v^16.2.1/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@commitlint/config-conventional' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@commitlint/config-conventional' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ // Filename aliases declare module '@commitlint/config-conventional/index' { declare module.exports: $Exports<'@commitlint/config-conventional'>; } declare module '@commitlint/config-conventional/index.js' { declare module.exports: $Exports<'@commitlint/config-conventional'>; } ================================================ FILE: flow-typed/npm/@krakenjs/belter_vx.x.x.js ================================================ // flow-typed signature: 78dfcbdab7b7573cb3d17170eaade9ab // flow-typed version: <>/@krakenjs/belter_v^2.0.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@krakenjs/belter' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@krakenjs/belter' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@krakenjs/belter/dist/belter' { declare module.exports: any; } declare module '@krakenjs/belter/dist/belter.min' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/constants' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/css' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/decorators' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/device' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/dom' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/experiment' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/global' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/http' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/index.flow' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/screenHeights' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/storage' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/test' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/types' { declare module.exports: any; } declare module '@krakenjs/belter/dist/module/util' { declare module.exports: any; } declare module '@krakenjs/belter/src/constants' { declare module.exports: any; } declare module '@krakenjs/belter/src/css' { declare module.exports: any; } declare module '@krakenjs/belter/src/decorators' { declare module.exports: any; } declare module '@krakenjs/belter/src/device' { declare module.exports: any; } declare module '@krakenjs/belter/src/dom' { declare module.exports: any; } declare module '@krakenjs/belter/src/experiment' { declare module.exports: any; } declare module '@krakenjs/belter/src/global' { declare module.exports: any; } declare module '@krakenjs/belter/src/http' { declare module.exports: any; } declare module '@krakenjs/belter/src/index.flow' { declare module.exports: any; } declare module '@krakenjs/belter/src' { declare module.exports: any; } declare module '@krakenjs/belter/src/screenHeights' { declare module.exports: any; } declare module '@krakenjs/belter/src/storage' { declare module.exports: any; } declare module '@krakenjs/belter/src/test' { declare module.exports: any; } declare module '@krakenjs/belter/src/types' { declare module.exports: any; } declare module '@krakenjs/belter/src/util' { declare module.exports: any; } // Filename aliases declare module '@krakenjs/belter/dist/belter.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/belter'>; } declare module '@krakenjs/belter/dist/belter.min.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/belter.min'>; } declare module '@krakenjs/belter/dist/module/constants.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/constants'>; } declare module '@krakenjs/belter/dist/module/css.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/css'>; } declare module '@krakenjs/belter/dist/module/decorators.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/decorators'>; } declare module '@krakenjs/belter/dist/module/device.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/device'>; } declare module '@krakenjs/belter/dist/module/dom.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/dom'>; } declare module '@krakenjs/belter/dist/module/experiment.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/experiment'>; } declare module '@krakenjs/belter/dist/module/global.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/global'>; } declare module '@krakenjs/belter/dist/module/http.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/http'>; } declare module '@krakenjs/belter/dist/module/index.flow.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/index.flow'>; } declare module '@krakenjs/belter/dist/module/index' { declare module.exports: $Exports<'@krakenjs/belter/dist/module'>; } declare module '@krakenjs/belter/dist/module/index.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module'>; } declare module '@krakenjs/belter/dist/module/screenHeights.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/screenHeights'>; } declare module '@krakenjs/belter/dist/module/storage.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/storage'>; } declare module '@krakenjs/belter/dist/module/test.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/test'>; } declare module '@krakenjs/belter/dist/module/types.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/types'>; } declare module '@krakenjs/belter/dist/module/util.js' { declare module.exports: $Exports<'@krakenjs/belter/dist/module/util'>; } declare module '@krakenjs/belter/index' { declare module.exports: $Exports<'@krakenjs/belter'>; } declare module '@krakenjs/belter/index.js' { declare module.exports: $Exports<'@krakenjs/belter'>; } declare module '@krakenjs/belter/src/constants.js' { declare module.exports: $Exports<'@krakenjs/belter/src/constants'>; } declare module '@krakenjs/belter/src/css.js' { declare module.exports: $Exports<'@krakenjs/belter/src/css'>; } declare module '@krakenjs/belter/src/decorators.js' { declare module.exports: $Exports<'@krakenjs/belter/src/decorators'>; } declare module '@krakenjs/belter/src/device.js' { declare module.exports: $Exports<'@krakenjs/belter/src/device'>; } declare module '@krakenjs/belter/src/dom.js' { declare module.exports: $Exports<'@krakenjs/belter/src/dom'>; } declare module '@krakenjs/belter/src/experiment.js' { declare module.exports: $Exports<'@krakenjs/belter/src/experiment'>; } declare module '@krakenjs/belter/src/global.js' { declare module.exports: $Exports<'@krakenjs/belter/src/global'>; } declare module '@krakenjs/belter/src/http.js' { declare module.exports: $Exports<'@krakenjs/belter/src/http'>; } declare module '@krakenjs/belter/src/index.flow.js' { declare module.exports: $Exports<'@krakenjs/belter/src/index.flow'>; } declare module '@krakenjs/belter/src/index' { declare module.exports: $Exports<'@krakenjs/belter/src'>; } declare module '@krakenjs/belter/src/index.js' { declare module.exports: $Exports<'@krakenjs/belter/src'>; } declare module '@krakenjs/belter/src/screenHeights.js' { declare module.exports: $Exports<'@krakenjs/belter/src/screenHeights'>; } declare module '@krakenjs/belter/src/storage.js' { declare module.exports: $Exports<'@krakenjs/belter/src/storage'>; } declare module '@krakenjs/belter/src/test.js' { declare module.exports: $Exports<'@krakenjs/belter/src/test'>; } declare module '@krakenjs/belter/src/types.js' { declare module.exports: $Exports<'@krakenjs/belter/src/types'>; } declare module '@krakenjs/belter/src/util.js' { declare module.exports: $Exports<'@krakenjs/belter/src/util'>; } ================================================ FILE: flow-typed/npm/@krakenjs/cross-domain-utils_vx.x.x.js ================================================ // flow-typed signature: 1b384d8a481c18b578d4eb7f1866aefd // flow-typed version: <>/@krakenjs/cross-domain-utils_v^3.0.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@krakenjs/cross-domain-utils' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@krakenjs/cross-domain-utils' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@krakenjs/cross-domain-utils/dist/cross-domain-utils' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/cross-domain-utils.min' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/module/constants' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/module/index.flow' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/module' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/module/types' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/module/util' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/dist/module/utils' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/src/constants' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/src/index.flow' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/src' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/src/types' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/src/util' { declare module.exports: any; } declare module '@krakenjs/cross-domain-utils/src/utils' { declare module.exports: any; } // Filename aliases declare module '@krakenjs/cross-domain-utils/dist/cross-domain-utils.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/cross-domain-utils'>; } declare module '@krakenjs/cross-domain-utils/dist/cross-domain-utils.min.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/cross-domain-utils.min'>; } declare module '@krakenjs/cross-domain-utils/dist/module/constants.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module/constants'>; } declare module '@krakenjs/cross-domain-utils/dist/module/index.flow.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module/index.flow'>; } declare module '@krakenjs/cross-domain-utils/dist/module/index' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module'>; } declare module '@krakenjs/cross-domain-utils/dist/module/index.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module'>; } declare module '@krakenjs/cross-domain-utils/dist/module/types.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module/types'>; } declare module '@krakenjs/cross-domain-utils/dist/module/util.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module/util'>; } declare module '@krakenjs/cross-domain-utils/dist/module/utils.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/dist/module/utils'>; } declare module '@krakenjs/cross-domain-utils/src/constants.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src/constants'>; } declare module '@krakenjs/cross-domain-utils/src/index.flow.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src/index.flow'>; } declare module '@krakenjs/cross-domain-utils/src/index' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src'>; } declare module '@krakenjs/cross-domain-utils/src/index.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src'>; } declare module '@krakenjs/cross-domain-utils/src/types.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src/types'>; } declare module '@krakenjs/cross-domain-utils/src/util.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src/util'>; } declare module '@krakenjs/cross-domain-utils/src/utils.js' { declare module.exports: $Exports<'@krakenjs/cross-domain-utils/src/utils'>; } ================================================ FILE: flow-typed/npm/@krakenjs/grumbler-scripts_vx.x.x.js ================================================ // flow-typed signature: 7ec2f9ff984b201918fcd9678837db06 // flow-typed version: <>/@krakenjs/grumbler-scripts_v^8.0.4/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@krakenjs/grumbler-scripts' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@krakenjs/grumbler-scripts' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@krakenjs/grumbler-scripts/config/karma.conf' { declare module.exports: any; } declare module '@krakenjs/grumbler-scripts/config/webpack.config' { declare module.exports: any; } declare module '@krakenjs/grumbler-scripts/test/component' { declare module.exports: any; } declare module '@krakenjs/grumbler-scripts/test/dependency' { declare module.exports: any; } declare module '@krakenjs/grumbler-scripts/test/module' { declare module.exports: any; } declare module '@krakenjs/grumbler-scripts/webpack.config' { declare module.exports: any; } // Filename aliases declare module '@krakenjs/grumbler-scripts/config/karma.conf.js' { declare module.exports: $Exports<'@krakenjs/grumbler-scripts/config/karma.conf'>; } declare module '@krakenjs/grumbler-scripts/config/webpack.config.js' { declare module.exports: $Exports<'@krakenjs/grumbler-scripts/config/webpack.config'>; } declare module '@krakenjs/grumbler-scripts/test/component.jsx' { declare module.exports: $Exports<'@krakenjs/grumbler-scripts/test/component'>; } declare module '@krakenjs/grumbler-scripts/test/dependency.js' { declare module.exports: $Exports<'@krakenjs/grumbler-scripts/test/dependency'>; } declare module '@krakenjs/grumbler-scripts/test/module.js' { declare module.exports: $Exports<'@krakenjs/grumbler-scripts/test/module'>; } declare module '@krakenjs/grumbler-scripts/webpack.config.js' { declare module.exports: $Exports<'@krakenjs/grumbler-scripts/webpack.config'>; } ================================================ FILE: flow-typed/npm/@krakenjs/jsx-pragmatic_vx.x.x.js ================================================ // flow-typed signature: e3879a2c640bc8421f798cb70cce7477 // flow-typed version: <>/@krakenjs/jsx-pragmatic_v^3.0.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@krakenjs/jsx-pragmatic' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@krakenjs/jsx-pragmatic' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@krakenjs/jsx-pragmatic/dist/jsx-pragmatic-demo' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/jsx-pragmatic' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/jsx-pragmatic.min' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/component' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/component/regex' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/component/style' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/constants' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/node' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/dom' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/html' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/preact' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/react' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/regex' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/text' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/types' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/dist/module/util' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/component' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/component/regex' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/component/style' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/constants' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/node' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers/dom' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers/html' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers/preact' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers/react' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers/regex' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/renderers/text' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/types' { declare module.exports: any; } declare module '@krakenjs/jsx-pragmatic/src/util' { declare module.exports: any; } // Filename aliases declare module '@krakenjs/jsx-pragmatic/dist/jsx-pragmatic-demo.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/jsx-pragmatic-demo'>; } declare module '@krakenjs/jsx-pragmatic/dist/jsx-pragmatic.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/jsx-pragmatic'>; } declare module '@krakenjs/jsx-pragmatic/dist/jsx-pragmatic.min.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/jsx-pragmatic.min'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/component/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/component'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/component/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/component'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/component/regex.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/component/regex'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/component/style.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/component/style'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/constants.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/constants'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/node.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/node'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/dom.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers/dom'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/html.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers/html'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/preact.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers/preact'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/react.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers/react'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/regex.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers/regex'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/renderers/text.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/renderers/text'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/types.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/types'>; } declare module '@krakenjs/jsx-pragmatic/dist/module/util.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/dist/module/util'>; } declare module '@krakenjs/jsx-pragmatic/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic'>; } declare module '@krakenjs/jsx-pragmatic/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic'>; } declare module '@krakenjs/jsx-pragmatic/src/component/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/component'>; } declare module '@krakenjs/jsx-pragmatic/src/component/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/component'>; } declare module '@krakenjs/jsx-pragmatic/src/component/regex.jsx' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/component/regex'>; } declare module '@krakenjs/jsx-pragmatic/src/component/style.jsx' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/component/style'>; } declare module '@krakenjs/jsx-pragmatic/src/constants.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/constants'>; } declare module '@krakenjs/jsx-pragmatic/src/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src'>; } declare module '@krakenjs/jsx-pragmatic/src/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src'>; } declare module '@krakenjs/jsx-pragmatic/src/node.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/node'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/dom.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers/dom'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/html.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers/html'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/index' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/index.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/preact.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers/preact'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/react.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers/react'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/regex.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers/regex'>; } declare module '@krakenjs/jsx-pragmatic/src/renderers/text.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/renderers/text'>; } declare module '@krakenjs/jsx-pragmatic/src/types.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/types'>; } declare module '@krakenjs/jsx-pragmatic/src/util.js' { declare module.exports: $Exports<'@krakenjs/jsx-pragmatic/src/util'>; } ================================================ FILE: flow-typed/npm/@krakenjs/post-robot_vx.x.x.js ================================================ // flow-typed signature: 18f28813f8bef0fbfc11f18b89116082 // flow-typed version: <>/@krakenjs/post-robot_v^11.0.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@krakenjs/post-robot' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@krakenjs/post-robot' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@krakenjs/post-robot/dist/module/bridge/bridge' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/bridge/child' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/bridge/common' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/bridge' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/bridge/parent' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/bridge/setup' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/clean' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/conf/config' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/conf/constants' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/conf' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/declarations' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers/listeners' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers/receive' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers/receive/types' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers/send' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers/send/strategies' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/drivers/types' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/global' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/lib/compat' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/lib/hello' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/lib' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/lib/windows' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/public' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/public/on' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/public/send' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/serialize/function' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/serialize' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/serialize/promise' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/serialize/serialize' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/serialize/window' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/setup' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/module/types' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/post-robot.ie' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/post-robot.ie.min' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/post-robot' { declare module.exports: any; } declare module '@krakenjs/post-robot/dist/post-robot.min' { declare module.exports: any; } declare module '@krakenjs/post-robot/globals' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/bridge/bridge' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/bridge/child' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/bridge/common' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/bridge' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/bridge/parent' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/bridge/setup' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/clean' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/conf/config' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/conf/constants' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/conf' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/declarations' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers/listeners' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers/receive' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers/receive/types' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers/send' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers/send/strategies' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/drivers/types' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/global' { declare module.exports: any; } declare module '@krakenjs/post-robot/src' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/lib/compat' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/lib/hello' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/lib' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/lib/windows' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/public' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/public/on' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/public/send' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/serialize/function' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/serialize' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/serialize/promise' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/serialize/serialize' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/serialize/window' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/setup' { declare module.exports: any; } declare module '@krakenjs/post-robot/src/types' { declare module.exports: any; } // Filename aliases declare module '@krakenjs/post-robot/dist/module/bridge/bridge.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge/bridge'>; } declare module '@krakenjs/post-robot/dist/module/bridge/child.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge/child'>; } declare module '@krakenjs/post-robot/dist/module/bridge/common.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge/common'>; } declare module '@krakenjs/post-robot/dist/module/bridge/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge'>; } declare module '@krakenjs/post-robot/dist/module/bridge/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge'>; } declare module '@krakenjs/post-robot/dist/module/bridge/parent.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge/parent'>; } declare module '@krakenjs/post-robot/dist/module/bridge/setup.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/bridge/setup'>; } declare module '@krakenjs/post-robot/dist/module/clean.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/clean'>; } declare module '@krakenjs/post-robot/dist/module/conf/config.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/conf/config'>; } declare module '@krakenjs/post-robot/dist/module/conf/constants.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/conf/constants'>; } declare module '@krakenjs/post-robot/dist/module/conf/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/conf'>; } declare module '@krakenjs/post-robot/dist/module/conf/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/conf'>; } declare module '@krakenjs/post-robot/dist/module/declarations.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/declarations'>; } declare module '@krakenjs/post-robot/dist/module/drivers/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers'>; } declare module '@krakenjs/post-robot/dist/module/drivers/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers'>; } declare module '@krakenjs/post-robot/dist/module/drivers/listeners.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/listeners'>; } declare module '@krakenjs/post-robot/dist/module/drivers/receive/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/receive'>; } declare module '@krakenjs/post-robot/dist/module/drivers/receive/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/receive'>; } declare module '@krakenjs/post-robot/dist/module/drivers/receive/types.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/receive/types'>; } declare module '@krakenjs/post-robot/dist/module/drivers/send/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/send'>; } declare module '@krakenjs/post-robot/dist/module/drivers/send/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/send'>; } declare module '@krakenjs/post-robot/dist/module/drivers/send/strategies.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/send/strategies'>; } declare module '@krakenjs/post-robot/dist/module/drivers/types.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/drivers/types'>; } declare module '@krakenjs/post-robot/dist/module/global.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/global'>; } declare module '@krakenjs/post-robot/dist/module/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module'>; } declare module '@krakenjs/post-robot/dist/module/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module'>; } declare module '@krakenjs/post-robot/dist/module/lib/compat.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/lib/compat'>; } declare module '@krakenjs/post-robot/dist/module/lib/hello.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/lib/hello'>; } declare module '@krakenjs/post-robot/dist/module/lib/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/lib'>; } declare module '@krakenjs/post-robot/dist/module/lib/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/lib'>; } declare module '@krakenjs/post-robot/dist/module/lib/windows.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/lib/windows'>; } declare module '@krakenjs/post-robot/dist/module/public/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/public'>; } declare module '@krakenjs/post-robot/dist/module/public/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/public'>; } declare module '@krakenjs/post-robot/dist/module/public/on.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/public/on'>; } declare module '@krakenjs/post-robot/dist/module/public/send.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/public/send'>; } declare module '@krakenjs/post-robot/dist/module/serialize/function.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/serialize/function'>; } declare module '@krakenjs/post-robot/dist/module/serialize/index' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/serialize'>; } declare module '@krakenjs/post-robot/dist/module/serialize/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/serialize'>; } declare module '@krakenjs/post-robot/dist/module/serialize/promise.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/serialize/promise'>; } declare module '@krakenjs/post-robot/dist/module/serialize/serialize.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/serialize/serialize'>; } declare module '@krakenjs/post-robot/dist/module/serialize/window.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/serialize/window'>; } declare module '@krakenjs/post-robot/dist/module/setup.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/setup'>; } declare module '@krakenjs/post-robot/dist/module/types.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/module/types'>; } declare module '@krakenjs/post-robot/dist/post-robot.ie.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/post-robot.ie'>; } declare module '@krakenjs/post-robot/dist/post-robot.ie.min.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/post-robot.ie.min'>; } declare module '@krakenjs/post-robot/dist/post-robot.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/post-robot'>; } declare module '@krakenjs/post-robot/dist/post-robot.min.js' { declare module.exports: $Exports<'@krakenjs/post-robot/dist/post-robot.min'>; } declare module '@krakenjs/post-robot/globals.js' { declare module.exports: $Exports<'@krakenjs/post-robot/globals'>; } declare module '@krakenjs/post-robot/index' { declare module.exports: $Exports<'@krakenjs/post-robot'>; } declare module '@krakenjs/post-robot/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot'>; } declare module '@krakenjs/post-robot/src/bridge/bridge.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge/bridge'>; } declare module '@krakenjs/post-robot/src/bridge/child.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge/child'>; } declare module '@krakenjs/post-robot/src/bridge/common.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge/common'>; } declare module '@krakenjs/post-robot/src/bridge/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge'>; } declare module '@krakenjs/post-robot/src/bridge/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge'>; } declare module '@krakenjs/post-robot/src/bridge/parent.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge/parent'>; } declare module '@krakenjs/post-robot/src/bridge/setup.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/bridge/setup'>; } declare module '@krakenjs/post-robot/src/clean.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/clean'>; } declare module '@krakenjs/post-robot/src/conf/config.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/conf/config'>; } declare module '@krakenjs/post-robot/src/conf/constants.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/conf/constants'>; } declare module '@krakenjs/post-robot/src/conf/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/conf'>; } declare module '@krakenjs/post-robot/src/conf/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/conf'>; } declare module '@krakenjs/post-robot/src/declarations.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/declarations'>; } declare module '@krakenjs/post-robot/src/drivers/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers'>; } declare module '@krakenjs/post-robot/src/drivers/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers'>; } declare module '@krakenjs/post-robot/src/drivers/listeners.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/listeners'>; } declare module '@krakenjs/post-robot/src/drivers/receive/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/receive'>; } declare module '@krakenjs/post-robot/src/drivers/receive/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/receive'>; } declare module '@krakenjs/post-robot/src/drivers/receive/types.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/receive/types'>; } declare module '@krakenjs/post-robot/src/drivers/send/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/send'>; } declare module '@krakenjs/post-robot/src/drivers/send/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/send'>; } declare module '@krakenjs/post-robot/src/drivers/send/strategies.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/send/strategies'>; } declare module '@krakenjs/post-robot/src/drivers/types.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/drivers/types'>; } declare module '@krakenjs/post-robot/src/global.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/global'>; } declare module '@krakenjs/post-robot/src/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src'>; } declare module '@krakenjs/post-robot/src/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src'>; } declare module '@krakenjs/post-robot/src/lib/compat.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/lib/compat'>; } declare module '@krakenjs/post-robot/src/lib/hello.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/lib/hello'>; } declare module '@krakenjs/post-robot/src/lib/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/lib'>; } declare module '@krakenjs/post-robot/src/lib/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/lib'>; } declare module '@krakenjs/post-robot/src/lib/windows.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/lib/windows'>; } declare module '@krakenjs/post-robot/src/public/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/public'>; } declare module '@krakenjs/post-robot/src/public/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/public'>; } declare module '@krakenjs/post-robot/src/public/on.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/public/on'>; } declare module '@krakenjs/post-robot/src/public/send.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/public/send'>; } declare module '@krakenjs/post-robot/src/serialize/function.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/serialize/function'>; } declare module '@krakenjs/post-robot/src/serialize/index' { declare module.exports: $Exports<'@krakenjs/post-robot/src/serialize'>; } declare module '@krakenjs/post-robot/src/serialize/index.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/serialize'>; } declare module '@krakenjs/post-robot/src/serialize/promise.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/serialize/promise'>; } declare module '@krakenjs/post-robot/src/serialize/serialize.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/serialize/serialize'>; } declare module '@krakenjs/post-robot/src/serialize/window.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/serialize/window'>; } declare module '@krakenjs/post-robot/src/setup.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/setup'>; } declare module '@krakenjs/post-robot/src/types.js' { declare module.exports: $Exports<'@krakenjs/post-robot/src/types'>; } ================================================ FILE: flow-typed/npm/@krakenjs/zalgo-promise_vx.x.x.js ================================================ // flow-typed signature: a31bde17276864ac955bb0ae5d9ebb5f // flow-typed version: <>/@krakenjs/zalgo-promise_v^2.0.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * '@krakenjs/zalgo-promise' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module '@krakenjs/zalgo-promise' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module '@krakenjs/zalgo-promise/dist/module/exceptions' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/module/export' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/module/flush' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/module' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/module/promise' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/module/types' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/module/utils' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/zalgo-promise' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/dist/zalgo-promise.min' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src/exceptions' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src/export' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src/flush' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src/promise' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src/types' { declare module.exports: any; } declare module '@krakenjs/zalgo-promise/src/utils' { declare module.exports: any; } // Filename aliases declare module '@krakenjs/zalgo-promise/dist/module/exceptions.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module/exceptions'>; } declare module '@krakenjs/zalgo-promise/dist/module/export.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module/export'>; } declare module '@krakenjs/zalgo-promise/dist/module/flush.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module/flush'>; } declare module '@krakenjs/zalgo-promise/dist/module/index' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module'>; } declare module '@krakenjs/zalgo-promise/dist/module/index.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module'>; } declare module '@krakenjs/zalgo-promise/dist/module/promise.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module/promise'>; } declare module '@krakenjs/zalgo-promise/dist/module/types.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module/types'>; } declare module '@krakenjs/zalgo-promise/dist/module/utils.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/module/utils'>; } declare module '@krakenjs/zalgo-promise/dist/zalgo-promise.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/zalgo-promise'>; } declare module '@krakenjs/zalgo-promise/dist/zalgo-promise.min.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/dist/zalgo-promise.min'>; } declare module '@krakenjs/zalgo-promise/index' { declare module.exports: $Exports<'@krakenjs/zalgo-promise'>; } declare module '@krakenjs/zalgo-promise/index.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise'>; } declare module '@krakenjs/zalgo-promise/src/exceptions.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src/exceptions'>; } declare module '@krakenjs/zalgo-promise/src/export.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src/export'>; } declare module '@krakenjs/zalgo-promise/src/flush.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src/flush'>; } declare module '@krakenjs/zalgo-promise/src/index' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src'>; } declare module '@krakenjs/zalgo-promise/src/index.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src'>; } declare module '@krakenjs/zalgo-promise/src/promise.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src/promise'>; } declare module '@krakenjs/zalgo-promise/src/types.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src/types'>; } declare module '@krakenjs/zalgo-promise/src/utils.js' { declare module.exports: $Exports<'@krakenjs/zalgo-promise/src/utils'>; } ================================================ FILE: flow-typed/npm/@octokit/rest_v18.x.x.js ================================================ // flow-typed signature: 6103021a6389a42ea8b41c577b3f91b3 // flow-typed version: 79dc43986b/@octokit/rest_v18.x.x/flow_>=v0.83.x declare module '@octokit/rest' { /** * Octokit-specific request options which are ignored for the actual request, but can be used by Octokit or plugins to manipulate how the request is sent or how a response is handled */ declare type RequestRequestOptions = {| /** * Node only. Useful for custom proxy, certificate, or dns lookup. * * @see https://nodejs.org/api/http.html#http_class_http_agent */ agent?: mixed, /** * Custom replacement for built-in fetch method. Useful for testing or request hooks. */ fetch?: any, /** * Use an `AbortController` instance to cancel a request. In node you can only cancel streamed requests. */ signal?: any, /** * Node only. Request/response timeout in ms, it resets on redirect. 0 to disable (OS limit applies). `options.request.signal` is recommended instead. */ timeout?: number, [option: string]: any, |}; declare class Octokit { constructor(options?: {| authStrategy?: any, auth?: any, userAgent?: string, previews?: Array, baseUrl?: string, log?: {| debug?: (message: string) => mixed; info?: (message: string) => mixed; warn?: (message: string) => mixed; error?: (message: string) => mixed; |}, request?: RequestRequestOptions, timeZone?: string, [option: string]: any, |}): this; static VERSION: string; actions: {| [key: string]: any |}, activity: {| [key: string]: any |}, apps: {| [key: string]: any |}, auth: (...args: Array) => Promise<{| [key: string]: any |}>, billing: {| [key: string]: any |}, checks: {| [key: string]: any |}, codeScanning: {| [key: string]: any |}, codesOfConduct: {| [key: string]: any |}, emojis: {| [key: string]: any |}, enterpriseAdmin: {| [key: string]: any |}, gists: {| [key: string]: any |}, git: {| [key: string]: any |}, gitignore: {| [key: string]: any |}, graphql: (...args: Array) => any, hook: (...args: Array) => any, interactions: {| [key: string]: any |}, issues: {| [key: string]: any |}, licenses: {| [key: string]: any |}, log:{| [key: string]: any |}, markdown: {| [key: string]: any |}, meta: {| [key: string]: any |}, migrations: {| [key: string]: any |}, orgs: {| [key: string]: any |}, packages: {| [key: string]: any |}, paginate: (...args: Array) => any, projects: {| [key: string]: any |}, pulls: {| [key: string]: any |}, rateLimit: {| [key: string]: any |}, reactions: {| [key: string]: any |}, repos: { getContent: ({| owner: string, repo: string, path?: string, ref?: string, |}) => Promise<{| headers: {| [key: string]: any |}, status: number, url: string, data: Array<{| download_url: any, git_url: string, html_url: string, name: string, path: string, sha: string, size: number, type: string, url: string, _links: {| git: string, html: string, self: string, |} |}>, |}>, /** * This returns a list of releases, which does not include regular Git tags that have not been associated with a release. To get a list of Git tags, use the Repository Tags API. * * Information about published releases are available to everyone. Only users with push access will receive listings for draft releases. */ listReleases: ({| /** * The account owner of the repository. The name is not case sensitive. */ owner: string, /** * The name of the repository. The name is not case sensitive. */ repo: string, /** * The number of results per page (max 100). */ page?: number, /** * Page number of the results to fetch. */ per_page?: number, |}) => Promise<{| headers: {| [key: string]: any |}, status: number, url: string, data: Array<{| url: string, assets_url: string, upload_url: string, html_url: string, id: number, author: {| login: string, id: number, node_id: string, avatar_url: string, gravatar_id: string, url: string, html_url: string, followers_url: string, following_url: string, gists_url: string, starred_url: string, subscriptions_url: string, organizations_url: string, repos_url: string, events_url: string, received_events_url: string, type: string, site_admin: boolean, |}, node_id: string, tag_name: string, target_commitish: string, name: any, draft: boolean, prerelease: boolean, created_at: string, published_at: string, assets: Array, tarball_url: string, zipball_url: string, body: string, |}>, |}>, [key: string]: any, }, request: (...args: Array) => any, rest: {| [key: string]: any |}, search: {| [key: string]: any |}, secretScanning: {| [key: string]: any |}, teams: {| [key: string]: any |}, users: {| [key: string]: any |}, } declare module.exports: {| Octokit: typeof Octokit, |}; } ================================================ FILE: flow-typed/npm/colors_v1.x.x.js ================================================ // flow-typed signature: 6c56e55f6af24f47c33f50f10270785f // flow-typed version: 590676b089/colors_v1.x.x/flow_>=v0.104.x declare module "colors" { declare type Color = { (text: string): string, strip: Color, stripColors: Color, black: Color, red: Color, green: Color, yellow: Color, blue: Color, magenta: Color, cyan: Color, white: Color, gray: Color, grey: Color, bgBlack: Color, bgRed: Color, bgGreen: Color, bgYellow: Color, bgBlue: Color, bgMagenta: Color, bgCyan: Color, bgWhite: Color, reset: Color, bold: Color, dim: Color, italic: Color, underline: Color, inverse: Color, hidden: Color, strikethrough: Color, rainbow: Color, zebra: Color, america: Color, trap: Color, random: Color, zalgo: Color, ... }; declare module.exports: { enabled: boolean, themes: {...}, enable(): void, disable(): void, setTheme(theme: {...}): void, strip: Color, stripColors: Color, black: Color, red: Color, green: Color, yellow: Color, blue: Color, magenta: Color, cyan: Color, white: Color, gray: Color, grey: Color, bgBlack: Color, bgRed: Color, bgGreen: Color, bgYellow: Color, bgBlue: Color, bgMagenta: Color, bgCyan: Color, bgWhite: Color, reset: Color, bold: Color, dim: Color, italic: Color, underline: Color, inverse: Color, hidden: Color, strikethrough: Color, rainbow: Color, zebra: Color, america: Color, trap: Color, random: Color, zalgo: Color, ... }; } declare module "colors/safe" { declare module.exports: $Exports<"colors">; } ================================================ FILE: flow-typed/npm/cross-env_vx.x.x.js ================================================ // flow-typed signature: d88f07e71439b946a3c634907a30e9c7 // flow-typed version: <>/cross-env_v^7.0.3/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * 'cross-env' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'cross-env' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'cross-env/src/bin/cross-env-shell' { declare module.exports: any; } declare module 'cross-env/src/bin/cross-env' { declare module.exports: any; } declare module 'cross-env/src/command' { declare module.exports: any; } declare module 'cross-env/src' { declare module.exports: any; } declare module 'cross-env/src/is-windows' { declare module.exports: any; } declare module 'cross-env/src/variable' { declare module.exports: any; } // Filename aliases declare module 'cross-env/src/bin/cross-env-shell.js' { declare module.exports: $Exports<'cross-env/src/bin/cross-env-shell'>; } declare module 'cross-env/src/bin/cross-env.js' { declare module.exports: $Exports<'cross-env/src/bin/cross-env'>; } declare module 'cross-env/src/command.js' { declare module.exports: $Exports<'cross-env/src/command'>; } declare module 'cross-env/src/index' { declare module.exports: $Exports<'cross-env/src'>; } declare module 'cross-env/src/index.js' { declare module.exports: $Exports<'cross-env/src'>; } declare module 'cross-env/src/is-windows.js' { declare module.exports: $Exports<'cross-env/src/is-windows'>; } declare module 'cross-env/src/variable.js' { declare module.exports: $Exports<'cross-env/src/variable'>; } ================================================ FILE: flow-typed/npm/flow-bin_v0.x.x.js ================================================ // flow-typed signature: 28fdff7f110e1c75efab63ff205dda30 // flow-typed version: c6154227d1/flow-bin_v0.x.x/flow_>=v0.104.x declare module "flow-bin" { declare module.exports: string; } ================================================ FILE: flow-typed/npm/fs-extra_v8.x.x.js ================================================ // flow-typed signature: beb4c73787fb04b445ce22aee439eed9 // flow-typed version: d81afd5307/fs-extra_v8.x.x/flow_>=v0.104.x declare module "fs-extra" { import type { Stats, ReadStream, WriteStream } from "fs"; import typeof fsTypes from "fs"; declare type SymlinkType = "dir" | "file"; declare type FsSymlinkType = "dir" | "file" | "junction"; declare type CopyFilterSync = (src: string, dest: string) => boolean; declare type CopyFilterAsync = ( src: string, dest: string ) => Promise; declare type CopyOptions = { dereference?: boolean, overwrite?: boolean, preserveTimestamps?: boolean, errorOnExist?: boolean, recursive?: boolean, ... }; declare type CopyOptionsAync = CopyOptions & { filter?: CopyFilterSync | CopyFilterAsync, ... }; declare type CopyOptionsSync = CopyOptions & { filter?: CopyFilterSync, ... }; declare type MoveOptions = { overwrite?: boolean, limit?: number, ... }; declare type ReadOptions = { throws?: boolean, fs?: Object, reviver?: any, encoding?: string, flag?: string, ... }; declare type WriteFileOptions = { encoding?: string, flag?: string, mode?: number, ... }; declare type WriteOptions = WriteFileOptions & { fs?: Object, replacer?: any, spaces?: number | string, EOL?: string, ... }; declare type ReadResult = { bytesRead: number, buffer: Buffer, ... }; declare type WriteResult = { bytesWritten: number, buffer: Buffer, ... }; declare type ReadStreamOptions = { bufferSize?: number, encoding?: string, fd?: number, flags?: string, mode?: number, ... } declare type WriteStreamOptions = { encoding?: string, flags?: string, string?: string, ... } declare function copy( src: string, dest: string, options?: CopyOptionsAync ): Promise; declare function copy( src: string, dest: string, callback: (err: Error) => void ): void; declare function copy( src: string, dest: string, options: CopyOptionsAync, callback: (err: Error) => void ): void; declare function copySync( src: string, dest: string, options?: CopyOptionsSync ): void; declare function move( src: string, dest: string, options?: MoveOptions ): Promise; declare function move( src: string, dest: string, callback: (err: Error) => void ): void; declare function move( src: string, dest: string, options: MoveOptions, callback: (err: Error) => void ): void; declare function moveSync( src: string, dest: string, options?: MoveOptions ): void; declare function createFile(file: string): Promise; declare function createFile( file: string, callback: (err: Error) => void ): void; declare function createFileSync(file: string): void; declare function createReadStream(path: string, options?: ReadStreamOptions): ReadStream; declare function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream; declare function ensureDir(path: string): Promise; declare function ensureDir( path: string, callback: (err: Error) => void ): void; declare function ensureDirSync(path: string): void; declare function exists(path: string): Promise; declare function exists(path: string, callback?: (exists: boolean) => void): void; declare function mkdirs(dir: string): Promise; declare function mkdirs( dir: string, callback: (err: Error) => void ): void; declare function mkdirsSync(dir: string): void; declare function mkdirp(dir: string): Promise; declare function mkdirp( dir: string, callback: (err: Error) => void ): void; declare function mkdirpSync(dir: string): void; declare function outputFile( file: string, data: any, options?: WriteFileOptions | string ): Promise; declare function outputFile( file: string, data: any, callback: (err: Error) => void ): void; declare function outputFile( file: string, data: any, options: WriteFileOptions | string, callback: (err: Error) => void ): void; declare function outputFileSync( file: string, data: any, options?: WriteFileOptions | string ): void; declare function readJson( file: string, options?: ReadOptions ): Promise; declare function readJson( file: string, callback: (err: Error, jsonObject: any) => void ): void; declare function readJson( file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void ): void; declare function readJSON( file: string, options?: ReadOptions ): Promise; declare function readJSON( file: string, callback: (err: Error, jsonObject: any) => void ): void; declare function readJSON( file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void ): void; declare function readJsonSync( file: string, options?: ReadOptions ): any; declare function readJSONSync( file: string, options?: ReadOptions ): any; declare function remove(dir: string): Promise; declare function remove( dir: string, callback: (err: Error) => void ): void; declare function removeSync(dir: string): void; declare function outputJson( file: string, data: any, options?: WriteOptions ): Promise; declare function outputJSON( file: string, data: any, options?: WriteOptions ): Promise; declare function outputJson( file: string, data: any, options: WriteOptions, callback: (err: Error) => void ): void; declare function outputJSON( file: string, data: any, options: WriteOptions, callback: (err: Error) => void ): void; declare function outputJson( file: string, data: any, callback: (err: Error) => void ): void; declare function outputJSON( file: string, data: any, callback: (err: Error) => void ): void; declare function outputJsonSync( file: string, data: any, options?: WriteOptions ): void; declare function outputJSONSync( file: string, data: any, options?: WriteOptions ): void; declare function writeJSON( file: string, object: any, options?: WriteOptions ): Promise; declare function writeJSON( file: string, object: any, callback: (err: Error) => void ): void; declare function writeJSON( file: string, object: any, options: WriteOptions, callback: (err: Error) => void ): void; declare function writeJson( file: string, object: any, options?: WriteOptions ): Promise; declare function writeJson( file: string, object: any, callback: (err: Error) => void ): void; declare function writeJson( file: string, object: any, options: WriteOptions, callback: (err: Error) => void ): void; declare function writeJsonSync( file: string, object: any, options?: WriteOptions ): void; declare function writeJSONSync( file: string, object: any, options?: WriteOptions ): void; declare function ensureFile(path: string): Promise; declare function ensureFile( path: string, callback: (err: Error) => void ): void; declare function ensureFileSync(path: string): void; declare function ensureLink(src: string, dest: string): Promise; declare function ensureLink( src: string, dest: string, callback: (err: Error) => void ): void; declare function ensureLinkSync(src: string, dest: string): void; declare function ensureSymlink( src: string, dest: string, type?: SymlinkType ): Promise; declare function ensureSymlink( src: string, dest: string, type: SymlinkType, callback: (err: Error) => void ): void; declare function ensureSymlink( src: string, dest: string, callback: (err: Error) => void ): void; declare function ensureSymlinkSync( src: string, dest: string, type?: SymlinkType ): void; declare function emptyDir(path: string): Promise; declare function emptyDir( path: string, callback: (err: Error) => void ): void; declare function emptyDirSync(path: string): void; declare function pathExists(path: string): Promise; declare function pathExists( path: string, callback: (err: Error, exists: boolean) => void ): void; declare function pathExistsSync(path: string): boolean; declare function access( path: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function access( path: string | Buffer, mode: number, callback: (err: ErrnoError) => void ): void; declare function access( path: string | Buffer, mode?: number ): Promise; declare function appendFile( file: string | Buffer | number, data: any, options: { encoding?: string, mode?: number | string, flag?: string, ... }, callback: (err: ErrnoError) => void ): void; declare function appendFile( file: string | Buffer | number, data: any, callback: (err: ErrnoError) => void ): void; declare function appendFile( file: string | Buffer | number, data: any, options?: { encoding?: string, mode?: number | string, flag?: string, ... } ): Promise; declare function chmod( path: string | Buffer, mode: string | number, callback: (err: ErrnoError) => void ): void; declare function chmod( path: string | Buffer, mode: string | number ): Promise; declare function chown( path: string | Buffer, uid: number, gid: number ): Promise; declare function chown( path: string | Buffer, uid: number, gid: number, callback: (err: ErrnoError) => void ): void; declare function close( fd: number, callback: (err: ErrnoError) => void ): void; declare function close(fd: number): Promise; declare function fchmod( fd: number, mode: string | number, callback: (err: ErrnoError) => void ): void; declare function fchmod( fd: number, mode: string | number ): Promise; declare function fchown( fd: number, uid: number, gid: number, callback: (err: ErrnoError) => void ): void; declare function fchown( fd: number, uid: number, gid: number ): Promise; declare function fdatasync(fd: number, callback: () => void): void; declare function fdatasync(fd: number): Promise; declare function fstat( fd: number, callback: (err: ErrnoError, stats: Stats) => any ): void; declare function fstat(fd: number): Promise; declare function fsync( fd: number, callback: (err: ErrnoError) => void ): void; declare function fsync(fd: number): Promise; declare function ftruncate( fd: number, callback: (err: ErrnoError) => void ): void; declare function ftruncate( fd: number, len: number, callback: (err: ErrnoError) => void ): void; declare function ftruncate(fd: number, len?: number): Promise; declare function futimes( fd: number, atime: number, mtime: number, callback: (err: ErrnoError) => void ): void; declare function futimes( fd: number, atime: Date, mtime: Date, callback: (err: ErrnoError) => void ): void; declare function futimes( fd: number, atime: number, mtime: number ): Promise; declare function futimes( fd: number, atime: Date, mtime: Date ): Promise; declare function lchown( path: string | Buffer, uid: number, gid: number, callback: (err: ErrnoError) => void ): void; declare function lchown( path: string | Buffer, uid: number, gid: number ): Promise; declare function link( srcpath: string | Buffer, dstpath: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function link( srcpath: string | Buffer, dstpath: string | Buffer ): Promise; declare function lstat( path: string | Buffer, callback: (err: ErrnoError, stats: Stats) => any ): void; declare function lstat(path: string | Buffer): Promise; declare function mkdir( path: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function mkdir( path: string | Buffer, mode: number | string, callback: (err: ErrnoError) => void ): void; declare function mkdir(path: string | Buffer): Promise; declare function open( path: string | Buffer, flags: string | number, callback: (err: ErrnoError, fd: number) => void ): void; declare function open( path: string | Buffer, flags: string | number, mode: number, callback: (err: ErrnoError, fd: number) => void ): void; declare function open( path: string | Buffer, flags: string | number, mode?: number ): Promise; declare function read( fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: ErrnoError, bytesRead: number, buffer: Buffer) => void ): void; declare function read( fd: number, buffer: Buffer, offset: number, length: number, position: number | null ): Promise; declare function readFile( file: string | Buffer | number, callback: (err: ErrnoError, data: Buffer) => void ): void; declare function readFile( file: string | Buffer | number, encoding: string, callback: (err: ErrnoError, data: string) => void ): void; declare function readFile( file: string | Buffer | number, options: { flag?: string, ... } | { encoding: string, flag?: string, ... }, callback: (err: ErrnoError, data: Buffer) => void ): void; declare function readFile( file: string | Buffer | number, options: { flag?: string, ... } | { encoding: string, flag?: string, ... }, ): Promise; declare function readFile( file: string | Buffer | number, encoding: string ): Promise; declare function readFile( file: string | Buffer | number ): Promise; declare function readdir( path: string | Buffer, callback: (err: ErrnoError, files: string[]) => void ): void; declare function readdir(path: string | Buffer): Promise; declare function readlink( path: string | Buffer, callback: (err: ErrnoError, linkString: string) => any ): void; declare function readlink(path: string | Buffer): Promise; declare function realpath( path: string | Buffer, callback: (err: ErrnoError, resolvedPath: string) => any ): void; declare function realpath( path: string | Buffer, cache: { [path: string]: string, ... }, callback: (err: ErrnoError, resolvedPath: string) => any ): void; declare function realpath( path: string | Buffer, cache?: { [path: string]: string, ... } ): Promise; declare function rename( oldPath: string, newPath: string, callback: (err: ErrnoError) => void ): void; declare function rename( oldPath: string, newPath: string ): Promise; declare function rmdir( path: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function rmdir(path: string | Buffer): Promise; declare function stat( path: string | Buffer, callback: (err: ErrnoError, stats: Stats) => any ): void; declare function stat(path: string | Buffer): Promise; declare function statSync(path: string): Stats; declare function symlink( srcpath: string | Buffer, dstpath: string | Buffer, type: FsSymlinkType | void, callback: (err: ErrnoError) => void ): void; declare function symlink( srcpath: string | Buffer, dstpath: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function symlink( srcpath: string | Buffer, dstpath: string | Buffer, type?: FsSymlinkType ): Promise; declare function truncate( path: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function truncate( path: string | Buffer, len: number, callback: (err: ErrnoError) => void ): void; declare function truncate( path: string | Buffer, len?: number ): Promise; declare function unlink( path: string | Buffer, callback: (err: ErrnoError) => void ): void; declare function unlink(path: string | Buffer): Promise; declare function utimes( path: string | Buffer, atime: number, mtime: number, callback: (err: ErrnoError) => void ): void; declare function utimes( path: string | Buffer, atime: Date, mtime: Date, callback: (err: ErrnoError) => void ): void; declare function utimes( path: string | Buffer, atime: number, mtime: number ): Promise; declare function utimes( path: string | Buffer, atime: Date, mtime: Date ): Promise; declare function write( fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: ErrnoError, written: number, buffer: Buffer) => void ): void; declare function write( fd: number, buffer: Buffer, offset: number, length: number, callback: (err: ErrnoError, written: number, buffer: Buffer) => void ): void; declare function write( fd: number, data: any, callback: (err: ErrnoError, written: number, str: string) => void ): void; declare function write( fd: number, data: any, offset: number, callback: (err: ErrnoError, written: number, str: string) => void ): void; declare function write( fd: number, data: any, offset: number, encoding: string, callback: (err: ErrnoError, written: number, str: string) => void ): void; declare function write( fd: number, buffer: Buffer, offset: number, length: number, position?: number | null ): Promise; declare function write( fd: number, data: any, offset: number, encoding?: string ): Promise; declare function writeFile( file: string | Buffer | number, data: any, callback: (err: ErrnoError) => void ): void; declare function writeFile( file: string | Buffer | number, data: any, options?: WriteFileOptions | string ): Promise; declare function writeFile( file: string | Buffer | number, data: any, options: WriteFileOptions | string, callback: (err: ErrnoError) => void ): void; declare function mkdtemp(prefix: string): Promise; declare function mkdtemp( prefix: string, callback: (err: ErrnoError, folder: string) => void ): void; declare module.exports: {| ...fsTypes; access: typeof access; appendFile: typeof appendFile; chmod: typeof chmod; chown: typeof chown; close: typeof close; copy: typeof copy; copySync: typeof copySync; createFile: typeof createFile; createFileSync: typeof createFileSync; createReadStream: typeof createReadStream; createWriteStream: typeof createWriteStream; emptyDir: typeof emptyDir; emptyDirSync: typeof emptyDirSync; ensureDir: typeof ensureDir; ensureDirSync: typeof ensureDirSync; ensureFile: typeof ensureFile; ensureFileSync: typeof ensureFileSync; ensureLink: typeof ensureLink; ensureLinkSync: typeof ensureLinkSync; ensureSymlink: typeof ensureSymlink; ensureSymlinkSync: typeof ensureSymlinkSync; exists: typeof exists; fchmod: typeof fchmod; fchown: typeof fchown; fdatasync: typeof fdatasync; fstat: typeof fstat; fsync: typeof fsync; ftruncate: typeof ftruncate; futimes: typeof futimes; lchown: typeof lchown; link: typeof link; lstat: typeof lstat; mkdir: typeof mkdir; mkdirp: typeof mkdirp; mkdirpSync: typeof mkdirpSync; mkdirs: typeof mkdirs; mkdirsSync: typeof mkdirsSync; mkdtemp: typeof mkdtemp; move: typeof move; moveSync: typeof moveSync; open: typeof open; outputFile: typeof outputFile; outputFileSync: typeof outputFileSync; outputJson: typeof outputJson; outputJSON: typeof outputJSON; outputJsonSync: typeof outputJsonSync; outputJSONSync: typeof outputJSONSync; pathExists: typeof pathExists; pathExistsSync: typeof pathExistsSync; read: typeof read; readdir: typeof readdir; readFile: typeof readFile; readJson: typeof readJson; readJSON: typeof readJSON; readJsonSync: typeof readJsonSync; readJSONSync: typeof readJSONSync; readlink: typeof readlink; realpath: typeof realpath; remove: typeof remove; removeSync: typeof removeSync; rename: typeof rename; rmdir: typeof rmdir; stat: typeof stat; statSync: typeof statSync; symlink: typeof symlink; truncate: typeof truncate; unlink: typeof unlink; utimes: typeof utimes; write: typeof write; writeFile: typeof writeFile; writeJSON: typeof writeJSON; writeJson: typeof writeJson; writeJsonSync: typeof writeJsonSync; writeJSONSync: typeof writeJSONSync; |}; } ================================================ FILE: flow-typed/npm/glob_v7.x.x.js ================================================ // flow-typed signature: d2a519d7d007e9ba3e5bf2ac3ff76eca // flow-typed version: f243e51ed7/glob_v7.x.x/flow_>=v0.104.x declare module "glob" { declare type MinimatchOptions = {| debug?: boolean, nobrace?: boolean, noglobstar?: boolean, dot?: boolean, noext?: boolean, nocase?: boolean, nonull?: boolean, matchBase?: boolean, nocomment?: boolean, nonegate?: boolean, flipNegate?: boolean |}; declare type Options = {| ...MinimatchOptions, cwd?: string, root?: string, nomount?: boolean, mark?: boolean, nosort?: boolean, stat?: boolean, silent?: boolean, strict?: boolean, cache?: { [path: string]: boolean | "DIR" | "FILE" | $ReadOnlyArray, ... }, statCache?: { [path: string]: boolean | { isDirectory(): boolean, ... } | void, ... }, symlinks?: { [path: string]: boolean | void, ... }, realpathCache?: { [path: string]: string, ... }, sync?: boolean, nounique?: boolean, nodir?: boolean, ignore?: string | $ReadOnlyArray, follow?: boolean, realpath?: boolean, absolute?: boolean |}; /** * Called when an error occurs, or matches are found * err * matches: filenames found matching the pattern */ declare type CallBack = (err: ?Error, matches: Array) => void; declare class Glob extends events$EventEmitter { constructor(pattern: string): this; constructor(pattern: string, callback: CallBack): this; constructor(pattern: string, options: Options, callback: CallBack): this; minimatch: {...}; options: Options; aborted: boolean; cache: { [path: string]: boolean | "DIR" | "FILE" | $ReadOnlyArray, ... }; statCache: { [path: string]: boolean | { isDirectory(): boolean, ... } | void, ... }; symlinks: { [path: string]: boolean | void, ... }; realpathCache: { [path: string]: string, ... }; found: Array; pause(): void; resume(): void; abort(): void; } declare class GlobModule { Glob: Class; (pattern: string, callback: CallBack): void; (pattern: string, options: Options, callback: CallBack): void; hasMagic(pattern: string, options?: Options): boolean; sync(pattern: string, options?: Options): Array; } declare module.exports: GlobModule; } ================================================ FILE: flow-typed/npm/husky_vx.x.x.js ================================================ // flow-typed signature: 879510e2b63c9ed0a1bead509d75e31c // flow-typed version: <>/husky_v^7.0.4/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * 'husky' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'husky' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'husky/lib/bin' { declare module.exports: any; } declare module 'husky/lib' { declare module.exports: any; } // Filename aliases declare module 'husky/lib/bin.js' { declare module.exports: $Exports<'husky/lib/bin'>; } declare module 'husky/lib/index' { declare module.exports: $Exports<'husky/lib'>; } declare module 'husky/lib/index.js' { declare module.exports: $Exports<'husky/lib'>; } ================================================ FILE: flow-typed/npm/jest_v29.x.x.js ================================================ // flow-typed signature: 0e64c840aab684c37415b655ddbf8ce1 // flow-typed version: 02d4f1d2c5/jest_v29.x.x/flow_>=v0.134.x <=v0.200.x type JestMockFn, TReturn> = { (...args: TArguments): TReturn, /** * An object for introspecting mock calls */ mock: { /** * An array that represents all calls that have been made into this mock * function. Each call is represented by an array of arguments that were * passed during the call. */ calls: Array, /** * An array containing the call arguments of the last call that was made * to this mock function. If the function was not called, it will return * undefined. */ lastCall: TArguments, /** * An array that contains all the object instances that have been * instantiated from this mock function. */ instances: Array, /** * An array that contains all the object results that have been * returned by this mock function call */ results: Array<{ isThrow: boolean, value: TReturn, ... }>, ... }, /** * Resets all information stored in the mockFn.mock.calls and * mockFn.mock.instances arrays. Often this is useful when you want to clean * up a mock's usage data between two assertions. */ mockClear(): void, /** * Resets all information stored in the mock. This is useful when you want to * completely restore a mock back to its initial state. */ mockReset(): void, /** * Removes the mock and restores the initial implementation. This is useful * when you want to mock functions in certain test cases and restore the * original implementation in others. Beware that mockFn.mockRestore only * works when mock was created with jest.spyOn. Thus you have to take care of * restoration yourself when manually assigning jest.fn(). */ mockRestore(): void, /** * Accepts a function that should be used as the implementation of the mock. * The mock itself will still record all calls that go into and instances * that come from itself -- the only difference is that the implementation * will also be executed when the mock is called. */ mockImplementation( fn: (...args: TArguments) => TReturn ): JestMockFn, /** * Accepts a function that will be used as an implementation of the mock for * one call to the mocked function. Can be chained so that multiple function * calls produce different results. */ mockImplementationOnce( fn: (...args: TArguments) => TReturn ): JestMockFn, /** * Accepts a string to use in test result output in place of "jest.fn()" to * indicate which mock function is being referenced. */ mockName(name: string): JestMockFn, /** * Just a simple sugar function for returning `this` */ mockReturnThis(): void, /** * Accepts a value that will be returned whenever the mock function is called. */ mockReturnValue(value: TReturn): JestMockFn, /** * Sugar for only returning a value once inside your mock */ mockReturnValueOnce(value: TReturn): JestMockFn, /** * Sugar for jest.fn().mockImplementation(() => Promise.resolve(value)) */ mockResolvedValue(value: TReturn): JestMockFn>, /** * Sugar for jest.fn().mockImplementationOnce(() => Promise.resolve(value)) */ mockResolvedValueOnce( value: TReturn ): JestMockFn>, /** * Sugar for jest.fn().mockImplementation(() => Promise.reject(value)) */ mockRejectedValue(value: TReturn): JestMockFn>, /** * Sugar for jest.fn().mockImplementationOnce(() => Promise.reject(value)) */ mockRejectedValueOnce(value: TReturn): JestMockFn>, ... }; type JestAsymmetricEqualityType = { /** * A custom Jasmine equality tester */ asymmetricMatch(value: mixed): boolean, ... }; type JestCallsType = { allArgs(): mixed, all(): mixed, any(): boolean, count(): number, first(): mixed, mostRecent(): mixed, reset(): void, ... }; type JestClockType = { install(): void, mockDate(date: Date): void, tick(milliseconds?: number): void, uninstall(): void, ... }; type JestMatcherResult = { message?: string | (() => string), pass: boolean, ... }; type JestMatcher = ( received: any, ...actual: Array ) => JestMatcherResult | Promise; type JestPromiseType = { /** * Use rejects to unwrap the reason of a rejected promise so any other * matcher can be chained. If the promise is fulfilled the assertion fails. */ rejects: JestExpectType, /** * Use resolves to unwrap the value of a fulfilled promise so any other * matcher can be chained. If the promise is rejected the assertion fails. */ resolves: JestExpectType, ... }; /** * Jest allows functions and classes to be used as test names in test() and * describe() */ type JestTestName = string | Function; type FakeableAPI = | 'Date' | 'hrtime' | 'nextTick' | 'performance' | 'queueMicrotask' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'setTimeout' | 'clearTimeout'; type FakeTimersConfig = { advanceTimers?: boolean | number, doNotFake?: Array, now?: number | Date, timerLimit?: number, legacyFakeTimers?: boolean, ... }; /** * Plugin: jest-styled-components */ type JestStyledComponentsMatcherValue = | string | JestAsymmetricEqualityType | RegExp | typeof undefined; type JestStyledComponentsMatcherOptions = { media?: string, modifier?: string, supports?: string, ... }; type JestStyledComponentsMatchersType = { toHaveStyleRule( property: string, value: JestStyledComponentsMatcherValue, options?: JestStyledComponentsMatcherOptions ): void, ... }; /** * Plugin: jest-enzyme */ type EnzymeMatchersType = { // 5.x toBeEmpty(): void, toBePresent(): void, // 6.x toBeChecked(): void, toBeDisabled(): void, toBeEmptyRender(): void, toContainMatchingElement(selector: string): void, toContainMatchingElements(n: number, selector: string): void, toContainExactlyOneMatchingElement(selector: string): void, toContainReact(element: React$Element): void, toExist(): void, toHaveClassName(className: string): void, toHaveHTML(html: string): void, toHaveProp: ((propKey: string, propValue?: any) => void) & ((props: { ... }) => void), toHaveRef(refName: string): void, toHaveState: ((stateKey: string, stateValue?: any) => void) & ((state: { ... }) => void), toHaveStyle: ((styleKey: string, styleValue?: any) => void) & ((style: { ... }) => void), toHaveTagName(tagName: string): void, toHaveText(text: string): void, toHaveValue(value: any): void, toIncludeText(text: string): void, toMatchElement( element: React$Element, options?: {| ignoreProps?: boolean, verbose?: boolean |} ): void, toMatchSelector(selector: string): void, // 7.x toHaveDisplayName(name: string): void, ... }; // DOM testing library extensions (jest-dom) // https://github.com/testing-library/jest-dom type DomTestingLibraryType = { /** * @deprecated */ toBeInTheDOM(container?: HTMLElement): void, // 4.x toBeInTheDocument(): void, toBeVisible(): void, toBeEmpty(): void, toBeDisabled(): void, toBeEnabled(): void, toBeInvalid(): void, toBeRequired(): void, toBeValid(): void, toContainElement(element: HTMLElement | null): void, toContainHTML(htmlText: string): void, toHaveAttribute(attr: string, value?: any): void, toHaveClass(...classNames: string[]): void, toHaveFocus(): void, toHaveFormValues(expectedValues: { [name: string]: any, ... }): void, toHaveStyle(css: string | { [name: string]: any, ... }): void, toHaveTextContent( text: string | RegExp, options?: {| normalizeWhitespace: boolean |} ): void, toHaveValue(value?: string | string[] | number): void, // 5.x toHaveDisplayValue(value: string | string[]): void, toBeChecked(): void, toBeEmptyDOMElement(): void, toBePartiallyChecked(): void, toHaveDescription(text: string | RegExp): void, ... }; // Jest JQuery Matchers: https://github.com/unindented/custom-jquery-matchers type JestJQueryMatchersType = { toExist(): void, toHaveLength(len: number): void, toHaveId(id: string): void, toHaveClass(className: string): void, toHaveTag(tag: string): void, toHaveAttr(key: string, val?: any): void, toHaveProp(key: string, val?: any): void, toHaveText(text: string | RegExp): void, toHaveData(key: string, val?: any): void, toHaveValue(val: any): void, toHaveCss(css: { [key: string]: any, ... }): void, toBeChecked(): void, toBeDisabled(): void, toBeEmpty(): void, toBeHidden(): void, toBeSelected(): void, toBeVisible(): void, toBeFocused(): void, toBeInDom(): void, toBeMatchedBy(sel: string): void, toHaveDescendant(sel: string): void, toHaveDescendantWithText(sel: string, text: string | RegExp): void, ... }; // Jest Extended Matchers: https://github.com/jest-community/jest-extended type JestExtendedMatchersType = { /** * Note: Currently unimplemented * Passing assertion * * @param {String} message */ // pass(message: string): void; /** * Note: Currently unimplemented * Failing assertion * * @param {String} message */ // fail(message: string): void; /** * Use .toBeEmpty when checking if a String '', Array [] or Object {} is empty. */ toBeEmpty(): void, /** * Use .toBeOneOf when checking if a value is a member of a given Array. * @param {Array.<*>} members */ toBeOneOf(members: any[]): void, /** * Use `.toBeNil` when checking a value is `null` or `undefined`. */ toBeNil(): void, /** * Use `.toSatisfy` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean`. * @param {Function} predicate */ toSatisfy(predicate: (n: any) => boolean): void, /** * Use `.toBeArray` when checking if a value is an `Array`. */ toBeArray(): void, /** * Use `.toBeArrayOfSize` when checking if a value is an `Array` of size x. * @param {Number} x */ toBeArrayOfSize(x: number): void, /** * Use `.toIncludeAllMembers` when checking if an `Array` contains all of the same members of a given set. * @param {Array.<*>} members */ toIncludeAllMembers(members: any[]): void, /** * Use `.toIncludeAnyMembers` when checking if an `Array` contains any of the members of a given set. * @param {Array.<*>} members */ toIncludeAnyMembers(members: any[]): void, /** * Use `.toSatisfyAll` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean` for all values in an array. * @param {Function} predicate */ toSatisfyAll(predicate: (n: any) => boolean): void, /** * Use `.toBeBoolean` when checking if a value is a `Boolean`. */ toBeBoolean(): void, /** * Use `.toBeTrue` when checking a value is equal (===) to `true`. */ toBeTrue(): void, /** * Use `.toBeFalse` when checking a value is equal (===) to `false`. */ toBeFalse(): void, /** * Use .toBeDate when checking if a value is a Date. */ toBeDate(): void, /** * Use `.toBeFunction` when checking if a value is a `Function`. */ toBeFunction(): void, /** * Use `.toHaveBeenCalledBefore` when checking if a `Mock` was called before another `Mock`. * * Note: Required Jest version >22 * Note: Your mock functions will have to be asynchronous to cause the timestamps inside of Jest to occur in a differentJS event loop, otherwise the mock timestamps will all be the same * * @param {Mock} mock */ toHaveBeenCalledBefore(mock: JestMockFn): void, /** * Use `.toBeNumber` when checking if a value is a `Number`. */ toBeNumber(): void, /** * Use `.toBeNaN` when checking a value is `NaN`. */ toBeNaN(): void, /** * Use `.toBeFinite` when checking if a value is a `Number`, not `NaN` or `Infinity`. */ toBeFinite(): void, /** * Use `.toBePositive` when checking if a value is a positive `Number`. */ toBePositive(): void, /** * Use `.toBeNegative` when checking if a value is a negative `Number`. */ toBeNegative(): void, /** * Use `.toBeEven` when checking if a value is an even `Number`. */ toBeEven(): void, /** * Use `.toBeOdd` when checking if a value is an odd `Number`. */ toBeOdd(): void, /** * Use `.toBeWithin` when checking if a number is in between the given bounds of: start (inclusive) and end (exclusive). * * @param {Number} start * @param {Number} end */ toBeWithin(start: number, end: number): void, /** * Use `.toBeObject` when checking if a value is an `Object`. */ toBeObject(): void, /** * Use `.toContainKey` when checking if an object contains the provided key. * * @param {String} key */ toContainKey(key: string): void, /** * Use `.toContainKeys` when checking if an object has all of the provided keys. * * @param {Array.} keys */ toContainKeys(keys: string[]): void, /** * Use `.toContainAllKeys` when checking if an object only contains all of the provided keys. * * @param {Array.} keys */ toContainAllKeys(keys: string[]): void, /** * Use `.toContainAnyKeys` when checking if an object contains at least one of the provided keys. * * @param {Array.} keys */ toContainAnyKeys(keys: string[]): void, /** * Use `.toContainValue` when checking if an object contains the provided value. * * @param {*} value */ toContainValue(value: any): void, /** * Use `.toContainValues` when checking if an object contains all of the provided values. * * @param {Array.<*>} values */ toContainValues(values: any[]): void, /** * Use `.toContainAllValues` when checking if an object only contains all of the provided values. * * @param {Array.<*>} values */ toContainAllValues(values: any[]): void, /** * Use `.toContainAnyValues` when checking if an object contains at least one of the provided values. * * @param {Array.<*>} values */ toContainAnyValues(values: any[]): void, /** * Use `.toContainEntry` when checking if an object contains the provided entry. * * @param {Array.} entry */ toContainEntry(entry: [string, string]): void, /** * Use `.toContainEntries` when checking if an object contains all of the provided entries. * * @param {Array.>} entries */ toContainEntries(entries: [string, string][]): void, /** * Use `.toContainAllEntries` when checking if an object only contains all of the provided entries. * * @param {Array.>} entries */ toContainAllEntries(entries: [string, string][]): void, /** * Use `.toContainAnyEntries` when checking if an object contains at least one of the provided entries. * * @param {Array.>} entries */ toContainAnyEntries(entries: [string, string][]): void, /** * Use `.toBeExtensible` when checking if an object is extensible. */ toBeExtensible(): void, /** * Use `.toBeFrozen` when checking if an object is frozen. */ toBeFrozen(): void, /** * Use `.toBeSealed` when checking if an object is sealed. */ toBeSealed(): void, /** * Use `.toBeString` when checking if a value is a `String`. */ toBeString(): void, /** * Use `.toEqualCaseInsensitive` when checking if a string is equal (===) to another ignoring the casing of both strings. * * @param {String} string */ toEqualCaseInsensitive(string: string): void, /** * Use `.toStartWith` when checking if a `String` starts with a given `String` prefix. * * @param {String} prefix */ toStartWith(prefix: string): void, /** * Use `.toEndWith` when checking if a `String` ends with a given `String` suffix. * * @param {String} suffix */ toEndWith(suffix: string): void, /** * Use `.toInclude` when checking if a `String` includes the given `String` substring. * * @param {String} substring */ toInclude(substring: string): void, /** * Use `.toIncludeRepeated` when checking if a `String` includes the given `String` substring the correct number of times. * * @param {String} substring * @param {Number} times */ toIncludeRepeated(substring: string, times: number): void, /** * Use `.toIncludeMultiple` when checking if a `String` includes all of the given substrings. * * @param {Array.} substring */ toIncludeMultiple(substring: string[]): void, ... }; // Diffing snapshot utility for Jest (snapshot-diff) // https://github.com/jest-community/snapshot-diff type SnapshotDiffType = { /** * Compare the difference between the actual in the `expect()` * vs the object inside `valueB` with some extra options. */ toMatchDiffSnapshot( valueB: any, options?: {| expand?: boolean, colors?: boolean, contextLines?: number, stablePatchmarks?: boolean, aAnnotation?: string, bAnnotation?: string, |}, testName?: string ): void, ... }; interface JestExpectType { not: JestExpectType & EnzymeMatchersType & DomTestingLibraryType & JestJQueryMatchersType & JestStyledComponentsMatchersType & JestExtendedMatchersType & SnapshotDiffType; /** * If you have a mock function, you can use .lastCalledWith to test what * arguments it was last called with. */ lastCalledWith(...args: Array): void; /** * toBe just checks that a value is what you expect. It uses === to check * strict equality. */ toBe(value: any): void; /** * Use .toBeCalledWith to ensure that a mock function was called with * specific arguments. */ toBeCalledWith(...args: Array): void; /** * Using exact equality with floating point numbers is a bad idea. Rounding * means that intuitive things fail. */ toBeCloseTo(num: number, delta: any): void; /** * Use .toBeDefined to check that a variable is not undefined. */ toBeDefined(): void; /** * Use .toBeFalsy when you don't care what a value is, you just want to * ensure a value is false in a boolean context. */ toBeFalsy(): void; /** * To compare floating point numbers, you can use toBeGreaterThan. */ toBeGreaterThan(number: number): void; /** * To compare floating point numbers, you can use toBeGreaterThanOrEqual. */ toBeGreaterThanOrEqual(number: number): void; /** * To compare floating point numbers, you can use toBeLessThan. */ toBeLessThan(number: number): void; /** * To compare floating point numbers, you can use toBeLessThanOrEqual. */ toBeLessThanOrEqual(number: number): void; /** * Use .toBeInstanceOf(Class) to check that an object is an instance of a * class. */ toBeInstanceOf(cls: Class<*>): void; /** * .toBeNull() is the same as .toBe(null) but the error messages are a bit * nicer. */ toBeNull(): void; /** * Use .toBeTruthy when you don't care what a value is, you just want to * ensure a value is true in a boolean context. */ toBeTruthy(): void; /** * Use .toBeUndefined to check that a variable is undefined. */ toBeUndefined(): void; /** * Use .toContain when you want to check that an item is in a list. For * testing the items in the list, this uses ===, a strict equality check. */ toContain(item: any): void; /** * Use .toContainEqual when you want to check that an item is in a list. For * testing the items in the list, this matcher recursively checks the * equality of all fields, rather than checking for object identity. */ toContainEqual(item: any): void; /** * Use .toEqual when you want to check that two objects have the same value. * This matcher recursively checks the equality of all fields, rather than * checking for object identity. */ toEqual(value: any): void; /** * Use .toHaveBeenCalled to ensure that a mock function got called. */ toHaveBeenCalled(): void; toBeCalled(): void; /** * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact * number of times. */ toHaveBeenCalledTimes(number: number): void; toBeCalledTimes(number: number): void; /** * */ toHaveBeenNthCalledWith(nthCall: number, ...args: Array): void; nthCalledWith(nthCall: number, ...args: Array): void; /** * */ toHaveReturned(): void; toReturn(): void; /** * */ toHaveReturnedTimes(number: number): void; toReturnTimes(number: number): void; /** * */ toHaveReturnedWith(value: any): void; toReturnWith(value: any): void; /** * */ toHaveLastReturnedWith(value: any): void; lastReturnedWith(value: any): void; /** * */ toHaveNthReturnedWith(nthCall: number, value: any): void; nthReturnedWith(nthCall: number, value: any): void; /** * Use .toHaveBeenCalledWith to ensure that a mock function was called with * specific arguments. */ toHaveBeenCalledWith(...args: Array): void; toBeCalledWith(...args: Array): void; /** * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called * with specific arguments. */ toHaveBeenLastCalledWith(...args: Array): void; lastCalledWith(...args: Array): void; /** * Check that an object has a .length property and it is set to a certain * numeric value. */ toHaveLength(number: number): void; /** * */ toHaveProperty(propPath: string | $ReadOnlyArray, value?: any): void; /** * Use .toMatch to check that a string matches a regular expression or string. */ toMatch(regexpOrString: RegExp | string): void; /** * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object. */ toMatchObject(object: Object | Array): void; /** * Use .toStrictEqual to check that a javascript object matches a subset of the properties of an object. */ toStrictEqual(value: any): void; /** * This ensures that an Object matches the most recent snapshot. */ toMatchSnapshot(propertyMatchers?: any, name?: string): void; /** * This ensures that an Object matches the most recent snapshot. */ toMatchSnapshot(name: string): void; toMatchInlineSnapshot(snapshot?: string): void; toMatchInlineSnapshot(propertyMatchers?: any, snapshot?: string): void; /** * Use .toThrow to test that a function throws when it is called. * If you want to test that a specific error gets thrown, you can provide an * argument to toThrow. The argument can be a string for the error message, * a class for the error, or a regex that should match the error. * * Alias: .toThrowError */ toThrow(message?: string | Error | Class | RegExp): void; toThrowError(message?: string | Error | Class | RegExp): void; /** * Use .toThrowErrorMatchingSnapshot to test that a function throws a error * matching the most recent snapshot when it is called. */ toThrowErrorMatchingSnapshot(): void; toThrowErrorMatchingInlineSnapshot(snapshot?: string): void; } type JestObjectType = { /** * Disables automatic mocking in the module loader. * * After this method is called, all `require()`s will return the real * versions of each module (rather than a mocked version). */ disableAutomock(): JestObjectType, /** * An un-hoisted version of disableAutomock */ autoMockOff(): JestObjectType, /** * Enables automatic mocking in the module loader. */ enableAutomock(): JestObjectType, /** * An un-hoisted version of enableAutomock */ autoMockOn(): JestObjectType, /** * Clears the mock.calls and mock.instances properties of all mocks. * Equivalent to calling .mockClear() on every mocked function. */ clearAllMocks(): JestObjectType, /** * Resets the state of all mocks. Equivalent to calling .mockReset() on every * mocked function. */ resetAllMocks(): JestObjectType, /** * Restores all mocks back to their original value. */ restoreAllMocks(): JestObjectType, /** * Removes any pending timers from the timer system. */ clearAllTimers(): void, /** * Returns the number of fake timers still left to run. */ getTimerCount(): number, /** * Set the current system time used by fake timers. * Simulates a user changing the system clock while your program is running. * It affects the current time but it does not in itself cause * e.g. timers to fire; they will fire exactly as they would have done * without the call to jest.setSystemTime(). */ setSystemTime(now?: number | Date): void, /** * The same as `mock` but not moved to the top of the expectation by * babel-jest. */ doMock(moduleName: string, moduleFactory?: any): JestObjectType, /** * The same as `unmock` but not moved to the top of the expectation by * babel-jest. */ dontMock(moduleName: string): JestObjectType, /** * Returns a new, unused mock function. Optionally takes a mock * implementation. */ fn, TReturn>( implementation?: (...args: TArguments) => TReturn ): JestMockFn, /** * Determines if the given function is a mocked function. */ isMockFunction(fn: Function): boolean, /** * Alias of `createMockFromModule`. */ genMockFromModule(moduleName: string): any, /** * Given the name of a module, use the automatic mocking system to generate a * mocked version of the module for you. */ createMockFromModule(moduleName: string): any, /** * Mocks a module with an auto-mocked version when it is being required. * * The second argument can be used to specify an explicit module factory that * is being run instead of using Jest's automocking feature. * * The third argument can be used to create virtual mocks -- mocks of modules * that don't exist anywhere in the system. */ mock( moduleName: string, moduleFactory?: any, options?: Object ): JestObjectType, /** * Returns the actual module instead of a mock, bypassing all checks on * whether the module should receive a mock implementation or not. */ requireActual(m: $Flow$ModuleRef | string): T, /** * Returns a mock module instead of the actual module, bypassing all checks * on whether the module should be required normally or not. */ requireMock(moduleName: string): any, /** * Resets the module registry - the cache of all required modules. This is * useful to isolate modules where local state might conflict between tests. */ resetModules(): JestObjectType, /** * Creates a sandbox registry for the modules that are loaded inside the * callback function. This is useful to isolate specific modules for every * test so that local module state doesn't conflict between tests. */ isolateModules(fn: () => void): JestObjectType, /** * Exhausts the micro-task queue (usually interfaced in node via * process.nextTick). */ runAllTicks(): void, /** * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(), * setInterval(), and setImmediate()). */ runAllTimers(): void, /** * Exhausts all tasks queued by setImmediate(). */ runAllImmediates(): void, /** * Executes only the macro task queue (i.e. all tasks queued by setTimeout() * or setInterval() and setImmediate()). */ advanceTimersByTime(msToRun: number): void, /** * Executes only the macro-tasks that are currently pending (i.e., only the * tasks that have been queued by setTimeout() or setInterval() up to this * point) */ runOnlyPendingTimers(): void, /** * Explicitly supplies the mock object that the module system should return * for the specified module. Note: It is recommended to use jest.mock() * instead. */ setMock(moduleName: string, moduleExports: any): JestObjectType, /** * Indicates that the module system should never return a mocked version of * the specified module from require() (e.g. that it should always return the * real module). */ unmock(moduleName: string): JestObjectType, /** * Instructs Jest to use fake versions of the standard timer functions * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, * setImmediate and clearImmediate). */ useFakeTimers(fakeTimersConfig?: FakeTimersConfig): JestObjectType, /** * Instructs Jest to use the real versions of the standard timer functions. */ useRealTimers(): JestObjectType, /** * Creates a mock function similar to jest.fn but also tracks calls to * object[methodName]. */ spyOn( object: Object, methodName: string, accessType?: 'get' | 'set' ): JestMockFn, /** * Set the default timeout interval for tests and before/after hooks in milliseconds. * Note: The default timeout interval is 5 seconds if this method is not called. */ setTimeout(timeout: number): JestObjectType, ... }; type JestSpyType = { calls: JestCallsType, ... }; type JestDoneFn = {| (error?: Error): void, fail: (error: Error) => void, |}; /** Runs this function after every test inside this context */ declare function afterEach( fn: (done: JestDoneFn) => ?Promise, timeout?: number ): void; /** Runs this function before every test inside this context */ declare function beforeEach( fn: (done: JestDoneFn) => ?Promise, timeout?: number ): void; /** Runs this function after all tests have finished inside this context */ declare function afterAll( fn: (done: JestDoneFn) => ?Promise, timeout?: number ): void; /** Runs this function before any tests have started inside this context */ declare function beforeAll( fn: (done: JestDoneFn) => ?Promise, timeout?: number ): void; /** A context for grouping tests together */ declare var describe: { /** * Creates a block that groups together several related tests in one "test suite" */ (name: JestTestName, fn: () => void): void, /** * Only run this describe block */ only(name: JestTestName, fn: () => void): void, /** * Skip running this describe block */ skip(name: JestTestName, fn: () => void): void, /** * each runs this test against array of argument arrays per each run * * @param {table} table of Test */ each( ...table: Array | mixed> | [Array, string] ): ( name: JestTestName, fn?: (...args: Array) => ?Promise, timeout?: number ) => void, ... }; /** An individual test unit */ declare var it: { /** * An individual test unit * * @param {JestTestName} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ ( name: JestTestName, fn?: (done: JestDoneFn) => ?Promise, timeout?: number ): void, /** * Only run this test * * @param {JestTestName} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ only: {| ( name: JestTestName, fn?: (done: JestDoneFn) => ?Promise, timeout?: number ): void, each( ...table: Array | mixed> | [Array, string] ): ( name: JestTestName, fn?: (...args: Array) => ?Promise, timeout?: number ) => void, |}, /** * Skip running this test * * @param {JestTestName} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ skip: {| ( name: JestTestName, fn?: (done: JestDoneFn) => ?Promise, timeout?: number ): void, each( ...table: Array | mixed> | [Array, string] ): ( name: JestTestName, fn?: (...args: Array) => ?Promise, timeout?: number ) => void, |}, /** * Highlight planned tests in the summary output * * @param {String} Name of Test to do */ todo(name: string): void, /** * Run the test concurrently * * @param {JestTestName} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ concurrent( name: JestTestName, fn?: (done: JestDoneFn) => ?Promise, timeout?: number ): void, /** * each runs this test against array of argument arrays per each run * * @param {table} table of Test */ each( ...table: Array | mixed> | [Array, string] ): ( name: JestTestName, fn?: (...args: Array) => ?Promise, timeout?: number ) => void, ... }; declare function fit( name: JestTestName, fn: (done: JestDoneFn) => ?Promise, timeout?: number ): void; /** An individual test unit */ declare var test: typeof it; /** A disabled group of tests */ declare var xdescribe: typeof describe; /** A focused group of tests */ declare var fdescribe: typeof describe; /** A disabled individual test */ declare var xit: typeof it; /** A disabled individual test */ declare var xtest: typeof it; type JestPrettyFormatColors = { comment: { close: string, open: string, ... }, content: { close: string, open: string, ... }, prop: { close: string, open: string, ... }, tag: { close: string, open: string, ... }, value: { close: string, open: string, ... }, ... }; type JestPrettyFormatIndent = (string) => string; type JestPrettyFormatRefs = Array; type JestPrettyFormatPrint = (any) => string; type JestPrettyFormatStringOrNull = string | null; type JestPrettyFormatOptions = {| callToJSON: boolean, edgeSpacing: string, escapeRegex: boolean, highlight: boolean, indent: number, maxDepth: number, min: boolean, plugins: JestPrettyFormatPlugins, printFunctionName: boolean, spacing: string, theme: {| comment: string, content: string, prop: string, tag: string, value: string, |}, |}; type JestPrettyFormatPlugin = { print: ( val: any, serialize: JestPrettyFormatPrint, indent: JestPrettyFormatIndent, opts: JestPrettyFormatOptions, colors: JestPrettyFormatColors ) => string, test: (any) => boolean, ... }; type JestPrettyFormatPlugins = Array; /** The expect function is used every time you want to test a value */ declare var expect: { /** The object that you want to make assertions against */ ( value: any ): JestExpectType & JestPromiseType & EnzymeMatchersType & DomTestingLibraryType & JestJQueryMatchersType & JestStyledComponentsMatchersType & JestExtendedMatchersType & SnapshotDiffType, /** Add additional Jasmine matchers to Jest's roster */ extend(matchers: { [name: string]: JestMatcher, ... }): void, /** Add a module that formats application-specific data structures. */ addSnapshotSerializer(pluginModule: JestPrettyFormatPlugin): void, assertions(expectedAssertions: number): void, hasAssertions(): void, any(value: mixed): JestAsymmetricEqualityType, anything(): any, arrayContaining(value: Array): Array, objectContaining(value: Object): Object, /** Matches any received string that contains the exact expected string. */ stringContaining(value: string): string, stringMatching(value: string | RegExp): string, not: { arrayContaining: (value: $ReadOnlyArray) => Array, objectContaining: (value: { ... }) => Object, stringContaining: (value: string) => string, stringMatching: (value: string | RegExp) => string, ... }, ... }; // TODO handle return type // http://jasmine.github.io/2.4/introduction.html#section-Spies declare function spyOn(value: mixed, method: string): Object; /** Holds all functions related to manipulating test runner */ declare var jest: JestObjectType; /** * The global Jasmine object, this is generally not exposed as the public API, * using features inside here could break in later versions of Jest. */ declare var jasmine: { DEFAULT_TIMEOUT_INTERVAL: number, any(value: mixed): JestAsymmetricEqualityType, anything(): any, arrayContaining(value: Array): Array, clock(): JestClockType, createSpy(name: string): JestSpyType, createSpyObj( baseName: string, methodNames: Array ): { [methodName: string]: JestSpyType, ... }, objectContaining(value: Object): Object, stringMatching(value: string): string, ... }; ================================================ FILE: flow-typed/npm/lint-staged_vx.x.x.js ================================================ // flow-typed signature: 9793179ff11430685c8286a4ff6f3f16 // flow-typed version: <>/lint-staged_v^12.4.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * 'lint-staged' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'lint-staged' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'lint-staged/bin/lint-staged' { declare module.exports: any; } declare module 'lint-staged/lib/chunkFiles' { declare module.exports: any; } declare module 'lint-staged/lib/dynamicImport' { declare module.exports: any; } declare module 'lint-staged/lib/execGit' { declare module.exports: any; } declare module 'lint-staged/lib/figures' { declare module.exports: any; } declare module 'lint-staged/lib/file' { declare module.exports: any; } declare module 'lint-staged/lib/generateTasks' { declare module.exports: any; } declare module 'lint-staged/lib/getRenderer' { declare module.exports: any; } declare module 'lint-staged/lib/getStagedFiles' { declare module.exports: any; } declare module 'lint-staged/lib/gitWorkflow' { declare module.exports: any; } declare module 'lint-staged/lib/groupFilesByConfig' { declare module.exports: any; } declare module 'lint-staged/lib' { declare module.exports: any; } declare module 'lint-staged/lib/loadConfig' { declare module.exports: any; } declare module 'lint-staged/lib/makeCmdTasks' { declare module.exports: any; } declare module 'lint-staged/lib/messages' { declare module.exports: any; } declare module 'lint-staged/lib/parseGitZOutput' { declare module.exports: any; } declare module 'lint-staged/lib/printTaskOutput' { declare module.exports: any; } declare module 'lint-staged/lib/resolveConfig' { declare module.exports: any; } declare module 'lint-staged/lib/resolveGitRepo' { declare module.exports: any; } declare module 'lint-staged/lib/resolveTaskFn' { declare module.exports: any; } declare module 'lint-staged/lib/runAll' { declare module.exports: any; } declare module 'lint-staged/lib/searchConfigs' { declare module.exports: any; } declare module 'lint-staged/lib/state' { declare module.exports: any; } declare module 'lint-staged/lib/symbols' { declare module.exports: any; } declare module 'lint-staged/lib/validateBraces' { declare module.exports: any; } declare module 'lint-staged/lib/validateConfig' { declare module.exports: any; } declare module 'lint-staged/lib/validateOptions' { declare module.exports: any; } // Filename aliases declare module 'lint-staged/bin/lint-staged.js' { declare module.exports: $Exports<'lint-staged/bin/lint-staged'>; } declare module 'lint-staged/lib/chunkFiles.js' { declare module.exports: $Exports<'lint-staged/lib/chunkFiles'>; } declare module 'lint-staged/lib/dynamicImport.js' { declare module.exports: $Exports<'lint-staged/lib/dynamicImport'>; } declare module 'lint-staged/lib/execGit.js' { declare module.exports: $Exports<'lint-staged/lib/execGit'>; } declare module 'lint-staged/lib/figures.js' { declare module.exports: $Exports<'lint-staged/lib/figures'>; } declare module 'lint-staged/lib/file.js' { declare module.exports: $Exports<'lint-staged/lib/file'>; } declare module 'lint-staged/lib/generateTasks.js' { declare module.exports: $Exports<'lint-staged/lib/generateTasks'>; } declare module 'lint-staged/lib/getRenderer.js' { declare module.exports: $Exports<'lint-staged/lib/getRenderer'>; } declare module 'lint-staged/lib/getStagedFiles.js' { declare module.exports: $Exports<'lint-staged/lib/getStagedFiles'>; } declare module 'lint-staged/lib/gitWorkflow.js' { declare module.exports: $Exports<'lint-staged/lib/gitWorkflow'>; } declare module 'lint-staged/lib/groupFilesByConfig.js' { declare module.exports: $Exports<'lint-staged/lib/groupFilesByConfig'>; } declare module 'lint-staged/lib/index' { declare module.exports: $Exports<'lint-staged/lib'>; } declare module 'lint-staged/lib/index.js' { declare module.exports: $Exports<'lint-staged/lib'>; } declare module 'lint-staged/lib/loadConfig.js' { declare module.exports: $Exports<'lint-staged/lib/loadConfig'>; } declare module 'lint-staged/lib/makeCmdTasks.js' { declare module.exports: $Exports<'lint-staged/lib/makeCmdTasks'>; } declare module 'lint-staged/lib/messages.js' { declare module.exports: $Exports<'lint-staged/lib/messages'>; } declare module 'lint-staged/lib/parseGitZOutput.js' { declare module.exports: $Exports<'lint-staged/lib/parseGitZOutput'>; } declare module 'lint-staged/lib/printTaskOutput.js' { declare module.exports: $Exports<'lint-staged/lib/printTaskOutput'>; } declare module 'lint-staged/lib/resolveConfig.js' { declare module.exports: $Exports<'lint-staged/lib/resolveConfig'>; } declare module 'lint-staged/lib/resolveGitRepo.js' { declare module.exports: $Exports<'lint-staged/lib/resolveGitRepo'>; } declare module 'lint-staged/lib/resolveTaskFn.js' { declare module.exports: $Exports<'lint-staged/lib/resolveTaskFn'>; } declare module 'lint-staged/lib/runAll.js' { declare module.exports: $Exports<'lint-staged/lib/runAll'>; } declare module 'lint-staged/lib/searchConfigs.js' { declare module.exports: $Exports<'lint-staged/lib/searchConfigs'>; } declare module 'lint-staged/lib/state.js' { declare module.exports: $Exports<'lint-staged/lib/state'>; } declare module 'lint-staged/lib/symbols.js' { declare module.exports: $Exports<'lint-staged/lib/symbols'>; } declare module 'lint-staged/lib/validateBraces.js' { declare module.exports: $Exports<'lint-staged/lib/validateBraces'>; } declare module 'lint-staged/lib/validateConfig.js' { declare module.exports: $Exports<'lint-staged/lib/validateConfig'>; } declare module 'lint-staged/lib/validateOptions.js' { declare module.exports: $Exports<'lint-staged/lib/validateOptions'>; } ================================================ FILE: flow-typed/npm/md5_v2.x.x.js ================================================ // flow-typed signature: 198b480a6b35dbf3a74cb37d21258b00 // flow-typed version: c6154227d1/md5_v2.x.x/flow_>=v0.104.x // @flow declare module "md5" { declare module.exports: ( message: string | Buffer, options?: { asString?: boolean, asBytes?: boolean, encoding?: string, ... } ) => string; } ================================================ FILE: flow-typed/npm/mkdirp_v1.x.x.js ================================================ // flow-typed signature: 28ddcca31abd597a77830710de25f5fe // flow-typed version: a75473352d/mkdirp_v1.x.x/flow_>=v0.83.x declare module 'mkdirp' { import typeof { mkdir, stat } from 'fs'; declare type FsImplementation = { +mkdir?: mkdir, +stat?: stat, ... }; declare type Options = number | string | {| mode?: number; fs?: FsImplementation |}; declare type Callback = (err: ?Error, path: ?string) => void; declare module.exports: {| (path: string, options?: Options | Callback): Promise; sync(path: string, options?: Options): string | void; manual(path: string, options?: Options | Callback): Promise; manualSync(path: string, options?: Options): string | void; native(path: string, options?: Options | Callback): Promise; nativeSync(path: string, options?: Options): string | void; |}; } ================================================ FILE: flow-typed/npm/mocha_v4.x.x.js ================================================ // flow-typed signature: 8b533a1271b4580048529f45ac3a3c68 // flow-typed version: ba7bfb2fda/mocha_v4.x.x/flow_>=v0.104.x declare interface $npm$mocha$SetupOptions { slow?: number; timeout?: number; ui?: string; globals?: Array; reporter?: any; bail?: boolean; ignoreLeaks?: boolean; grep?: any; } declare type $npm$mocha$done = (error?: any) => any; // declare interface $npm$mocha$SuiteCallbackContext { // timeout(ms: number): void; // retries(n: number): void; // slow(ms: number): void; // } // declare interface $npm$mocha$TestCallbackContext { // skip(): void; // timeout(ms: number): void; // retries(n: number): void; // slow(ms: number): void; // [index: string]: any; // } declare interface $npm$mocha$Suite { parent: $npm$mocha$Suite; title: string; fullTitle(): string; } declare type $npm$mocha$ContextDefinition = {| (description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): $npm$mocha$Suite; only(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): $npm$mocha$Suite; skip(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): void; timeout(ms: number): void; |} declare type $npm$mocha$TestDefinition = {| (expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): $npm$mocha$Test; only(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): $npm$mocha$Test; skip(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): void; timeout(ms: number): void; state: 'failed' | 'passed'; |} declare interface $npm$mocha$Runner {} declare class $npm$mocha$BaseReporter { stats: { suites: number, tests: number, passes: number, pending: number, failures: number, ... }; constructor(runner: $npm$mocha$Runner): $npm$mocha$BaseReporter; } declare class $npm$mocha$DocReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$DotReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$HTMLReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$HTMLCovReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$JSONReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$JSONCovReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$JSONStreamReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$LandingReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$ListReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$MarkdownReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$MinReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$NyanReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$ProgressReporter extends $npm$mocha$BaseReporter { constructor(runner: $npm$mocha$Runner, options?: { open?: string, complete?: string, incomplete?: string, close?: string, ... }): $npm$mocha$ProgressReporter; } declare class $npm$mocha$SpecReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$TAPReporter extends $npm$mocha$BaseReporter {} declare class $npm$mocha$XUnitReporter extends $npm$mocha$BaseReporter { constructor(runner: $npm$mocha$Runner, options?: any): $npm$mocha$XUnitReporter; } declare class $npm$mocha$Mocha { currentTest: $npm$mocha$TestDefinition; constructor(options?: { grep?: RegExp, ui?: string, reporter?: string, timeout?: number, reporterOptions?: any, slow?: number, bail?: boolean, ... }): $npm$mocha$Mocha; setup(options: $npm$mocha$SetupOptions): this; bail(value?: boolean): this; addFile(file: string): this; reporter(name: string): this; reporter(reporter: (runner: $npm$mocha$Runner, options: any) => any): this; ui(value: string): this; grep(value: string): this; grep(value: RegExp): this; invert(): this; ignoreLeaks(value: boolean): this; checkLeaks(): this; throwError(error: Error): void; growl(): this; globals(value: string): this; globals(values: Array): this; useColors(value: boolean): this; useInlineDiffs(value: boolean): this; timeout(value: number): this; slow(value: number): this; enableTimeouts(value: boolean): this; asyncOnly(value: boolean): this; noHighlighting(value: boolean): this; run(onComplete?: (failures: number) => void): $npm$mocha$Runner; static reporters: { Doc: $npm$mocha$DocReporter, Dot: $npm$mocha$DotReporter, HTML: $npm$mocha$HTMLReporter, HTMLCov: $npm$mocha$HTMLCovReporter, JSON: $npm$mocha$JSONReporter, JSONCov: $npm$mocha$JSONCovReporter, JSONStream: $npm$mocha$JSONStreamReporter, Landing: $npm$mocha$LandingReporter, List: $npm$mocha$ListReporter, Markdown: $npm$mocha$MarkdownReporter, Min: $npm$mocha$MinReporter, Nyan: $npm$mocha$NyanReporter, Progress: $npm$mocha$ProgressReporter, ... }; } // declare interface $npm$mocha$HookCallbackContext { // skip(): void; // timeout(ms: number): void; // [index: string]: any; // } declare interface $npm$mocha$Runnable { title: string; fn: Function; async: boolean; sync: boolean; timedOut: boolean; } declare interface $npm$mocha$Test extends $npm$mocha$Runnable { parent: $npm$mocha$Suite; pending: boolean; state: 'failed' | 'passed' | void; fullTitle(): string; } // declare interface $npm$mocha$BeforeAndAfterContext extends $npm$mocha$HookCallbackContext { // currentTest: $npm$mocha$Test; // } declare var mocha: $npm$mocha$Mocha; declare var describe: $npm$mocha$ContextDefinition; declare var xdescribe: $npm$mocha$ContextDefinition; declare var context: $npm$mocha$ContextDefinition; declare var suite: $npm$mocha$ContextDefinition; declare var it: $npm$mocha$TestDefinition; declare var xit: $npm$mocha$TestDefinition; declare var test: $npm$mocha$TestDefinition; declare var specify: $npm$mocha$TestDefinition; type Run = () => void; declare var run: Run; type Setup = (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void; type Teardown = (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void; type SuiteSetup = (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void; type SuiteTeardown = (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void; type Before = | (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void | (description: string, callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void; type After = | (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void | (description: string, callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void; type BeforeEach = | (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void | (description: string, callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void; type AfterEach = | (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void | (description: string, callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void; declare var setup: Setup; declare var teardown: Teardown; declare var suiteSetup: SuiteSetup; declare var suiteTeardown: SuiteTeardown; declare var before: Before declare var after: After; declare var beforeEach: BeforeEach; declare var afterEach: AfterEach; declare module "mocha" { declare export var mocha: $npm$mocha$TestDefinition; declare export var describe: $npm$mocha$ContextDefinition; declare export var xdescribe: $npm$mocha$ContextDefinition; declare export var context: $npm$mocha$ContextDefinition; declare export var suite: $npm$mocha$ContextDefinition; declare export var it: $npm$mocha$TestDefinition; declare export var xit: $npm$mocha$TestDefinition; declare export var test: $npm$mocha$TestDefinition; declare export var specify: $npm$mocha$TestDefinition; declare export var run: Run; declare export var setup: Setup; declare export var teardown: Teardown; declare export var suiteSetup: SuiteSetup; declare export var suiteTeardown: SuiteTeardown; declare export var before: Before; declare export var after: After; declare export var beforeEach: BeforeEach; declare export var afterEach: AfterEach; declare export default $npm$mocha$Mocha; } ================================================ FILE: flow-typed/npm/node-stream-zip_v1.x.x.js ================================================ // flow-typed signature: bd18604d0696d9e4ad0da443cf74273b // flow-typed version: 1ff21d416b/node-stream-zip_v1.x.x/flow_>=v0.104.x declare module 'node-stream-zip' { declare type StreamZipOptions = {| /** * File to read * @default undefined */ file?: string; /** * Alternatively, you can pass fd here * @default undefined */ fd?: number; /** * You will be able to work with entries inside zip archive, * otherwise the only way to access them is entry event * @default true */ storeEntries?: boolean; /** * By default, entry name is checked for malicious characters, like ../ or c:\123, * pass this flag to disable validation error * @default false */ skipEntryNameValidation?: boolean; /** * Filesystem read chunk size * @default automatic based on file size */ chunkSize?: number; /** * Encoding used to decode file names * @default UTF8 */ nameEncoding?: string; |} declare type ZipEntry = {| /** * file name */ name: string; /** * true if it's a directory entry */ isDirectory: boolean; /** * true if it's a file entry, see also isDirectory */ isFile: boolean; /** * file comment */ comment: string; /** * if the file is encrypted */ encrypted: boolean; /** * version made by */ verMade: number; /** * version needed to extract */ version: number; /** * encrypt, decrypt flags */ flags: number; /** * compression method */ method: number; /** * modification time */ time: number; /** * uncompressed file crc-32 value */ crc: number; /** * compressed size */ compressedSize: number; /** * uncompressed size */ size: number; /** * volume number start */ diskStart: number; /** * internal file attributes */ inattr: number; /** * external file attributes */ attr: number; /** * LOC header offset */ offset: number; |} declare class StreamZipAsync { constructor(config: StreamZipOptions): this; entriesCount: Promise; comment: Promise; entry(name: string): Promise; entries(): Promise<{ [name: string]: ZipEntry }>; entryData(entry: string | ZipEntry): Promise; stream(entry: string | ZipEntry): Promise; extract(entry: string | ZipEntry | null, outPath: string): Promise; on(event: 'entry', handler: (entry: ZipEntry) => void): void; on(event: 'extract', handler: (entry: ZipEntry, outPath: string) => void): void; close(): Promise; } declare class StreamZip { constructor(config: StreamZipOptions): this; entriesCount: number; comment: string; on(event: 'error', handler: (error: any) => void): void; on(event: 'entry', handler: (entry: ZipEntry) => void): void; on(event: 'ready', handler: () => void): void; on(event: 'extract', handler: (entry: ZipEntry, outPath: string) => void): void; entry(name: string): ?ZipEntry; entries(): { [name: string]: ZipEntry }; stream( entry: string | ZipEntry, callback: (err: any | null, stream?: ReadableStream) => void ): void; entryDataSync(entry: string | ZipEntry): Buffer; openEntry( entry: string | ZipEntry, callback: (err: any | null, entry?: ZipEntry) => void, sync: boolean ): void; extract( entry: string | ZipEntry | null, outPath: string, callback: (err?: any, res?: number) => void ): void; close(callback?: (err?: any) => void): void; static async: Class; } declare module.exports: Class; } ================================================ FILE: flow-typed/npm/prettier_v1.x.x.js ================================================ // flow-typed signature: cfdc7e61e71ab8d32e882a236b798eaf // flow-typed version: 02d4f1d2c5/prettier_v1.x.x/flow_>=v0.104.x <=v0.200.x declare module "prettier" { declare export type AST = { [key: string]: any, ... }; declare export type Doc = { [key: string]: any, ... }; declare export type FastPath = { stack: any[], getName(): null | string | number | Symbol, getValue(): T, getNode(count?: number): null | T, getParentNode(count?: number): null | T, call(callback: (path: FastPath) => U, ...names: Array): U, each(callback: (path: FastPath) => void, ...names: Array): void, map(callback: (path: FastPath, index: number) => U, ...names: Array): U[], ... }; declare export type PrettierParserName = | "babylon" // deprecated | "babel" | "babel-flow" | "flow" | "typescript" | "postcss" // deprecated | "css" | "less" | "scss" | "json" | "json5" | "json-stringify" | "graphql" | "markdown" | "vue" | "html" | "angular" | "mdx" | "yaml"; declare export type PrettierParser = { [name: PrettierParserName]: (text: string, options?: { [key: string]: any, ... }) => AST, ... }; declare export type CustomParser = ( text: string, parsers: PrettierParser, options: Options ) => AST; declare export type Options = {| printWidth?: number, tabWidth?: number, useTabs?: boolean, semi?: boolean, singleQuote?: boolean, trailingComma?: "none" | "es5" | "all", bracketSpacing?: boolean, jsxBracketSameLine?: boolean, arrowParens?: "avoid" | "always", rangeStart?: number, rangeEnd?: number, parser?: PrettierParserName | CustomParser, filepath?: string, requirePragma?: boolean, insertPragma?: boolean, proseWrap?: "always" | "never" | "preserve", plugins?: Array |}; declare export type Plugin = { languages: SupportLanguage, parsers: { [parserName: string]: Parser, ... }, printers: { [astFormat: string]: Printer, ... }, options?: SupportOption[], ... }; declare export type Parser = { parse: ( text: string, parsers: { [parserName: string]: Parser, ... }, options: { [key: string]: any, ... } ) => AST, astFormat: string, hasPragma?: (text: string) => boolean, locStart: (node: any) => number, locEnd: (node: any) => number, preprocess?: (text: string, options: { [key: string]: any, ... }) => string, ... }; declare export type Printer = { print: ( path: FastPath<>, options: { [key: string]: any, ... }, print: (path: FastPath<>) => Doc ) => Doc, embed: ( path: FastPath<>, print: (path: FastPath<>) => Doc, textToDoc: (text: string, options: { [key: string]: any, ... }) => Doc, options: { [key: string]: any, ... } ) => ?Doc, insertPragma?: (text: string) => string, massageAstNode?: (node: any, newNode: any, parent: any) => any, hasPrettierIgnore?: (path: FastPath<>) => boolean, canAttachComment?: (node: any) => boolean, willPrintOwnComments?: (path: FastPath<>) => boolean, printComments?: (path: FastPath<>, print: (path: FastPath<>) => Doc, options: { [key: string]: any, ... }, needsSemi: boolean) => Doc, handleComments?: { ownLine?: (commentNode: any, text: string, options: { [key: string]: any, ... }, ast: any, isLastComment: boolean) => boolean, endOfLine?: (commentNode: any, text: string, options: { [key: string]: any, ... }, ast: any, isLastComment: boolean) => boolean, remaining?: (commentNode: any, text: string, options: { [key: string]: any, ... }, ast: any, isLastComment: boolean) => boolean, ... }, ... }; declare export type CursorOptions = {| cursorOffset: number, printWidth?: $PropertyType, tabWidth?: $PropertyType, useTabs?: $PropertyType, semi?: $PropertyType, singleQuote?: $PropertyType, trailingComma?: $PropertyType, bracketSpacing?: $PropertyType, jsxBracketSameLine?: $PropertyType, arrowParens?: $PropertyType, parser?: $PropertyType, filepath?: $PropertyType, requirePragma?: $PropertyType, insertPragma?: $PropertyType, proseWrap?: $PropertyType, plugins?: $PropertyType |}; declare export type CursorResult = {| formatted: string, cursorOffset: number |}; declare export type ResolveConfigOptions = {| useCache?: boolean, config?: string, editorconfig?: boolean |}; declare export type SupportLanguage = { name: string, since: string, parsers: Array, group?: string, tmScope: string, aceMode: string, codemirrorMode: string, codemirrorMimeType: string, aliases?: Array, extensions: Array, filenames?: Array, linguistLanguageId: number, vscodeLanguageIds: Array, ... }; declare export type SupportOption = {| since: string, type: "int" | "boolean" | "choice" | "path", deprecated?: string, redirect?: SupportOptionRedirect, description: string, oppositeDescription?: string, default: SupportOptionValue, range?: SupportOptionRange, choices?: SupportOptionChoice |}; declare export type SupportOptionRedirect = {| options: string, value: SupportOptionValue |}; declare export type SupportOptionRange = {| start: number, end: number, step: number |}; declare export type SupportOptionChoice = {| value: boolean | string, description?: string, since?: string, deprecated?: string, redirect?: SupportOptionValue |}; declare export type SupportOptionValue = number | boolean | string; declare export type SupportInfo = {| languages: Array, options: Array |}; declare export type FileInfo = {| ignored: boolean, inferredParser: PrettierParserName | null, |}; declare export type Prettier = {| format: (source: string, options?: Options) => string, check: (source: string, options?: Options) => boolean, formatWithCursor: (source: string, options: CursorOptions) => CursorResult, resolveConfig: { (filePath: string, options?: ResolveConfigOptions): Promise, sync(filePath: string, options?: ResolveConfigOptions): ?Options, ... }, clearConfigCache: () => void, getSupportInfo: (version?: string) => SupportInfo, getFileInfo: (filePath: string) => Promise |}; declare export default Prettier; } ================================================ FILE: flow-typed/npm/prettier_vx.x.x.js ================================================ // flow-typed signature: 1f4ab6c1d3d18b92a343b925d5e6384c // flow-typed version: <>/prettier_v^2.6.2/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * 'prettier' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'prettier' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'prettier/bin-prettier' { declare module.exports: any; } declare module 'prettier/cli' { declare module.exports: any; } declare module 'prettier/doc' { declare module.exports: any; } declare module 'prettier/parser-angular' { declare module.exports: any; } declare module 'prettier/parser-babel' { declare module.exports: any; } declare module 'prettier/parser-espree' { declare module.exports: any; } declare module 'prettier/parser-flow' { declare module.exports: any; } declare module 'prettier/parser-glimmer' { declare module.exports: any; } declare module 'prettier/parser-graphql' { declare module.exports: any; } declare module 'prettier/parser-html' { declare module.exports: any; } declare module 'prettier/parser-markdown' { declare module.exports: any; } declare module 'prettier/parser-meriyah' { declare module.exports: any; } declare module 'prettier/parser-postcss' { declare module.exports: any; } declare module 'prettier/parser-typescript' { declare module.exports: any; } declare module 'prettier/parser-yaml' { declare module.exports: any; } declare module 'prettier/standalone' { declare module.exports: any; } declare module 'prettier/third-party' { declare module.exports: any; } // Filename aliases declare module 'prettier/bin-prettier.js' { declare module.exports: $Exports<'prettier/bin-prettier'>; } declare module 'prettier/cli.js' { declare module.exports: $Exports<'prettier/cli'>; } declare module 'prettier/doc.js' { declare module.exports: $Exports<'prettier/doc'>; } declare module 'prettier/index' { declare module.exports: $Exports<'prettier'>; } declare module 'prettier/index.js' { declare module.exports: $Exports<'prettier'>; } declare module 'prettier/parser-angular.js' { declare module.exports: $Exports<'prettier/parser-angular'>; } declare module 'prettier/parser-babel.js' { declare module.exports: $Exports<'prettier/parser-babel'>; } declare module 'prettier/parser-espree.js' { declare module.exports: $Exports<'prettier/parser-espree'>; } declare module 'prettier/parser-flow.js' { declare module.exports: $Exports<'prettier/parser-flow'>; } declare module 'prettier/parser-glimmer.js' { declare module.exports: $Exports<'prettier/parser-glimmer'>; } declare module 'prettier/parser-graphql.js' { declare module.exports: $Exports<'prettier/parser-graphql'>; } declare module 'prettier/parser-html.js' { declare module.exports: $Exports<'prettier/parser-html'>; } declare module 'prettier/parser-markdown.js' { declare module.exports: $Exports<'prettier/parser-markdown'>; } declare module 'prettier/parser-meriyah.js' { declare module.exports: $Exports<'prettier/parser-meriyah'>; } declare module 'prettier/parser-postcss.js' { declare module.exports: $Exports<'prettier/parser-postcss'>; } declare module 'prettier/parser-typescript.js' { declare module.exports: $Exports<'prettier/parser-typescript'>; } declare module 'prettier/parser-yaml.js' { declare module.exports: $Exports<'prettier/parser-yaml'>; } declare module 'prettier/standalone.js' { declare module.exports: $Exports<'prettier/standalone'>; } declare module 'prettier/third-party.js' { declare module.exports: $Exports<'prettier/third-party'>; } ================================================ FILE: flow-typed/npm/rimraf_v3.x.x.js ================================================ // flow-typed signature: 31191d41b239d1242753bdea18136ae9 // flow-typed version: 6ee04b16cf/rimraf_v3.x.x/flow_>=v0.104.x declare module 'rimraf' { declare type Options = { maxBusyTries?: number, emfileWait?: number, glob?: boolean, disableGlob?: boolean, ... }; declare type Callback = (err: ?Error, path: ?string) => void; declare module.exports: { (f: string, opts?: Options | Callback, callback?: Callback): void, sync(path: string, opts?: Options): void, ... }; } ================================================ FILE: flow-typed/npm/semver_v7.x.x.js ================================================ // flow-typed signature: bf6205896c200fb28700dfa8d29f2b8a // flow-typed version: 3d76504c27/semver_v7.x.x/flow_>=v0.104.x declare module "semver" { declare type Release = | "major" | "premajor" | "minor" | "preminor" | "patch" | "prepatch" | "prerelease"; // The supported comparators are taken from the source here: // https://github.com/npm/node-semver/blob/8bd070b550db2646362c9883c8d008d32f66a234/semver.js#L623 declare type Operator = | "===" | "!==" | "==" | "=" | "" // Not sure why you would want this, but whatever. | "!=" | ">" | ">=" | "<" | "<="; declare class SemVer { build: Array; loose: ?boolean; major: number; minor: number; patch: number; prerelease: Array; raw: string; version: string; constructor(version: string | SemVer, options?: Options): SemVer; compare(other: string | SemVer): -1 | 0 | 1; compareMain(other: string | SemVer): -1 | 0 | 1; comparePre(other: string | SemVer): -1 | 0 | 1; compareBuild(other: string | SemVer): -1 | 0 | 1; format(): string; inc(release: Release, identifier: string): this; } declare class Comparator { options?: Options; operator: Operator; semver: SemVer; value: string; constructor(comp: string | Comparator, options?: Options): Comparator; parse(comp: string): void; test(version: string): boolean; } declare class Range { loose: ?boolean; raw: string; set: Array>; constructor(range: string | Range, options?: Options): Range; format(): string; parseRange(range: string): Array; test(version: string): boolean; toString(): string; } declare var SEMVER_SPEC_VERSION: string; declare var re: Array; declare var src: Array; declare type Options = { options?: Options, includePrerelease?: boolean, ... } | boolean; // Functions declare function valid(v: string | SemVer, options?: Options): string | null; declare function clean(v: string | SemVer, options?: Options): string | null; declare function inc( v: string | SemVer, release: Release, options?: Options, identifier?: string ): string | null; declare function inc( v: string | SemVer, release: Release, identifier: string ): string | null; declare function major(v: string | SemVer, options?: Options): number; declare function minor(v: string | SemVer, options?: Options): number; declare function patch(v: string | SemVer, options?: Options): number; declare function intersects(r1: string | SemVer, r2: string | SemVer, loose?: boolean): boolean; declare function minVersion(r: string | Range): Range | null; // Comparison declare function gt( v1: string | SemVer, v2: string | SemVer, options?: Options ): boolean; declare function gte( v1: string | SemVer, v2: string | SemVer, options?: Options ): boolean; declare function lt( v1: string | SemVer, v2: string | SemVer, options?: Options ): boolean; declare function lte( v1: string | SemVer, v2: string | SemVer, options?: Options ): boolean; declare function eq( v1: string | SemVer, v2: string | SemVer, options?: Options ): boolean; declare function neq( v1: string | SemVer, v2: string | SemVer, options?: Options ): boolean; declare function cmp( v1: string | SemVer, comparator: Operator, v2: string | SemVer, options?: Options ): boolean; declare function compare( v1: string | SemVer, v2: string | SemVer, options?: Options ): -1 | 0 | 1; declare function rcompare( v1: string | SemVer, v2: string | SemVer, options?: Options ): -1 | 0 | 1; declare function diff(v1: string | SemVer, v2: string | SemVer): ?Release; declare function intersects(comparator: Comparator): boolean; declare function sort( list: Array, options?: Options ): Array; declare function rsort( list: Array, options?: Options ): Array; declare function compareIdentifiers( v1: string | SemVer, v2: string | SemVer ): -1 | 0 | 1; declare function rcompareIdentifiers( v1: string | SemVer, v2: string | SemVer ): -1 | 0 | 1; // Ranges declare function validRange( range: string | Range, options?: Options ): string | null; declare function satisfies( version: string | SemVer, range: string | Range, options?: Options ): boolean; declare function maxSatisfying( versions: Array, range: string | Range, options?: Options ): string | SemVer | null; declare function minSatisfying( versions: Array, range: string | Range, options?: Options ): string | SemVer | null; declare function gtr( version: string | SemVer, range: string | Range, options?: Options ): boolean; declare function ltr( version: string | SemVer, range: string | Range, options?: Options ): boolean; declare function outside( version: string | SemVer, range: string | Range, hilo: ">" | "<", options?: Options ): boolean; declare function intersects( range: Range ): boolean; declare function simplifyRange( ranges: Array, range: string | Range, options?: Options, ): string | Range; declare function subset( sub: string | Range, dom: string | Range, options?: Options, ): boolean; // Coercion declare function coerce( version: string | SemVer, options?: Options ): ?SemVer // Not explicitly documented, or deprecated declare function parse(version: string, options?: Options): ?SemVer; declare function toComparators( range: string | Range, options?: Options ): Array>; } declare module "semver/preload" { declare module.exports: $Exports<"semver">; } ================================================ FILE: flow-typed/npm/serve_vx.x.x.js ================================================ // flow-typed signature: ff47633e906b77d18196430051db52fa // flow-typed version: <>/serve_v^10.0.0/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * 'serve' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'serve' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'serve/bin/serve' { declare module.exports: any; } // Filename aliases declare module 'serve/bin/serve.js' { declare module.exports: $Exports<'serve/bin/serve'>; } ================================================ FILE: flow-typed/npm/standard-version_vx.x.x.js ================================================ // flow-typed signature: 570f5014289cb73342d1dd70c136bca1 // flow-typed version: <>/standard-version_v^9.3.2/flow_v0.155.0 /** * This is an autogenerated libdef stub for: * * 'standard-version' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'standard-version' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'standard-version/bin/cli' { declare module.exports: any; } declare module 'standard-version/command' { declare module.exports: any; } declare module 'standard-version/defaults' { declare module.exports: any; } declare module 'standard-version/lib/checkpoint' { declare module.exports: any; } declare module 'standard-version/lib/configuration' { declare module.exports: any; } declare module 'standard-version/lib/format-commit-message' { declare module.exports: any; } declare module 'standard-version/lib/latest-semver-tag' { declare module.exports: any; } declare module 'standard-version/lib/lifecycles/bump' { declare module.exports: any; } declare module 'standard-version/lib/lifecycles/changelog' { declare module.exports: any; } declare module 'standard-version/lib/lifecycles/commit' { declare module.exports: any; } declare module 'standard-version/lib/lifecycles/tag' { declare module.exports: any; } declare module 'standard-version/lib/preset-loader' { declare module.exports: any; } declare module 'standard-version/lib/print-error' { declare module.exports: any; } declare module 'standard-version/lib/run-exec' { declare module.exports: any; } declare module 'standard-version/lib/run-execFile' { declare module.exports: any; } declare module 'standard-version/lib/run-lifecycle-script' { declare module.exports: any; } declare module 'standard-version/lib/updaters' { declare module.exports: any; } declare module 'standard-version/lib/updaters/types/json' { declare module.exports: any; } declare module 'standard-version/lib/updaters/types/plain-text' { declare module.exports: any; } declare module 'standard-version/lib/write-file' { declare module.exports: any; } declare module 'standard-version/test/config-files.spec' { declare module.exports: any; } declare module 'standard-version/test/core.spec' { declare module.exports: any; } declare module 'standard-version/test/git.spec' { declare module.exports: any; } declare module 'standard-version/test/mocks/updater/customer-updater' { declare module.exports: any; } declare module 'standard-version/test/preset.spec' { declare module.exports: any; } // Filename aliases declare module 'standard-version/bin/cli.js' { declare module.exports: $Exports<'standard-version/bin/cli'>; } declare module 'standard-version/command.js' { declare module.exports: $Exports<'standard-version/command'>; } declare module 'standard-version/defaults.js' { declare module.exports: $Exports<'standard-version/defaults'>; } declare module 'standard-version/index' { declare module.exports: $Exports<'standard-version'>; } declare module 'standard-version/index.js' { declare module.exports: $Exports<'standard-version'>; } declare module 'standard-version/lib/checkpoint.js' { declare module.exports: $Exports<'standard-version/lib/checkpoint'>; } declare module 'standard-version/lib/configuration.js' { declare module.exports: $Exports<'standard-version/lib/configuration'>; } declare module 'standard-version/lib/format-commit-message.js' { declare module.exports: $Exports<'standard-version/lib/format-commit-message'>; } declare module 'standard-version/lib/latest-semver-tag.js' { declare module.exports: $Exports<'standard-version/lib/latest-semver-tag'>; } declare module 'standard-version/lib/lifecycles/bump.js' { declare module.exports: $Exports<'standard-version/lib/lifecycles/bump'>; } declare module 'standard-version/lib/lifecycles/changelog.js' { declare module.exports: $Exports<'standard-version/lib/lifecycles/changelog'>; } declare module 'standard-version/lib/lifecycles/commit.js' { declare module.exports: $Exports<'standard-version/lib/lifecycles/commit'>; } declare module 'standard-version/lib/lifecycles/tag.js' { declare module.exports: $Exports<'standard-version/lib/lifecycles/tag'>; } declare module 'standard-version/lib/preset-loader.js' { declare module.exports: $Exports<'standard-version/lib/preset-loader'>; } declare module 'standard-version/lib/print-error.js' { declare module.exports: $Exports<'standard-version/lib/print-error'>; } declare module 'standard-version/lib/run-exec.js' { declare module.exports: $Exports<'standard-version/lib/run-exec'>; } declare module 'standard-version/lib/run-execFile.js' { declare module.exports: $Exports<'standard-version/lib/run-execFile'>; } declare module 'standard-version/lib/run-lifecycle-script.js' { declare module.exports: $Exports<'standard-version/lib/run-lifecycle-script'>; } declare module 'standard-version/lib/updaters/index' { declare module.exports: $Exports<'standard-version/lib/updaters'>; } declare module 'standard-version/lib/updaters/index.js' { declare module.exports: $Exports<'standard-version/lib/updaters'>; } declare module 'standard-version/lib/updaters/types/json.js' { declare module.exports: $Exports<'standard-version/lib/updaters/types/json'>; } declare module 'standard-version/lib/updaters/types/plain-text.js' { declare module.exports: $Exports<'standard-version/lib/updaters/types/plain-text'>; } declare module 'standard-version/lib/write-file.js' { declare module.exports: $Exports<'standard-version/lib/write-file'>; } declare module 'standard-version/test/config-files.spec.js' { declare module.exports: $Exports<'standard-version/test/config-files.spec'>; } declare module 'standard-version/test/core.spec.js' { declare module.exports: $Exports<'standard-version/test/core.spec'>; } declare module 'standard-version/test/git.spec.js' { declare module.exports: $Exports<'standard-version/test/git.spec'>; } declare module 'standard-version/test/mocks/updater/customer-updater.js' { declare module.exports: $Exports<'standard-version/test/mocks/updater/customer-updater'>; } declare module 'standard-version/test/preset.spec.js' { declare module.exports: $Exports<'standard-version/test/preset.spec'>; } ================================================ FILE: flow-typed/npm/yargs_v15.x.x.js ================================================ // flow-typed signature: d538758c32ffc612a9c0d1262c22d161 // flow-typed version: 3c81f4d103/yargs_v15.x.x/flow_>=v0.118.x <=v0.200.x declare module "yargs" { declare type Argv = { [key: string]: any, _: Array, $0: string, ... }; declare type Options = $Shape<{ alias: string | Array, array: boolean, boolean: boolean, choices: Array, coerce: (arg: {[key: string]: any, ...} | any) => mixed, config: boolean, configParser: (configPath: string) => { [key: string]: mixed, ... }, conflicts: string | Array | { [key: string]: string, ... }, count: boolean, default: mixed, defaultDescription: string, demandOption: boolean | string, desc: string, describe: string, description: string, global: boolean, group: string, implies: string | { [key: string]: string, ... }, nargs: number, normalize: boolean, number: boolean, required: boolean, requiresArg: boolean, skipValidation: boolean, string: boolean, type: "array" | "boolean" | "count" | "number" | "string", ... }>; declare type CommonModuleObject = {| command?: string | Array, aliases?: Array | string, builder?: { [key: string]: Options, ... } | ((yargsInstance: Yargs) => mixed), handler?: ((argv: Argv) => void) | ((argv: Argv) => Promise) |}; declare type ModuleObjectDesc = {| ...CommonModuleObject, desc?: string | false |}; declare type ModuleObjectDescribe = {| ...CommonModuleObject, describe?: string | false |}; declare type ModuleObjectDescription = {| ...CommonModuleObject, description?: string | false |}; declare type ModuleObject = | ModuleObjectDesc | ModuleObjectDescribe | ModuleObjectDescription; declare type MiddleWareCallback = | (argv: Argv, yargsInstance?: Yargs) => void | (argv: Argv, yargsInstance?: Yargs) => Promise; declare type Middleware = MiddleWareCallback | Array; declare class Yargs { (args: Array): Yargs; alias(key: string, alias: string): this; alias(alias: { [key: string]: string | Array, ... }): this; argv: Argv; array(key: string | Array): this; boolean(parameter: string | Array): this; check(fn: (argv: Argv, options: Array) => ?boolean): this; choices(key: string, allowed: Array): this; choices(allowed: { [key: string]: Array, ... }): this; coerce(key: string, fn: (value: any) => mixed): this; coerce(object: { [key: string]: (value: any) => mixed, ... }): this; coerce(keys: Array, fn: (value: any) => mixed): this; command( cmd: string | Array, desc: string | false, builder?: { [key: string]: Options, ... } | ((yargsInstance: Yargs) => mixed), handler?: Function ): this; command( cmd: string | Array, desc: string | false, module: ModuleObject ): this; command(module: ModuleObject): this; commandDir( directory: string, options?: { exclude?: string | Function, extensions?: Array, include?: string | Function, recurse?: boolean, visit?: Function, ... }, ): this; completion( cmd?: string, description?: string | false | ( current: string, argv: Argv, done: (compeltion: Array) => void ) => ?(Array | Promise>), fn?: ( current: string, argv: Argv, done: (completion: Array) => void ) => ?(Array | Promise>) ): this; config( key?: string, description?: string, parseFn?: (configPath: string) => { [key: string]: mixed, ... } ): this; config( key: string, parseFn?: (configPath: string) => { [key: string]: mixed, ... } ): this; config(config: { [key: string]: mixed, ... }): this; conflicts(key: string, value: string | Array): this; conflicts(keys: { [key: string]: string | Array, ... }): this; count(name: string): this; default(key: string, value: mixed, description?: string): this; default(defaults: { [key: string]: mixed, ... }): this; // Deprecated: use demandOption() and demandCommand() instead. demand(key: string, msg?: string | boolean): this; demand(count: number, max?: number, msg?: string | boolean): this; demandOption(key: string | Array, msg?: string | boolean): this; demandCommand(): this; demandCommand(min: number, minMsg?: string): this; demandCommand( min: number, max: number, minMsg?: string, maxMsg?: string ): this; describe(key: string, description: string): this; describe(describeObject: { [key: string]: string, ... }): this; detectLocale(shouldDetect: boolean): this; env(prefix?: string): this; epilog(text: string): this; epilogue(text: string): this; example(cmd: string, desc?: string): this; exitProcess(enable: boolean): this; fail(fn: (failureMessage: string, err: Error, yargs: Yargs) => mixed): this; getCompletion(args: Array, fn: () => void): this; global(globals: string | Array, isGlobal?: boolean): this; group(key: string | Array, groupName: string): this; help(option: boolean): this; help(option?: string, desc?: string): this; hide(key: string): this; implies(key: string, value: string | Array): this; implies(keys: { [key: string]: string | Array, ... }): this; locale( locale: | "de" | "en" | "es" | "fr" | "hi" | "hu" | "id" | "it" | "ja" | "ko" | "nb" | "pirate" | "pl" | "pt" | "pt_BR" | "ru" | "th" | "tr" | "zh_CN" ): this; locale(): string; middleware( middlewareCallbacks: Middleware, applyBeforeValidation?: boolean, ): this; nargs(key: string, count: number): this; normalize(key: string): this; number(key: string | Array): this; onFinishCommand(handler: () => mixed): this; option(key: string, options?: Options): this; option(optionMap: { [key: string]: Options, ... }): this; options(key: string, options?: Options): this; options(optionMap: { [key: string]: Options, ... }): this; parse( args?: string | Array, context?: { [key: string]: any, ... }, parseCallback?: (err: Error, argv: Argv, output?: string) => void ): Argv; parse( args?: string | Array, parseCallback?: (err: Error, argv: Argv, output?: string) => void ): Argv; parserConfiguration(configuration: {[key: string]: any, ...}): this; pkgConf(key: string, cwd?: string): this; positional(key: string, opt?: Options): this; recommendCommands(): this; // Alias of demand() require(key: string, msg: string | boolean): this; require(count: number, max?: number, msg?: string | boolean): this; requiresArg(key: string | Array): this; reset(): this; scriptName(name: string): this; showCompletionScript(): this; showHelp(consoleLevel?: "error" | "warn" | "log"): this; showHelp(printCallback: (usageData: string) => void): this; showHelpOnFail(enable: boolean, message?: string): this; strict(): this; skipValidation(key: string): this; strict(global?: boolean): this; string(key: string | Array): this; terminalWidth(): number; updateLocale(obj: { [key: string]: string, ... }): this; updateStrings(obj: { [key: string]: string, ... }): this; usage(message: string, opts?: { [key: string]: Options, ... }): this; version(): this; version(version: string | false): this; version(option: string | (() => string), version: string): this; version( option: string | (() => string), description: string | (() => string), version: string ): this; wrap(columns: number | null): this; } declare module.exports: Yargs; } ================================================ FILE: globals.js ================================================ /* @flow */ /* eslint import/no-commonjs: off */ const postRobotGlobals = require("@krakenjs/post-robot/globals"); const pkg = require("./package.json"); const formatVersion = (version) => { return version.replace(/[^\d]+/g, "_"); }; module.exports = { __POST_ROBOT__: { ...postRobotGlobals.__POST_ROBOT__, __AUTO_SETUP__: false, }, __ZOID__: { __VERSION__: `${formatVersion(pkg.version)}`, __GLOBAL_KEY__: `__zoid_${formatVersion(pkg.version)}__`, __IFRAME_SUPPORT__: true, __POPUP_SUPPORT__: true, __FRAMEWORK_SUPPORT__: false, __DEFAULT_CONTAINER__: true, __DEFAULT_PRERENDER__: true, __SCRIPT_NAMESPACE__: false, }, }; ================================================ FILE: index.js ================================================ /* @flow */ /* eslint import/no-commonjs: 0, import/extensions: 0 */ // eslint-disable-next-line no-process-env if (process && process.env && process.env.ZOID_FRAME_ONLY) { // $FlowFixMe module.exports = require("./dist/zoid.frame"); // $FlowFixMe module.exports.default = module.exports; } else { // $FlowFixMe module.exports = require("./dist/zoid"); // $FlowFixMe module.exports.default = module.exports; } ================================================ FILE: karma.conf.js ================================================ /* @flow */ /* eslint import/no-default-export: off */ import { getKarmaConfig } from "@krakenjs/karma-config-grumbler"; import { WEBPACK_CONFIG_TEST } from "./webpack.config"; // List libs that can be dynamically loaded // Those files should be available(served), but not included as default const serveWithoutInclude = [ "test/lib/angular-4.js", "test/lib/angular-12/zone_v0.8.12.js", "test/lib/angular-12/rxjs_v6.2.0.js", "test/lib/angular-12/angular-12-core.js", "test/lib/angular-12/angular-12-common.js", "test/lib/angular-12/angular-12-compiler.js", "test/lib/angular-12/angular-12-platform-browser.js", "test/lib/angular-12/angular-12-platform-browser-dynamic.js", "test/lib/vue_v2.5.16.runtime.min.js", "test/lib/vue_v3.2.1.js", ].map((file) => ({ pattern: file, included: false, served: true, })); export default function configKarma(karma: Object) { const karmaConfig = getKarmaConfig(karma, { basePath: __dirname, webpack: WEBPACK_CONFIG_TEST, }); karmaConfig.client.useIframe = false; karma.set({ ...karmaConfig, files: [ "test/lib/react_v16.0.0.js", "test/lib/react-dom_v16.0.0.js", "test/lib/angular.min.js", { pattern: "test/zoid.global.js", included: true, served: true, }, ...serveWithoutInclude, ...karmaConfig.files, ], preprocessors: { ...karmaConfig.preprocessors, "src/index.js": ["webpack", "sourcemap"], "src/**/*.js": ["sourcemap"], }, }); } ================================================ FILE: package.json ================================================ { "name": "@krakenjs/zoid", "version": "10.5.1", "description": "Cross domain components.", "main": "index.js", "scripts": { "setup": "npm install && npm run flow-typed", "demo": "serve . -l 1337", "lint": "eslint --ext .js --ext .jsx src/ test/ *.js", "flow-typed": "rm -rf ./flow-typed && flow-typed install", "flow": "flow", "format": "prettier --write --ignore-unknown .", "format:check": "prettier --check .", "karma": "cross-env NODE_ENV=test babel-node --plugins=@babel/plugin-transform-modules-commonjs ./node_modules/.bin/karma start", "babel": "babel src/ --out-dir dist/module", "webpack": "babel-node --plugins=@babel/plugin-transform-modules-commonjs ./node_modules/.bin/webpack -- --progress", "test": "npm run format:check && npm run lint && npm run flow && npm run karma", "clear-dist": "rm -rf dist/*;", "build": "npm run test && npm run babel && npm run clear-dist && npm run webpack -- $@", "clean": "rimraf dist coverage", "reinstall": "rimraf flow-typed && rimraf node_modules && npm install && flow-typed install", "debug": "cross-env NODE_ENV=debug", "prepare": "husky install", "prebuild:release": "npm run clean && npm run test && npm run build", "prerelease": "npm run prebuild:release", "release": "standard-version", "postrelease": "git push && git push --follow-tags && npm publish", "prerelease:alpha": "npm run prebuild:release", "release:alpha": "standard-version --prerelease alpha", "postrelease:alpha": "git push && git push --follow-tags && npm publish --tag alpha" }, "standard-version": { "types": [ { "type": "feat", "section": "Features" }, { "type": "fix", "section": "Bug Fixes" }, { "type": "chore", "hidden": false }, { "type": "docs", "hidden": false }, { "type": "style", "hidden": false }, { "type": "refactor", "hidden": false }, { "type": "perf", "hidden": false }, { "type": "test", "hidden": false } ] }, "repository": { "type": "git", "url": "git://github.com/krakenjs/zoid.git" }, "keywords": [ "cross-domain", "cross domain", "components", "component", "krakenjs", "kraken" ], "browserslist": [ "IE >= 11", "chrome >= 41", "firefox >= 43", "safari >= 8", "opera >= 23" ], "licenses": [ { "type": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" } ], "files": [ "dist/", "src/", "globals.js" ], "readmeFilename": "README.md", "devDependencies": { "@commitlint/cli": "^16.2.1", "@commitlint/config-conventional": "^16.2.1", "@krakenjs/grumbler-scripts": "^8.0.4", "@krakenjs/jsx-pragmatic": "^3.0.0", "cross-env": "^7.0.3", "flow-bin": "0.155.0", "flow-typed": "^3.8.0", "husky": "^7.0.4", "jest": "^29.3.1", "lint-staged": "^12.4.0", "mocha": "^4", "prettier": "^2.6.2", "serve": "^10.0.0", "standard-version": "^9.3.2" }, "dependencies": { "@krakenjs/belter": "^2.0.0", "@krakenjs/cross-domain-utils": "^3.0.0", "@krakenjs/post-robot": "^11.0.0", "@krakenjs/zalgo-promise": "^2.0.0" }, "lint-staged": { "*": "prettier --write --ignore-unknown" } } ================================================ FILE: src/babel.config.js ================================================ /* @flow */ // eslint-disable-next-line import/no-commonjs module.exports = { extends: "@krakenjs/babel-config-grumbler/babelrc-browser", }; ================================================ FILE: src/child/child.js ================================================ /* @flow */ /* eslint max-lines: 0 */ import { isSameDomain, matchDomain, getAllFramesInWindow, type CrossDomainWindowType, onCloseWindow, assertSameDomain, } from "@krakenjs/cross-domain-utils/src"; import { markWindowKnown, type CrossDomainFunctionType, } from "@krakenjs/post-robot/src"; import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { extend, onResize, elementReady, noop } from "@krakenjs/belter/src"; import { getGlobal, tryGlobal, getInitialParentPayload, updateChildWindowNameWithRef, } from "../lib"; import { CONTEXT } from "../constants"; import type { NormalizedComponentOptionsType, getSiblingsPropType, } from "../component"; import type { PropsType, ChildPropsType } from "../component/props"; import type { StringMatcherType } from "../types"; import { normalizeChildProps } from "./props"; export type ChildExportsType

= {| updateProps: CrossDomainFunctionType<[PropsType

], void>, close: CrossDomainFunctionType<[], void>, name: string, |}; export type ChildHelpers = {| uid: string, tag: string, close: () => ZalgoPromise, focus: () => ZalgoPromise, resize: ({| width: ?number, height: ?number |}) => ZalgoPromise, onError: (mixed) => ZalgoPromise, onProps: ((PropsType

) => void) => {| cancel: () => void |}, getParent: () => CrossDomainWindowType, getParentDomain: () => string, show: () => ZalgoPromise, hide: () => ZalgoPromise, export: (X) => ZalgoPromise, getSiblings: getSiblingsPropType, |}; function checkParentDomain( allowedParentDomains: StringMatcherType, domain: string ) { if (!matchDomain(allowedParentDomains, domain)) { throw new Error(`Can not be rendered by domain: ${domain}`); } } function focus(): ZalgoPromise { return ZalgoPromise.try(() => { window.focus(); }); } function destroy(): ZalgoPromise { return ZalgoPromise.try(() => { window.close(); }); } // Compares the first numerical value of the parent and child versions of zoid, // ensuring that an error is only thrown when major versions of Zoid do not match. // Additionally, zoid version strings should be in snake_case format (10_1_0, 10_2_0, 11_0_0, etc.) function versionCompatabilityCheck( version1: string, version2: string ): boolean { if (!/_/.test(version1) || !/_/.test(version2)) { throw new Error( `Versions are in an invalid format (${version1}, ${version2})` ); } return version1.split("_")[0] === version2.split("_")[0]; } export type ChildComponent = {| getProps: () => ChildPropsType, init: () => ZalgoPromise, |}; export function childComponent( options: NormalizedComponentOptionsType ): ChildComponent { const { tag, propsDef, autoResize, allowedParentDomains } = options; const onPropHandlers = []; const { parent, payload } = getInitialParentPayload(); const { win: parentComponentWindow, domain: parentDomain } = parent; let props: ChildPropsType; const exportsPromise = new ZalgoPromise(); const { version, uid, exports: parentExports, context, props: initialProps, } = payload; if (!versionCompatabilityCheck(version, __ZOID__.__VERSION__)) { throw new Error( `Parent window has zoid version ${version}, child window has version ${__ZOID__.__VERSION__}` ); } const { show, hide, close, onError, checkClose, export: parentExport, resize: parentResize, init: parentInit, } = parentExports; const getParent = () => parentComponentWindow; const getParentDomain = () => parentDomain; const onProps = (handler: Function) => { onPropHandlers.push(handler); return { cancel: () => { onPropHandlers.splice(onPropHandlers.indexOf(handler), 1); }, }; }; const resize = ({ width, height, }: {| width: ?number, height: ?number, |}): ZalgoPromise => { return parentResize.fireAndForget({ width, height }); }; const xport = (xports: X): ZalgoPromise => { exportsPromise.resolve(xports); return parentExport(xports); }; const getSiblings = ({ anyParent } = {}) => { const result = []; const currentParent = props.parent; if (typeof anyParent === "undefined") { anyParent = !currentParent; } if (!anyParent && !currentParent) { throw new Error(`No parent found for ${tag} child`); } for (const win of getAllFramesInWindow(window)) { if (!isSameDomain(win)) { continue; } const xprops: ChildPropsType = assertSameDomain(win).xprops; if (!xprops || getParent() !== xprops.getParent()) { continue; } const winParent = xprops.parent; if (!anyParent && currentParent) { if (!winParent || winParent.uid !== currentParent.uid) { continue; } } const xports = tryGlobal(win, (global) => global.exports); result.push({ props: xprops, exports: xports, }); } return result; }; const getHelpers = (): ChildHelpers => { return { tag, show, hide, close, focus, onError, resize, getSiblings, onProps, getParent, getParentDomain, uid, export: xport, }; }; const watchForClose = () => { window.addEventListener("beforeunload", () => { checkClose.fireAndForget(); }); if ("onpagehide" in window) { window.addEventListener("pagehide", () => { checkClose.fireAndForget(); }); } else { window.addEventListener("unload", () => { checkClose.fireAndForget(); }); } onCloseWindow(parentComponentWindow, () => { destroy(); }); }; const setProps = ( newProps: PropsType

, origin: string, isUpdate: boolean = false ) => { const helpers = getHelpers(); const normalizedProps = normalizeChildProps( parentComponentWindow, propsDef, newProps, origin, helpers, isUpdate ); if (props) { extend(props, normalizedProps); } else { props = normalizedProps; } for (const handler of onPropHandlers) { handler(props); } }; const getAutoResize = (): ZalgoPromise<{| width: boolean, height: boolean, element: ?HTMLElement, |}> => { const { width = false, height = false, element: elementRef = "body", } = autoResize; return elementReady(elementRef) .catch(noop) .then((element) => { return { width, height, element }; }); }; const watchForResize = (): ?ZalgoPromise => { return getAutoResize().then(({ width, height, element }) => { if (!element || (!width && !height) || context === CONTEXT.POPUP) { return; } onResize( element, ({ width: newWidth, height: newHeight }) => { resize({ width: width ? newWidth : undefined, height: height ? newHeight : undefined, }); }, { width, height } ); }); }; const updateProps = (newProps: PropsType

): ZalgoPromise => { return ZalgoPromise.try(() => setProps(newProps, parentDomain, true)); }; const init = () => { return ZalgoPromise.try(() => { let updatedChildName = ""; if (isSameDomain(parentComponentWindow)) { updatedChildName = updateChildWindowNameWithRef({ componentName: options.name, parentComponentWindow, }) || ""; } getGlobal(window).exports = options.exports({ getExports: () => exportsPromise, }); checkParentDomain(allowedParentDomains, parentDomain); markWindowKnown(parentComponentWindow); watchForClose(); return parentInit({ name: updatedChildName, updateProps, close: destroy, }); }) .then(() => { return watchForResize(); }) .catch((err) => { onError(err); }); }; const getProps = () => { if (props) { return props; } else { setProps(initialProps, parentDomain); return props; } }; return { init, getProps, }; } ================================================ FILE: src/child/index.js ================================================ /* @flow */ export * from "./child"; ================================================ FILE: src/child/props.js ================================================ /* @flow */ import { getDomain, isSameDomain, matchDomain, type CrossDomainWindowType, } from "@krakenjs/cross-domain-utils/src"; import type { PropsDefinitionType, PropsType, ChildPropsType, } from "../component/props"; import type { ChildHelpers } from "./index"; export function normalizeChildProp( // $FlowFixMe propsDef: PropsDefinitionType, props: PropsType

, key: string, value: ?T, helpers: ChildHelpers ): ?T { if (!propsDef.hasOwnProperty(key)) { return value; } const prop = propsDef[key]; if (typeof prop.childDecorate === "function") { const { uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings, } = helpers; const decoratedValue = prop.childDecorate({ value, uid, tag, close, focus, onError, onProps, resize, getParent, getParentDomain, show, hide, export: xport, getSiblings, }); // $FlowFixMe return decoratedValue; } return value; } // eslint-disable-next-line max-params export function normalizeChildProps( parentComponentWindow: CrossDomainWindowType, propsDef: PropsDefinitionType, props: PropsType

, origin: string, helpers: ChildHelpers, isUpdate: boolean = false ): ChildPropsType { const result = {}; for (const key of Object.keys(props)) { const prop = propsDef[key]; const trustedChild: boolean = prop && prop.trustedDomains && prop.trustedDomains.length > 0 ? prop.trustedDomains.reduce((acc, val) => { return acc || matchDomain(val, getDomain(window)); }, false) : origin === getDomain(window) || isSameDomain(parentComponentWindow); // let trustedDomains override sameDomain prop if (prop && prop.sameDomain && !trustedChild) { continue; } // sameDomain was not set and trusted domains must match if (prop && prop.trustedDomains && !trustedChild) { continue; } // $FlowFixMe const value = normalizeChildProp(propsDef, props, key, props[key], helpers); result[key] = value; if (prop && prop.alias && !result[prop.alias]) { result[prop.alias] = value; } } if (!isUpdate) { for (const key of Object.keys(propsDef)) { if (!props.hasOwnProperty(key)) { result[key] = normalizeChildProp( propsDef, props, key, undefined, helpers ); } } } // $FlowFixMe return result; } ================================================ FILE: src/component/component.js ================================================ /* @flow */ /* eslint max-lines: 0 */ import { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot, } from "@krakenjs/post-robot/src"; import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher, } from "@krakenjs/cross-domain-utils/src"; import { noop, isElement, cleanup, memoize, identity, extend, uniqueID, } from "@krakenjs/belter/src"; import { childComponent, type ChildComponent } from "../child"; import { type ParentComponent, type RenderOptionsType, type ParentHelpers, parentComponent, } from "../parent/parent"; import { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE, } from "../constants"; import { react, angular, vue, vue3, angular2 } from "../drivers"; import { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow, } from "../lib"; import type { CssDimensionsType, StringMatcherType, ContainerReferenceType, } from "../types"; import { validateOptions } from "./validate"; import { defaultContainerTemplate, defaultPrerenderTemplate, } from "./templates"; import { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType, type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE, } from "./props"; type LoggerPayload = { [string]: ?string | ?boolean }; // eslint-disable-next-line flowtype/require-exact-type type Logger = { info: (event: string, payload?: LoggerPayload) => any, // eslint-disable-line flowtype/no-weak-types }; /* Component --------- This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance of Component with the blueprint needed to set up ParentComponents and ChildComponents. This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and contains all of the configuration needed for them to set themselves up. */ type Attributes = {| iframe?: { [string]: string }, popup?: { [string]: string }, |}; export type ExportsConfigDefinition = {| [string]: {| type: DEFINITION_TYPE, |}, |}; export type ExportsMapperDefinition = ({| getExports: () => ZalgoPromise, |}) => X; export type ExportsDefinition = | ExportsConfigDefinition | ExportsMapperDefinition; export type ComponentOptionsType = {| tag: string, getExtensions?: (parent: ParentComponent) => ExtType, url: string | (({| props: PropsType

|}) => string), domain?: DomainMatcher, bridgeUrl?: string, method?: $Values, props?: UserPropsDefinitionType, dimensions?: | CssDimensionsType | (({| props: PropsType

|}) => CssDimensionsType), autoResize?: {| width?: boolean, height?: boolean, element?: string |}, allowedParentDomains?: StringMatcherType, attributes?: Attributes | (({| props: PropsType

|}) => Attributes), eligible?: ({| props: PropsInputType

|}) => {| eligible: boolean, reason?: string, |}, defaultContext?: $Values, containerTemplate?: (RenderOptionsType

) => ?HTMLElement, prerenderTemplate?: (RenderOptionsType

) => ?HTMLElement, validate?: ({| props: PropsInputType

|}) => void, logger?: Logger, children?: () => C, exports?: ExportsDefinition, |}; export type AttributesType = {| iframe?: { [string]: string }, popup?: { [string]: string }, |}; type AutoResizeType = {| width?: boolean, height?: boolean, element?: string, |}; export type NormalizedComponentOptionsType = {| tag: string, name: string, getExtensions: (parent: ParentComponent) => ExtType, url: string | (({| props: PropsType

|}) => string), domain: ?DomainMatcher, bridgeUrl: ?string, method: ?$Values, propsDef: PropsDefinitionType, dimensions: | CssDimensionsType | (({| props: PropsType

|}) => CssDimensionsType), autoResize: AutoResizeType, allowedParentDomains: StringMatcherType, attributes: AttributesType | (({| props: PropsType

|}) => AttributesType), eligible: ({| props: PropsInputType

|}) => {| eligible: boolean, reason?: string, |}, defaultContext: $Values, containerTemplate: (RenderOptionsType

) => ?HTMLElement, prerenderTemplate: ?(RenderOptionsType

) => ?HTMLElement, validate: ?({| props: PropsInputType

|}) => void, logger: Logger, children: () => C, exports: ExportsMapperDefinition, |}; export type ZoidComponentInstance = {| ...ExtType, ...ParentHelpers

, ...X, ...C, isEligible: () => boolean, clone: () => ZoidComponentInstance, render: ( container?: ContainerReferenceType, context?: $Values ) => ZalgoPromise, renderTo: ( target: CrossDomainWindowType, container?: ContainerReferenceType, context?: $Values ) => ZalgoPromise, |}; // eslint-disable-next-line flowtype/require-exact-type export type ZoidComponent = { (props?: PropsInputType

| void): ZoidComponentInstance, // eslint-disable-next-line no-undef driver: (string, mixed) => T, isChild: () => boolean, xprops?: PropsType

, canRenderTo: (CrossDomainWindowType) => ZalgoPromise, instances: $ReadOnlyArray>, }; const getDefaultAttributes = (): AttributesType => { // $FlowFixMe return {}; }; const getDefaultAutoResize = (): AutoResizeType => { // $FlowFixMe return {}; }; const getDefaultExports = (): (() => X) => { // $FlowFixMe return noop; }; const getDefaultDimensions = (): CssDimensionsType => { // $FlowFixMe return {}; }; function getDefaultGetExtensions(): ( parent: ParentComponent ) => ExtType { return function getExtensions(): ExtType { // $FlowFixMe const ext: ExtType = {}; return ext; }; } function normalizeOptions( options: ComponentOptionsType ): NormalizedComponentOptionsType { const { tag, url, domain, bridgeUrl, props = {}, getExtensions = getDefaultGetExtensions(), dimensions = getDefaultDimensions(), autoResize = getDefaultAutoResize(), allowedParentDomains = WILDCARD, attributes = getDefaultAttributes(), defaultContext = CONTEXT.IFRAME, containerTemplate = __ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null, prerenderTemplate = __ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null, validate, eligible = () => ({ eligible: true }), logger = { info: noop }, exports: xportsDefinition = getDefaultExports(), method, children = (): C => { // $FlowFixMe return {}; }, } = options; const name = tag.replace(/-/g, "_"); // $FlowFixMe[incompatible-type] // $FlowFixMe[cannot-spread-inexact] const propsDef: PropsDefinitionType = { ...getBuiltInProps(), ...props, }; if (!containerTemplate) { throw new Error(`Container template required`); } const xports = typeof xportsDefinition === "function" ? xportsDefinition : ({ getExports }): X => { const result = {}; for (const key of Object.keys(xportsDefinition)) { const { type } = xportsDefinition[key]; const valuePromise = getExports().then((res) => { // $FlowFixMe return res[key]; }); if (type === PROP_TYPE.FUNCTION) { result[key] = (...args) => valuePromise.then((value) => value(...args)); } else { result[key] = valuePromise; } } // $FlowFixMe return result; }; return { name, tag, url, domain, bridgeUrl, method, propsDef, dimensions, autoResize, allowedParentDomains, attributes, defaultContext, containerTemplate, prerenderTemplate, validate, logger, eligible, children, exports: xports, getExtensions, }; } let cleanInstances = cleanup(); const cleanZoid = cleanup(); export type Component = {| init: ( props?: PropsInputType

| void ) => ZoidComponentInstance, instances: $ReadOnlyArray>, driver: (string, mixed) => mixed, isChild: () => boolean, canRenderTo: (CrossDomainWindowType) => ZalgoPromise, registerChild: () => ?ChildComponent, |}; export function component( opts: ComponentOptionsType ): Component { if (__DEBUG__) { validateOptions(opts); } const options = normalizeOptions(opts); const { name, tag, defaultContext, propsDef, eligible, children, getExtensions, } = options; const global = getGlobal(window); const driverCache = {}; const instances = []; const isChild = (): boolean => { if (isChildComponentWindow(name)) { const { payload } = getInitialParentPayload(); if ( payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain()) ) { return true; } } return false; }; const registerChild = memoize((): ?ChildComponent => { if (isChild()) { if (window.xprops) { delete global.components[tag]; throw new Error( `Can not register ${name} as child - child already registered` ); } const child = childComponent(options); child.init(); return child; } }); const listenForDelegate = () => { const allowDelegateListener = on( `${POST_MESSAGE.ALLOW_DELEGATE}_${name}`, () => { return true; } ); const delegateListener = on( `${POST_MESSAGE.DELEGATE}_${name}`, ({ source, data: { uid, overrides } }) => { return { parent: parentComponent({ uid, options, overrides, parentWin: source, }), }; } ); cleanZoid.register(allowDelegateListener.cancel); cleanZoid.register(delegateListener.cancel); }; const canRenderTo = (win: CrossDomainWindowType): ZalgoPromise => { return send(win, `${POST_MESSAGE.ALLOW_DELEGATE}_${name}`) .then(({ data }) => { return data; }) .catch(() => { return false; }); }; const getDefaultContainer = ( context: $Values, container?: ContainerReferenceType ): ContainerReferenceType => { if (container) { if (typeof container !== "string" && !isElement(container)) { throw new TypeError(`Expected string or element selector to be passed`); } return container; } if (context === CONTEXT.POPUP) { return "body"; } throw new Error(`Expected element to be passed to render iframe`); }; const getDefaultContext = ( props: PropsInputType

, context: ?$Values ): ZalgoPromise<$Values> => { return ZalgoPromise.try(() => { if (props.window) { return toProxyWindow(props.window).getType(); } if (context) { if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) { throw new Error(`Unrecognized context: ${context}`); } return context; } return defaultContext; }); }; const getDefaultInputProps = (): PropsInputType

=> { // $FlowFixMe return {}; }; const init = ( inputProps?: PropsInputType

| void ): ZoidComponentInstance => { // eslint-disable-next-line prefer-const let instance; const uid = `${ZOID}-${tag}-${uniqueID()}`; const props = inputProps || getDefaultInputProps(); const { eligible: eligibility, reason } = eligible({ props }); const isEligible = () => eligibility; const onDestroy = props.onDestroy; props.onDestroy = (...args) => { if (instance && eligibility) { instances.splice(instances.indexOf(instance), 1); } if (onDestroy) { return onDestroy(...args); } }; const parent = parentComponent({ uid, options, }); parent.init(); if (eligibility) { parent.setProps(props); } else { if (props.onDestroy) { props.onDestroy(); } } cleanInstances.register((err) => { return parent.destroy(err || new Error(`zoid destroyed all components`)); }); const clone = ({ decorate = identity } = {}) => { return init(decorate(props)); }; const getChildren = (): C => { // $FlowFixMe const childComponents: {| [string]: ZoidComponent |} = children(); const result = {}; for (const childName of Object.keys(childComponents)) { const Child: ZoidComponent = childComponents[childName]; result[childName] = (childInputProps) => { const parentProps: PropsType

= parent.getProps(); const parentExport: exportPropType = parent.export; const childParent: ParentPropType = { uid, props: parentProps, export: parentExport, }; const childProps: PropsInputType = { ...childInputProps, parent: childParent, }; return Child(childProps); }; } // $FlowFixMe return result; }; const render = (target, container, context) => { return ZalgoPromise.try(() => { if (!eligibility) { const err = new Error(reason || `${name} component is not eligible`); return parent.destroy(err).then(() => { throw err; }); } if (!isWindow(target)) { throw new Error(`Must pass window to renderTo`); } return getDefaultContext(props, context); }) .then((finalContext) => { container = getDefaultContainer(finalContext, container); if (target !== window && typeof container !== "string") { throw new Error( `Must pass string element when rendering to another window` ); } return parent.render({ target, container, context: finalContext, rerender: () => { const newInstance = clone(); extend(instance, newInstance); return newInstance.renderTo(target, container, context); }, }); }) .catch((err) => { return parent.destroy(err).then(() => { throw err; }); }); }; instance = { ...getExtensions(parent), ...parent.getExports(), ...parent.getHelpers(), ...getChildren(), isEligible, clone, render: (container, context) => render(window, container, context), renderTo: (target, container, context) => render(target, container, context), }; if (eligibility) { instances.push(instance); } return instance; }; const driver = (driverName: string, dep: mixed): mixed => { if (__ZOID__.__FRAMEWORK_SUPPORT__) { const drivers = { react, angular, vue, vue3, angular2 }; if (!drivers[driverName]) { throw new Error(`Could not find driver for framework: ${driverName}`); } if (!driverCache[driverName]) { driverCache[driverName] = drivers[driverName].register( tag, propsDef, init, dep ); } return driverCache[driverName]; } else { throw new Error(`Driver support not enabled`); } }; registerChild(); listenForDelegate(); global.components = global.components || {}; if (global.components[tag]) { throw new Error( `Can not register multiple components with the same tag: ${tag}` ); } global.components[tag] = true; return { init, instances, driver, isChild, canRenderTo, registerChild, }; } export type ComponentDriverType = {| register: ( string, PropsDefinitionType, (PropsInputType

) => ZoidComponentInstance, L ) => D, |}; export type ZoidProps

= PropsType

; // eslint-disable-next-line no-undef export type CreateZoidComponent = ( // eslint-disable-next-line no-undef options: ComponentOptionsType // eslint-disable-next-line no-undef ) => ZoidComponent; export const create: CreateZoidComponent = ( options: ComponentOptionsType ): ZoidComponent => { setupPostRobot(); const comp = component(options); const init = (props?: PropsInputType

| void) => comp.init(props); init.driver = (name, dep) => comp.driver(name, dep); init.isChild = () => comp.isChild(); init.canRenderTo = (win) => comp.canRenderTo(win); init.instances = comp.instances; const child = comp.registerChild(); if (child) { window.xprops = init.xprops = child.getProps(); } return init; }; export function destroyComponents(err?: mixed): ZalgoPromise { if (bridge) { bridge.destroyBridges(); } const destroyPromise = cleanInstances.all(err); cleanInstances = cleanup(); return destroyPromise; } export const destroyAll = destroyComponents; export function destroy(err?: mixed): ZalgoPromise { destroyAll(); destroyGlobal(); destroyPostRobot(); return cleanZoid.all(err); } ================================================ FILE: src/component/index.js ================================================ /* @flow */ export * from "./component"; export * from "./props"; ================================================ FILE: src/component/props.js ================================================ /* @flow */ /* eslint max-lines: off */ import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { once, noop, type EventEmitterType } from "@krakenjs/belter/src"; import { isWindow, type CrossDomainWindowType, type DomainMatcher, isWindowClosed, isSameDomain, } from "@krakenjs/cross-domain-utils/src"; import { ProxyWindow, toProxyWindow } from "@krakenjs/post-robot/src"; import type { CssDimensionsType } from "../types"; import { PROP_SERIALIZATION, PROP_TYPE } from "../constants"; export type EventHandlerType = (T) => void | ZalgoPromise; export type Sibling = {| props: mixed, exports: mixed, |}; export type timeoutPropType = number; export type windowPropType = CrossDomainWindowType | ProxyWindow; export type cspNoncePropType = string; export type uidPropType = string; export type tagPropType = string; export type closePropType = () => ZalgoPromise; export type focusPropType = () => ZalgoPromise; export type showPropType = () => ZalgoPromise; export type exportPropType = (X) => ZalgoPromise; export type getSiblingsPropType = (opts?: {| anyParent?: boolean, |}) => $ReadOnlyArray; export type hidePropType = () => ZalgoPromise; export type resizePropType = ({| width: ?number, height: ?number, |}) => ZalgoPromise; export type getParentPropType = () => CrossDomainWindowType; export type getParentDomainPropType = () => string; export type onDisplayPropType = EventHandlerType; export type onRenderedPropType = EventHandlerType; export type onRenderPropType = EventHandlerType; export type onPrerenderedPropType = EventHandlerType; export type onPrerenderPropType = EventHandlerType; export type onClosePropType = EventHandlerType; export type onDestroyPropType = EventHandlerType; export type onResizePropType = EventHandlerType; export type onFocusPropType = EventHandlerType; export type onBfcacheCachePropType = EventHandlerType; export type onBfcacheRestorePropType = EventHandlerType<{| cachedDurationMs: ?number, |}>; export type onErrorPropType = EventHandlerType; // eslint-disable-next-line no-use-before-define export type onPropsPropType

= ((PropsType

) => void) => {| cancel: () => void, |}; export type ParentPropType = {| uid: string, // eslint-disable-next-line no-use-before-define props: PropsType

, export: exportPropType, |}; export type PropsInputType

= {| parent?: ParentPropType, timeout?: timeoutPropType, window?: windowPropType, cspNonce?: ?cspNoncePropType, onDisplay?: onDisplayPropType, onRendered?: onRenderedPropType, onRender?: onRenderPropType, onPrerendered?: onPrerenderedPropType, onPrerender?: onPrerenderPropType, onClose?: onClosePropType, onDestroy?: onDestroyPropType, onResize?: onResizePropType, onFocus?: onFocusPropType, onBfcacheCache?: onBfcacheCachePropType, onBfcacheRestore?: onBfcacheRestorePropType, onError?: onErrorPropType, onProps?: onPropsPropType

, ...P, |}; export type PropsType

= {| timeout?: timeoutPropType, window?: ?windowPropType, cspNonce?: ?cspNoncePropType, dimensions: CssDimensionsType, onDisplay: onDisplayPropType, onRendered: onRenderedPropType, onRender: onRenderPropType, onPrerendered: onPrerenderedPropType, onPrerender: onPrerenderPropType, onClose: onClosePropType, onDestroy: onDestroyPropType, onResize: onResizePropType, onFocus: onFocusPropType, onError: onErrorPropType, onBfcacheCache: EventHandlerType, onBfcacheRestore: EventHandlerType<{| cachedDurationMs: ?number |}>, onProps: onPropsPropType

, ...P, |}; type onErrorChildPropType = (mixed) => ZalgoPromise; export type ChildPropsType = {| ...PropsType

, parent?: ParentPropType, uid: uidPropType, tag: tagPropType, close: closePropType, focus: focusPropType, show: showPropType, hide: hidePropType, export: exportPropType, getParent: getParentPropType, getParentDomain: getParentDomainPropType, resize: resizePropType, onError: onErrorChildPropType, onProps: onPropsPropType

, getSiblings: getSiblingsPropType, |}; export type PropDefinitionType, X> = {| type: S, alias?: string, value?: ({| props: P, state: Object, close: () => ZalgoPromise, focus: () => ZalgoPromise, onError: (mixed) => ZalgoPromise, container: HTMLElement | void, event: EventEmitterType, |}) => ?T, default?: ({| props: P, state: Object, close: () => ZalgoPromise, focus: () => ZalgoPromise, onError: (mixed) => ZalgoPromise, container: HTMLElement | void, event: EventEmitterType, |}) => ?T, decorate?: ({| value: T, props: PropsType

, state: Object, close: () => ZalgoPromise, focus: () => ZalgoPromise, onError: (mixed) => ZalgoPromise, container: HTMLElement | void, event: EventEmitterType, |}) => T, childDecorate?: ({| value: ?T, uid: uidPropType, tag: tagPropType, close: closePropType, focus: focusPropType, onError: onErrorPropType, onProps: onPropsPropType

, resize: resizePropType, getParentDomain: getParentDomainPropType, getParent: getParentPropType, show: showPropType, hide: hidePropType, export: exportPropType, getSiblings: getSiblingsPropType, |}) => ?T, required?: boolean, queryParam?: | boolean | string | (({| value: T |}) => string | ZalgoPromise), bodyParam?: | boolean | string | (({| value: T |}) => string | ZalgoPromise), // eslint-disable-next-line no-undef queryValue?: ({| value: T |}) => ZalgoPromise | R | string, // eslint-disable-next-line no-undef bodyValue?: ({| value: T |}) => ZalgoPromise | R | string, sendToChild?: boolean, allowDelegate?: boolean, validate?: ({| value: T, props: PropsType

|}) => void, sameDomain?: boolean, serialization?: $Values, trustedDomains?: $ReadOnlyArray, |}; export type BOOLEAN_DEFINITION_TYPE = typeof PROP_TYPE.BOOLEAN; export type STRING_DEFINITION_TYPE = typeof PROP_TYPE.STRING; export type NUMBER_DEFINITION_TYPE = typeof PROP_TYPE.NUMBER; export type FUNCTION_DEFINITION_TYPE = typeof PROP_TYPE.FUNCTION; export type ARRAY_DEFINITION_TYPE = typeof PROP_TYPE.ARRAY; export type OBJECT_DEFINITION_TYPE = typeof PROP_TYPE.OBJECT; export type DEFINITION_TYPE = | BOOLEAN_DEFINITION_TYPE | STRING_DEFINITION_TYPE | NUMBER_DEFINITION_TYPE | FUNCTION_DEFINITION_TYPE | ARRAY_DEFINITION_TYPE | OBJECT_DEFINITION_TYPE; export type BooleanPropDefinitionType = PropDefinitionType< T, P, BOOLEAN_DEFINITION_TYPE, X >; export type StringPropDefinitionType = PropDefinitionType< T, P, STRING_DEFINITION_TYPE, X >; export type NumberPropDefinitionType = PropDefinitionType< T, P, NUMBER_DEFINITION_TYPE, X >; export type FunctionPropDefinitionType = PropDefinitionType< T, P, FUNCTION_DEFINITION_TYPE, X >; export type ArrayPropDefinitionType< // eslint-disable-next-line flowtype/no-mutable-array T: Array<*> | $ReadOnlyArray<*>, P, X > = PropDefinitionType; export type ObjectPropDefinitionType = PropDefinitionType< T, P, OBJECT_DEFINITION_TYPE, X >; export type MixedPropDefinitionType = | BooleanPropDefinitionType<*, P, X> | StringPropDefinitionType<*, P, X> | NumberPropDefinitionType<*, P, X> | FunctionPropDefinitionType<*, P, X> | ObjectPropDefinitionType<*, P, X> | ArrayPropDefinitionType<*, P, X>; export type UserPropsDefinitionType = {| [string]: MixedPropDefinitionType, |}; export type BuiltInPropsDefinitionType = {| timeout: NumberPropDefinitionType, window: ObjectPropDefinitionType, close: FunctionPropDefinitionType, focus: FunctionPropDefinitionType, resize: FunctionPropDefinitionType, uid: StringPropDefinitionType, tag: StringPropDefinitionType, cspNonce: StringPropDefinitionType, getParent: FunctionPropDefinitionType, getParentDomain: FunctionPropDefinitionType, hide: FunctionPropDefinitionType, show: FunctionPropDefinitionType, export: FunctionPropDefinitionType, P, X>, getSiblings: FunctionPropDefinitionType, onDisplay: FunctionPropDefinitionType, onRendered: FunctionPropDefinitionType, onRender: FunctionPropDefinitionType, onPrerendered: FunctionPropDefinitionType, onPrerender: FunctionPropDefinitionType, onClose: FunctionPropDefinitionType, onDestroy: FunctionPropDefinitionType, onResize: FunctionPropDefinitionType, onFocus: FunctionPropDefinitionType, onBfcacheCache: FunctionPropDefinitionType, onBfcacheRestore: FunctionPropDefinitionType, onError: FunctionPropDefinitionType, onProps: FunctionPropDefinitionType, P, X>, |}; export type PropsDefinitionType = {| ...BuiltInPropsDefinitionType, [string]: MixedPropDefinitionType, |}; const defaultNoop = () => noop; // eslint-disable-next-line flowtype/require-exact-type const decorateOnce = ({ value }: { value: F }): F => once(value); export function getBuiltInProps(): BuiltInPropsDefinitionType { return { window: { type: PROP_TYPE.OBJECT, sendToChild: false, required: false, allowDelegate: true, validate: ({ value }) => { if (!isWindow(value) && !ProxyWindow.isProxyWindow(value)) { throw new Error(`Expected Window or ProxyWindow`); } if (isWindow(value)) { // $FlowFixMe if (isWindowClosed(value)) { throw new Error(`Window is closed`); } // $FlowFixMe if (!isSameDomain(value)) { throw new Error(`Window is not same domain`); } } }, decorate: ({ value }) => { return toProxyWindow(value); }, }, timeout: { type: PROP_TYPE.NUMBER, required: false, sendToChild: false, }, cspNonce: { type: PROP_TYPE.STRING, required: false, }, onDisplay: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, decorate: decorateOnce, }, onRendered: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, default: defaultNoop, decorate: decorateOnce, }, onRender: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, default: defaultNoop, decorate: decorateOnce, }, onPrerendered: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, default: defaultNoop, decorate: decorateOnce, }, onPrerender: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, default: defaultNoop, decorate: decorateOnce, }, onClose: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, decorate: decorateOnce, }, onDestroy: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, decorate: decorateOnce, }, onResize: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, }, onFocus: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, }, // Note: decorateOnce is intentionally omitted for bfcache events. // Unlike other lifecycle props, these can fire multiple times as the page // transitions in and out of bfcache (cache -> restore -> cache -> restore). onBfcacheCache: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, }, onBfcacheRestore: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, allowDelegate: true, default: defaultNoop, }, close: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ close }) => close, }, focus: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ focus }) => focus, }, resize: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ resize }) => resize, }, uid: { type: PROP_TYPE.STRING, required: false, sendToChild: false, childDecorate: ({ uid }) => uid, }, tag: { type: PROP_TYPE.STRING, required: false, sendToChild: false, childDecorate: ({ tag }) => tag, }, getParent: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ getParent }) => getParent, }, getParentDomain: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ getParentDomain }) => getParentDomain, }, show: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ show }) => show, }, hide: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ hide }) => hide, }, export: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ export: xport }) => xport, }, onError: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ onError }) => onError, }, onProps: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ onProps }) => onProps, }, getSiblings: { type: PROP_TYPE.FUNCTION, required: false, sendToChild: false, childDecorate: ({ getSiblings }) => getSiblings, }, }; } type PropCallback = (( string, BooleanPropDefinitionType | void, boolean ) => R) & ((string, StringPropDefinitionType | void, string) => R) & ((string, NumberPropDefinitionType | void, number) => R) & ((string, FunctionPropDefinitionType | void, Function) => R) & (( string, ArrayPropDefinitionType<$ReadOnlyArray<*> | $ReadOnlyArray<*>, P, X> | void, $ReadOnlyArray<*> | $ReadOnlyArray<*> ) => R) & ((string, ObjectPropDefinitionType | void, Object) => R); export function eachProp( props: PropsType

, propsDef: PropsDefinitionType, handler: PropCallback ) { // $FlowFixMe[cannot-spread-indexer] for (const key of Object.keys({ ...props, ...propsDef })) { const propDef = propsDef[key]; const value = props[key]; // $FlowFixMe[incompatible-call] handler(key, propDef, value); } } export function mapProps( props: PropsType

, propsDef: PropsDefinitionType, handler: PropCallback ): $ReadOnlyArray { const results = []; eachProp(props, propsDef, (key, propDef, value) => { // $FlowFixMe[incompatible-call] const result = handler(key, propDef, value); results.push(result); }); return results; } ================================================ FILE: src/component/templates/component.js ================================================ /* @flow */ /* eslint react/react-in-jsx-scope: off */ import { type RenderOptionsType } from "../../parent/parent"; export function defaultPrerenderTemplate

({ doc, props, }: RenderOptionsType

): ?HTMLElement { if (__ZOID__.__DEFAULT_PRERENDER__) { const html = doc.createElement("html"); const body = doc.createElement("body"); const style = doc.createElement("style"); const spinner = doc.createElement("div"); spinner.classList.add("spinner"); if (props.cspNonce) { style.setAttribute("nonce", props.cspNonce); } html.appendChild(body); body.appendChild(spinner); body.appendChild(style); style.appendChild( doc.createTextNode(` html, body { width: 100%; height: 100%; } .spinner { position: fixed; max-height: 60vmin; max-width: 60vmin; height: 40px; width: 40px; top: 50%; left: 50%; box-sizing: border-box; border: 3px solid rgba(0, 0, 0, .2); border-top-color: rgba(33, 128, 192, 0.8); border-radius: 100%; animation: rotation .7s infinite linear; } @keyframes rotation { from { transform: translateX(-50%) translateY(-50%) rotate(0deg); } to { transform: translateX(-50%) translateY(-50%) rotate(359deg); } } `) ); return html; } } ================================================ FILE: src/component/templates/container.js ================================================ /* @flow */ /* eslint react/react-in-jsx-scope: off */ import { destroyElement, toCSS } from "@krakenjs/belter/src"; import { type RenderOptionsType } from "../../parent/parent"; import { EVENT } from "../../constants"; const CLASS = { VISIBLE: "zoid-visible", INVISIBLE: "zoid-invisible", }; export function defaultContainerTemplate

({ uid, frame, prerenderFrame, doc, props, event, dimensions, }: RenderOptionsType

): ?HTMLElement { const { width, height } = dimensions; if (__ZOID__.__DEFAULT_CONTAINER__) { if (!frame || !prerenderFrame) { return; } const div = doc.createElement("div"); div.setAttribute("id", uid); const style = doc.createElement("style"); if (props.cspNonce) { style.setAttribute("nonce", props.cspNonce); } style.appendChild( doc.createTextNode(` #${uid} { display: inline-block; position: relative; width: ${width}; height: ${height}; } #${uid} > iframe { display: inline-block; position: absolute; width: 100%; height: 100%; top: 0; left: 0; transition: opacity .2s ease-in-out; } #${uid} > iframe.${CLASS.INVISIBLE} { opacity: 0; } #${uid} > iframe.${CLASS.VISIBLE} { opacity: 1; } `) ); div.appendChild(frame); div.appendChild(prerenderFrame); div.appendChild(style); prerenderFrame.classList.add(CLASS.VISIBLE); frame.classList.add(CLASS.INVISIBLE); event.on(EVENT.RENDERED, () => { prerenderFrame.classList.remove(CLASS.VISIBLE); prerenderFrame.classList.add(CLASS.INVISIBLE); frame.classList.remove(CLASS.INVISIBLE); frame.classList.add(CLASS.VISIBLE); setTimeout(() => { destroyElement(prerenderFrame); }, 1); }); event.on(EVENT.RESIZE, ({ width: newWidth, height: newHeight }) => { if (typeof newWidth === "number") { div.style.width = toCSS(newWidth); } if (typeof newHeight === "number") { div.style.height = toCSS(newHeight); } }); return div; } } ================================================ FILE: src/component/templates/index.js ================================================ /* @flow */ export * from "./container"; export * from "./component"; ================================================ FILE: src/component/validate.js ================================================ /* @flow */ import { isPerc, isPx, values } from "@krakenjs/belter/src"; import { CONTEXT, PROP_TYPE } from "../constants"; import type { ComponentOptionsType } from "./index"; function validatepropsDefinitions( options: ComponentOptionsType ) { if (options.props && !(typeof options.props === "object")) { throw new Error(`Expected options.props to be an object`); } const PROP_TYPE_LIST = values(PROP_TYPE); if (options.props) { for (const key of Object.keys(options.props)) { const prop = options.props[key]; if (!prop || !(typeof prop === "object")) { throw new Error(`Expected options.props.${key} to be an object`); } if (!prop.type) { throw new Error(`Expected prop.type`); } if (PROP_TYPE_LIST.indexOf(prop.type) === -1) { throw new Error( `Expected prop.type to be one of ${PROP_TYPE_LIST.join(", ")}` ); } if (prop.required && prop.default) { throw new Error(`Required prop can not have a default value`); } if ( prop.type === PROP_TYPE.FUNCTION && prop.queryParam && !prop.queryValue ) { throw new Error(`Do not pass queryParam for function prop`); } } } } // eslint-disable-next-line complexity export function validateOptions( options: ?ComponentOptionsType ) { // eslint-ignore-line if (!options) { throw new Error(`Expected options to be passed`); } // eslint-disable-next-line security/detect-unsafe-regex if (!options.tag || !options.tag.match(/^([a-z0-9][a-z0-9-]*)+[a-z0-9]+$/)) { throw new Error(`Invalid options.tag: ${options.tag}`); } validatepropsDefinitions(options); const { dimensions } = options; if (dimensions) { if (typeof dimensions === "function") { // pass } else if (typeof dimensions === "object" && dimensions !== null) { if (!isPx(dimensions.height) && !isPerc(dimensions.height)) { throw new Error( `Expected options.dimensions.height to be a px or % string value` ); } if (!isPx(dimensions.width) && !isPerc(dimensions.width)) { throw new Error( `Expected options.dimensions.width to be a px or % string value` ); } } else { throw new Error(`Expected dimensions to be a function or object`); } } if (options.defaultContext) { if ( options.defaultContext !== CONTEXT.IFRAME && options.defaultContext !== CONTEXT.POPUP ) { throw new Error( `Unsupported context type: ${options.defaultContext || "unknown"}` ); } } if (!options.url) { throw new Error(`Must pass url`); } if (typeof options.url !== "string" && typeof options.url !== "function") { throw new TypeError(`Expected url to be string or function`); } if ( options.prerenderTemplate && typeof options.prerenderTemplate !== "function" ) { throw new Error(`Expected options.prerenderTemplate to be a function`); } if ( (options.containerTemplate || !__ZOID__.__DEFAULT_CONTAINER__) && typeof options.containerTemplate !== "function" ) { throw new Error(`Expected options.containerTemplate to be a function`); } } ================================================ FILE: src/constants.js ================================================ /* @flow */ import { WINDOW_TYPE } from "@krakenjs/cross-domain-utils/src"; export const ZOID = `zoid`; export const POST_MESSAGE = { DELEGATE: `${ZOID}_delegate`, ALLOW_DELEGATE: `${ZOID}_allow_delegate`, }; export const COMPONENT_ERROR = { NAVIGATED_AWAY: "Window navigated away", COMPONENT_DESTROYED: "Component destroyed", COMPONENT_CLOSED: "Component closed", WINDOW_CLOSED: "Detected component window close", IFRAME_CLOSE: "Detected iframe close", }; export const PROP_TYPE = { STRING: ("string": "string"), OBJECT: ("object": "object"), FUNCTION: ("function": "function"), BOOLEAN: ("boolean": "boolean"), NUMBER: ("number": "number"), ARRAY: ("array": "array"), }; export const WINDOW_REFERENCE = { OPENER: ("opener": "opener"), PARENT: ("parent": "parent"), GLOBAL: ("global": "global"), NAME: ("name": "name"), }; export const PROP_SERIALIZATION = { JSON: ("json": "json"), DOTIFY: ("dotify": "dotify"), BASE64: ("base64": "base64"), }; export const CONTEXT = WINDOW_TYPE; export const WILDCARD = "*"; export const DEFAULT_DIMENSIONS = { WIDTH: "300px", HEIGHT: "150px", }; export const EVENT = { RENDER: "zoid-render", RENDERED: "zoid-rendered", PRERENDER: "zoid-prerender", PRERENDERED: "zoid-prerendered", DISPLAY: "zoid-display", ERROR: "zoid-error", CLOSE: "zoid-close", DESTROY: "zoid-destroy", PROPS: "zoid-props", RESIZE: "zoid-resize", FOCUS: "zoid-focus", BFCACHE_CACHE: "zoid-bfcache-cache", BFCACHE_RESTORE: "zoid-bfcache-restore", }; export const METHOD = { GET: ("get": "get"), POST: ("post": "post"), }; ================================================ FILE: src/declarations.js ================================================ /* @flow */ declare var __ZOID__: {| __VERSION__: string, __GLOBAL_KEY__: string, __POPUP_SUPPORT__: boolean, __IFRAME_SUPPORT__: boolean, __FRAMEWORK_SUPPORT__: boolean, __DEFAULT_CONTAINER__: boolean, __DEFAULT_PRERENDER__: boolean, __SCRIPT_NAMESPACE__: boolean, |}; declare var __DEBUG__: boolean; ================================================ FILE: src/drivers/angular.js ================================================ /* @flow */ import { dasherizeToCamel, replaceObject, noop } from "@krakenjs/belter/src"; import type { ComponentDriverType } from "../component"; import { CONTEXT } from "../constants"; type AngularModule = {| directive: ( string, () => {| scope: { [string]: "=" | "@" }, restrict: string, controller: $ReadOnlyArray, |} ) => AngularModule, |}; type Angular = {| module: (string, $ReadOnlyArray) => AngularModule, |}; export const angular: ComponentDriverType<*, Angular, AngularModule, *, *> = { register: (tag, propsDef, init, ng) => { const module = ng.module(tag, []).directive(dasherizeToCamel(tag), () => { const scope = {}; for (const key of Object.keys(propsDef)) { scope[key] = "="; } scope.props = "="; return { scope, restrict: "E", controller: [ "$scope", "$element", ($scope, $element) => { function safeApply() { if ( $scope.$root.$$phase !== "$apply" && $scope.$root.$$phase !== "$digest" ) { try { $scope.$apply(); } catch (err) { // pass } } } const getProps = () => { return replaceObject($scope.props, (item) => { if (typeof item === "function") { return function angularWrapped(): mixed { // $FlowFixMe const result = item.apply(this, arguments); safeApply(); return result; }; } return item; }); }; const instance = init(getProps()); instance.render($element[0], CONTEXT.IFRAME); $scope.$watch(() => { instance.updateProps(getProps()).catch(noop); }); }, ], }; }); return module; }, }; ================================================ FILE: src/drivers/angular2.js ================================================ /* @flow */ /* eslint new-cap: 0 */ import { replaceObject } from "@krakenjs/belter/src"; import type { ComponentDriverType } from "../component"; import { CONTEXT } from "../constants"; type Angular2Injection = {||}; type Angular2Component = {||}; type Angular2Module = {| annotations: Object, name: string |}; type Angular2 = {| Component: ({| selector: string, template: string, inputs: $ReadOnlyArray, |}) => {| Class: ({| constructor: $ReadOnlyArray, ngOnInit: () => void, ngDoCheck: () => void, |}) => Angular2Component, |}, NgModule: ({| declarations: $ReadOnlyArray<*>, exports: $ReadOnlyArray<*>, |}) => {| Class: ({| constructor: () => void |}) => Angular2Module, |}, ElementRef: Angular2Injection, NgZone: Angular2Injection, Inject: Function, |}; const equals = (obj1, obj2) => { const checked = {}; for (const key in obj1) { if (obj1.hasOwnProperty(key)) { checked[key] = true; if (obj1[key] !== obj2[key]) { return false; } } } for (const key in obj2) { if (!checked[key]) { return false; } } return true; }; export const angular2: ComponentDriverType<*, Angular2, Angular2Module, *, *> = { register: ( tag, propsDef, init, { Component: AngularComponent, NgModule, ElementRef, NgZone, Inject } ) => { class ComponentInstance { elementRef: Object; internalProps: Object; parent: Object; props: Object; zone: Object; _props: Object; static annotations: $ReadOnlyArray<*>; static parameters: $ReadOnlyArray<*>; constructor(elementRef, zone) { this._props = {}; this.elementRef = elementRef; this.zone = zone; } getProps(): Object { return replaceObject( { ...this.internalProps, ...this.props }, (item) => { if (typeof item === "function") { const { zone } = this; return function angular2Wrapped(): void { // $FlowFixMe return zone.run(() => item.apply(this, arguments)); }; } return item; } ); } ngOnInit() { const targetElement = this.elementRef.nativeElement; this.parent = init(this.getProps()); this.parent.render(targetElement, CONTEXT.IFRAME); } ngDoCheck() { if (this.parent && !equals(this._props, this.props)) { this._props = { ...this.props }; this.parent.updateProps(this.getProps()); } } } ComponentInstance.parameters = [ [new Inject(ElementRef)], [new Inject(NgZone)], ]; ComponentInstance.annotations = [ new AngularComponent({ selector: tag, template: `

`, inputs: ["props"], }), ]; class ModuleInstance { static annotations: $ReadOnlyArray<*>; } ModuleInstance.annotations = [ new NgModule({ declarations: [ComponentInstance], exports: [ComponentInstance], }), ]; return ModuleInstance; }, }; ================================================ FILE: src/drivers/index.js ================================================ /* @flow */ export * from "./react"; export * from "./vue"; export * from "./vue3"; export * from "./angular"; export * from "./angular2"; ================================================ FILE: src/drivers/react.js ================================================ /* @flow */ /* eslint react/no-deprecated: off, react/no-find-dom-node: off, react/display-name: off, react/no-did-mount-set-state: off, react/destructuring-assignment: off, react/prop-types: off */ import { extend, noop } from "@krakenjs/belter/src"; import type { ComponentDriverType } from "../component"; import { CONTEXT } from "../constants"; declare class ReactClassType {} declare class __ReactComponent {} type ReactElementType = {||}; type ReactType = {| Component: __ReactComponent, createClass: ({| render: () => ReactElementType, componentDidMount: () => void, componentDidUpdate: () => void, |}) => typeof ReactClassType, createElement: ( string, ?{ [string]: mixed }, ...children: $ReadOnlyArray ) => ReactElementType, |}; type ReactDomType = {| findDOMNode: (typeof ReactClassType) => HTMLElement, |}; type ReactLibraryType = {| React: ReactType, ReactDOM: ReactDomType, |}; export const react: ComponentDriverType< *, ReactLibraryType, typeof ReactClassType, *, * > = { register: (tag, propsDef, init, { React, ReactDOM }) => { // $FlowFixMe return class extends React.Component { render(): ReactElementType { return React.createElement("div", null); } componentDidMount() { // $FlowFixMe const el = ReactDOM.findDOMNode(this); const parent = init(extend({}, this.props)); parent.render(el, CONTEXT.IFRAME); this.setState({ parent }); } componentDidUpdate() { if (this.state && this.state.parent) { this.state.parent.updateProps(extend({}, this.props)).catch(noop); } } }; }, }; ================================================ FILE: src/drivers/vue.js ================================================ /* @flow */ import { noop, dasherizeToCamel } from "@krakenjs/belter/src"; import type { ComponentDriverType } from "../component"; import { CONTEXT } from "../constants"; type VueComponent = {| render: (Function) => Element, inheritAttrs: boolean, mounted: () => void, watch: {| $attrs: {| deep: boolean, handler: () => void, |}, |}, |}; type RegisteredVueComponent = {||}; type VueType = {| component: (string, VueComponent) => RegisteredVueComponent, |}; function propsToCamelCase(props: Object): Object { return Object.keys(props).reduce((acc, key) => { const value = props[key]; // In vue `style` is a reserved prop name if (key === "style-object" || key === "styleObject") { acc.style = value; // To keep zoid as generic as possible, passing in the original prop name as well acc.styleObject = value; } else if (key.includes("-")) { acc[dasherizeToCamel(key)] = value; } else { acc[key] = value; } return acc; }, {}); } export const vue: ComponentDriverType< *, VueType, RegisteredVueComponent, *, * > = { register: (tag, propsDef, init, Vue) => { return Vue.component(tag, { render(createElement): Element { return createElement("div"); }, inheritAttrs: false, mounted() { // $FlowFixMe[object-this-reference] const el = this.$el; // $FlowFixMe[object-this-reference] this.parent = init({ ...propsToCamelCase(this.$attrs) }); // $FlowFixMe[object-this-reference] this.parent.render(el, CONTEXT.IFRAME); }, watch: { $attrs: { handler: function handler() { if (this.parent && this.$attrs) { this.parent.updateProps({ ...this.$attrs }).catch(noop); } }, deep: true, }, }, }); }, }; ================================================ FILE: src/drivers/vue3.js ================================================ /* @flow */ import { dasherizeToCamel, noop } from "@krakenjs/belter/src"; import type { ComponentDriverType } from "../component"; import { CONTEXT } from "../constants"; function propsToCamelCase(props: Object): Object { return Object.keys(props).reduce((acc, key) => { const value = props[key]; // In vue `style` is a reserved prop name if (key === "style-object" || key === "styleObject") { acc.style = value; // To keep zoid as generic as possible, passing in the original prop name as well acc.styleObject = value; } else if (key.includes("-")) { acc[dasherizeToCamel(key)] = value; } else { acc[key] = value; } return acc; }, {}); } export const vue3: ComponentDriverType<*, *, *, *, *> = { register: (tag, propsDef, init) => { return { template: `
`, inheritAttrs: false, mounted() { // $FlowFixMe[object-this-reference] const el = this.$el; // $FlowFixMe[object-this-reference] this.parent = init({ ...propsToCamelCase(this.$attrs) }); // $FlowFixMe[object-this-reference] this.parent.render(el, CONTEXT.IFRAME); }, watch: { $attrs: { handler: function handler() { if (this.parent && this.$attrs) { this.parent.updateProps({ ...this.$attrs }).catch(noop); } }, deep: true, }, }, }; }, }; ================================================ FILE: src/index.js ================================================ /* @flow */ import typeof { PopupOpenError } from "@krakenjs/belter/src"; import type { CreateZoidComponent } from "./component"; // eslint-disable-next-line no-duplicate-imports import typeof { destroy, destroyComponents, destroyAll } from "./component"; import typeof { PROP_TYPE, PROP_SERIALIZATION, CONTEXT, EVENT, } from "./constants"; export { PopupOpenError } from "@krakenjs/belter/src"; export type { ZoidComponent, ZoidComponentInstance, ZoidProps, } from "./component"; export type { RenderOptionsType } from "./parent"; export { create, destroy, destroyComponents, destroyAll } from "./component"; export { PROP_TYPE, PROP_SERIALIZATION, CONTEXT, EVENT } from "./constants"; export type Zoid = {| create: CreateZoidComponent, destroy: destroy, destroyComponents: destroyComponents, destroyAll: destroyAll, PROP_TYPE: PROP_TYPE, PROP_SERIALIZATION: PROP_SERIALIZATION, CONTEXT: CONTEXT, EVENT: EVENT, PopupOpenError: PopupOpenError, |}; ================================================ FILE: src/lib/global.js ================================================ /* @flow */ import { isSameDomain, type CrossDomainWindowType, } from "@krakenjs/cross-domain-utils/src"; import { getCurrentScriptUID } from "@krakenjs/belter/src"; export function getGlobalKey(): string { if (__ZOID__.__SCRIPT_NAMESPACE__) { return `${__ZOID__.__GLOBAL_KEY__}_${getCurrentScriptUID()}`; } else { return __ZOID__.__GLOBAL_KEY__; } } export function getGlobal(win: CrossDomainWindowType): T { const globalKey = getGlobalKey(); if (!isSameDomain(win)) { throw new Error(`Can not get global for window on different domain`); } if (!win[globalKey]) { win[globalKey] = {}; } return win[globalKey]; } export function tryGlobal( win: CrossDomainWindowType, handler: (T) => R ): ?R { try { return handler(getGlobal(win)); } catch (err) { // pass } } export function destroyGlobal() { const globalKey = getGlobalKey(); delete window[globalKey]; } ================================================ FILE: src/lib/index.js ================================================ /* @flow */ export * from "./global"; export * from "./serialize"; export * from "./window"; ================================================ FILE: src/lib/serialize.js ================================================ /* @flow */ import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { serializeMessage, deserializeMessage, toProxyWindow, type ProxyWindow, } from "@krakenjs/post-robot/src"; import { uniqueID, base64encode, base64decode } from "@krakenjs/belter/src"; import type { CrossDomainWindowType, DomainMatcher, } from "@krakenjs/cross-domain-utils/src"; import { getGlobal } from "./global"; export type ProxyObject = {| get: () => ZalgoPromise, |}; export function getProxyObject(obj: T): ProxyObject { return { get(): ZalgoPromise { return ZalgoPromise.try(() => { // $FlowFixMe[object-this-reference] if (this.source && this.source !== window) { throw new Error( `Can not call get on proxy object from a remote window` ); } return obj; }); }, }; } export function basicSerialize(data: T): string { return base64encode(JSON.stringify(data)); } export function basicDeserialize(serializedData: string): T { return JSON.parse(base64decode(serializedData)); } export const REFERENCE_TYPE = { UID: ("uid": "uid"), RAW: ("raw": "raw"), }; export type UIDReferenceType = {| type: typeof REFERENCE_TYPE.UID, uid: string, |}; export type RawReferenceType = {| type: typeof REFERENCE_TYPE.RAW, val: T |}; export type ReferenceType = UIDReferenceType | RawReferenceType; export function getUIDRefStore(win: CrossDomainWindowType): { [string]: T } { const global = getGlobal(win); global.references = global.references || {}; return global.references; } export function getUIDRef(val: T): ReferenceType { const uid = uniqueID(); const references = getUIDRefStore(window); references[uid] = val; return { type: REFERENCE_TYPE.UID, uid }; } export function getRawRef(val: T): ReferenceType { return { type: REFERENCE_TYPE.RAW, val }; } export function getRefValue( win: CrossDomainWindowType, ref: ReferenceType ): T { if (ref.type === REFERENCE_TYPE.RAW) { return ref.val; } if (ref.type === REFERENCE_TYPE.UID) { const references = getUIDRefStore(win); return references[ref.uid]; } throw new Error(`Unsupported ref type: ${ref.type}`); } export function cleanupRef( win: CrossDomainWindowType, ref: ReferenceType ) { if (ref.type === REFERENCE_TYPE.UID) { const references = getUIDRefStore(win); delete references[ref.uid]; } } type Message = {| sender: {| domain: string, |}, metaData: M, reference: ReferenceType, |}; type CrossDomainSerializeOptions = {| data: T, metaData: M, sender: {| domain: string, |}, receiver: {| win: ProxyWindow | CrossDomainWindowType, domain: DomainMatcher, |}, passByReference?: boolean, basic?: boolean, |}; type CrossDomainSerializedMessage = {| serializedData: string, cleanReference: () => void, |}; export function crossDomainSerialize({ data, metaData, sender, receiver, passByReference = false, basic = false, }: CrossDomainSerializeOptions): CrossDomainSerializedMessage { const proxyWin = toProxyWindow(receiver.win); const serializedMessage = basic ? JSON.stringify(data) : serializeMessage(proxyWin, receiver.domain, data); const reference = passByReference ? getUIDRef(serializedMessage) : getRawRef(serializedMessage); const message: Message = { sender: { domain: sender.domain, }, metaData, reference, }; const cleanReference = () => { cleanupRef(window, reference); }; return { serializedData: basicSerialize(message), cleanReference, }; } type CrossDomainDeserializeOptions = {| data: string, sender: {| win: CrossDomainWindowType | (({| metaData: M |}) => CrossDomainWindowType), domain?: string | (({| metaData: M |}) => string), |}, basic?: boolean, |}; type CrossDomainDeserializedMessage = {| data: T, metaData: M, sender: {| domain: string, win: CrossDomainWindowType, |}, reference: ReferenceType, |}; export function crossDomainDeserialize({ data, sender, basic = false, }: CrossDomainDeserializeOptions): CrossDomainDeserializedMessage { const message: Message = basicDeserialize(data); const { reference, metaData } = message; let win; if (typeof sender.win === "function") { win = sender.win({ metaData }); } else { win = sender.win; } let domain; if (typeof sender.domain === "function") { domain = sender.domain({ metaData }); } else if (typeof sender.domain === "string") { domain = sender.domain; } else { domain = message.sender.domain; } const serializedData = getRefValue(win, reference); const deserializedData = basic ? JSON.parse(serializedData) : deserializeMessage(win, domain, serializedData); return { data: deserializedData, metaData, sender: { win, domain }, reference, }; } ================================================ FILE: src/lib/window.js ================================================ /* @flow */ import { assertExists, memoize } from "@krakenjs/belter/src"; import { isSameDomain, getOpener, getNthParentFromTop, getAncestor, getAllFramesInWindow, getParent, isTop, findFrameByName, getDomain, assertSameDomain, type CrossDomainWindowType, getDistanceFromTop, } from "@krakenjs/cross-domain-utils/src"; import { ZOID, WINDOW_REFERENCE } from "../constants"; import type { InitialChildPayload, WindowRef } from "../parent"; import { crossDomainDeserialize, crossDomainSerialize, REFERENCE_TYPE, type ReferenceType, } from "./serialize"; import { tryGlobal } from "./global"; function getWindowByRef(windowRef: WindowRef): CrossDomainWindowType { if (windowRef.type === WINDOW_REFERENCE.OPENER) { return assertExists("opener", getOpener(window)); } else if ( windowRef.type === WINDOW_REFERENCE.PARENT && typeof windowRef.distance === "number" ) { return assertExists( "parent", getNthParentFromTop(window, windowRef.distance) ); } else if ( windowRef.type === WINDOW_REFERENCE.GLOBAL && windowRef.uid && typeof windowRef.uid === "string" ) { const { uid } = windowRef; const ancestor = getAncestor(window); if (!ancestor) { throw new Error(`Can not find ancestor window`); } for (const frame of getAllFramesInWindow(ancestor)) { if (isSameDomain(frame)) { const win = tryGlobal( frame, (global) => global.windows && global.windows[uid] ); if (win) { return win; } } } } else if (windowRef.type === WINDOW_REFERENCE.NAME) { const { name } = windowRef; return assertExists( "namedWindow", findFrameByName(assertExists("ancestor", getAncestor(window)), name) ); } throw new Error(`Unable to find ${windowRef.type} parent component window`); } export function buildChildWindowName({ name, serializedPayload, }: {| name: string, serializedPayload: string, |}): string { return `__${ZOID}__${name}__${serializedPayload}__`; } function parseWindowName(windowName: string): {| name: string, serializedInitialPayload: string, |} { if (!windowName) { throw new Error(`No window name`); } const [, zoidcomp, name, serializedInitialPayload] = windowName.split("__"); if (zoidcomp !== ZOID) { throw new Error(`Window not rendered by zoid - got ${zoidcomp}`); } if (!name) { throw new Error(`Expected component name`); } if (!serializedInitialPayload) { throw new Error(`Expected serialized payload ref`); } return { name, serializedInitialPayload }; } export type InitialParentPayload = {| parent: {| domain: string, win: CrossDomainWindowType, |}, payload: InitialChildPayload, reference: ReferenceType, |}; const parseInitialParentPayload = memoize( (windowName: string): InitialParentPayload => { const { serializedInitialPayload } = parseWindowName(windowName); const { data: payload, sender: parent, reference, } = crossDomainDeserialize({ data: serializedInitialPayload, sender: { win: ({ metaData: { windowRef } }) => getWindowByRef(windowRef), }, }); return { parent, payload, reference, }; } ); export function getInitialParentPayload(): InitialParentPayload { return parseInitialParentPayload(window.name); } export function isChildComponentWindow(name: string): boolean { try { return parseWindowName(window.name).name === name; } catch (err) { // pass } return false; } export function getWindowRef( targetWindow: CrossDomainWindowType, currentWindow?: CrossDomainWindowType = window ): ?WindowRef { if (targetWindow === getParent(currentWindow)) { return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(targetWindow), }; } if (targetWindow === getOpener(currentWindow)) { return { type: WINDOW_REFERENCE.OPENER }; } if (isSameDomain(targetWindow) && !isTop(targetWindow)) { const windowName = assertSameDomain(targetWindow).name; if (windowName) { return { type: WINDOW_REFERENCE.NAME, name: windowName }; } } } type UpdateChildWindowNameWithRefOptions = {| componentName: string, parentComponentWindow: CrossDomainWindowType, |}; export function updateChildWindowNameWithRef({ componentName, parentComponentWindow, }: UpdateChildWindowNameWithRefOptions): ?string { const { serializedInitialPayload } = parseWindowName(window.name); const { data, sender, reference, metaData } = crossDomainDeserialize({ data: serializedInitialPayload, sender: { win: parentComponentWindow, }, basic: true, }); if ( reference.type === REFERENCE_TYPE.UID || metaData.windowRef.type === WINDOW_REFERENCE.GLOBAL ) { const windowRef = getWindowRef(parentComponentWindow); const { serializedData: serializedPayload } = crossDomainSerialize({ data, metaData: { windowRef, }, sender: { domain: sender.domain, }, receiver: { win: window, domain: getDomain(), }, basic: true, }); const childWindowName = buildChildWindowName({ name: componentName, serializedPayload, }); window.name = childWindowName; return childWindowName; } } ================================================ FILE: src/parent/index.js ================================================ /* @flow */ export * from "./parent"; ================================================ FILE: src/parent/parent.js ================================================ /* @flow */ /* eslint max-lines: 0 */ import { send, bridge, ProxyWindow, toProxyWindow, type CrossDomainFunctionType, cleanUpWindow, } from "@krakenjs/post-robot/src"; import { isSameDomain, matchDomain, getDomainFromUrl, isBlankDomain, getAncestor, getDomain, type CrossDomainWindowType, getDistanceFromTop, normalizeMockUrl, assertSameDomain, closeWindow, onCloseWindow, isWindowClosed, isSameTopWindow, type DomainMatcher, } from "@krakenjs/cross-domain-utils/src"; import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { addEventListener, uniqueID, elementReady, writeElementToWindow, eventEmitter, type EventEmitterType, noop, onResize, extendUrl, appendChild, cleanup, stringifyError, destroyElement, getElementSafe, showElement, hideElement, iframe, memoize, isElementClosed, awaitFrameWindow, popup, normalizeDimension, watchElementForClose, isShadowElement, insertShadowSlot, extend, } from "@krakenjs/belter/src"; import { ZOID, POST_MESSAGE, CONTEXT, EVENT, METHOD, WINDOW_REFERENCE, DEFAULT_DIMENSIONS, COMPONENT_ERROR, } from "../constants"; import { getGlobal, getProxyObject, crossDomainSerialize, buildChildWindowName, type ProxyObject, } from "../lib"; import type { PropsInputType, PropsType } from "../component/props"; import type { ChildExportsType } from "../child"; import type { CssDimensionsType, ContainerReferenceType } from "../types"; import type { NormalizedComponentOptionsType, AttributesType, } from "../component"; import { serializeProps, extendProps } from "./props"; export type RenderOptionsType

= {| uid: string, props: PropsType

, tag: string, context: $Values, close: (?string) => ZalgoPromise, focus: () => ZalgoPromise, doc: Document, container?: HTMLElement, dimensions: CssDimensionsType, state: Object, event: EventEmitterType, frame: ?HTMLIFrameElement, prerenderFrame: ?HTMLIFrameElement, |}; export type ParentExportsType = {| init: (ChildExportsType

) => ZalgoPromise, close: () => ZalgoPromise, checkClose: CrossDomainFunctionType<[], boolean>, resize: CrossDomainFunctionType< [{| width?: ?number, height?: ?number |}], void >, onError: (mixed) => ZalgoPromise, show: () => ZalgoPromise, hide: () => ZalgoPromise, export: (X) => ZalgoPromise, |}; export type WindowRef = | {| type: typeof WINDOW_REFERENCE.OPENER |} | {| type: typeof WINDOW_REFERENCE.PARENT, distance: number |} | {| type: typeof WINDOW_REFERENCE.GLOBAL, uid: string |} | {| type: typeof WINDOW_REFERENCE.NAME, name: string |}; export type InitialChildPayload = {| uid: string, tag: string, version: string, context: $Values, childDomainMatch: DomainMatcher, props: PropsType

, exports: ParentExportsType, |}; export type InitialChildPayloadMetadata = {| windowRef: WindowRef, |}; export type StateType = Object; export type ParentHelpers

= {| state: StateType, close: () => ZalgoPromise, focus: () => ZalgoPromise, resize: ({| width: ?number, height: ?number |}) => ZalgoPromise, onError: (mixed) => ZalgoPromise, updateProps: (PropsInputType

) => ZalgoPromise, event: EventEmitterType, show: () => ZalgoPromise, hide: () => ZalgoPromise, |}; function getDefaultProps

(): PropsType

{ // $FlowFixMe return {}; } type InternalState = {| visible: boolean, |}; type Rerender = () => ZalgoPromise; type RenderContainerOptions = {| context: $Values, proxyFrame: ?ProxyObject, proxyPrerenderFrame: ?ProxyObject, rerender: Rerender, |}; type ResolveInitPromise = () => ZalgoPromise; type RejectInitPromise = (mixed) => ZalgoPromise; type GetProxyContainer = ( container: ContainerReferenceType ) => ZalgoPromise>; type Show = () => ZalgoPromise; type Hide = () => ZalgoPromise; type Close = () => ZalgoPromise; type OnError = (mixed) => ZalgoPromise; type RenderContainer = ( proxyContainer: ProxyObject, RenderContainerOptions ) => ZalgoPromise>; type SetProxyWin = (ProxyWindow) => ZalgoPromise; type GetProxyWindow = () => ZalgoPromise; type OpenFrame = ( context: $Values, {| windowName: string |} ) => ZalgoPromise>; type OpenPrerenderFrame = ( context: $Values ) => ZalgoPromise>; type Prerender = ( proxyPrerenderWin: ProxyWindow, {| context: $Values |} ) => ZalgoPromise; type Open = ( context: $Values, {| proxyWin: ProxyWindow, proxyFrame: ?ProxyObject, windowName: string, |} ) => ZalgoPromise; type OpenPrerender = ( context: $Values, proxyWin: ProxyWindow, proxyPrerenderFrame: ?ProxyObject ) => ZalgoPromise; type WatchForUnload = () => ZalgoPromise; type GetInternalState = () => ZalgoPromise; type SetInternalState = (InternalState) => ZalgoPromise; type ParentDelegateOverrides

= {| props: PropsType

, event: EventEmitterType, close: Close, onError: OnError, getProxyContainer: GetProxyContainer, show: Show, hide: Hide, renderContainer: RenderContainer, getProxyWindow: GetProxyWindow, setProxyWin: SetProxyWin, openFrame: OpenFrame, openPrerenderFrame: OpenPrerenderFrame, prerender: Prerender, open: Open, openPrerender: OpenPrerender, watchForUnload: WatchForUnload, getInternalState: GetInternalState, setInternalState: SetInternalState, resolveInitPromise: ResolveInitPromise, rejectInitPromise: RejectInitPromise, |}; type DelegateOverrides = {| getProxyContainer: GetProxyContainer, show: Show, hide: Hide, renderContainer: RenderContainer, getProxyWindow: GetProxyWindow, setProxyWin: SetProxyWin, openFrame: OpenFrame, openPrerenderFrame: OpenPrerenderFrame, prerender: Prerender, open: Open, openPrerender: OpenPrerender, watchForUnload: WatchForUnload, |}; type RenderOptions = {| target: CrossDomainWindowType, container: ContainerReferenceType, context: $Values, rerender: Rerender, |}; export type ParentComponent = {| init: () => void, render: (RenderOptions) => ZalgoPromise, getProps: () => PropsType

, setProps: (newProps: PropsInputType

, isUpdate?: boolean) => void, export: (X) => ZalgoPromise, destroy: (err?: mixed) => ZalgoPromise, getHelpers: () => ParentHelpers

, getDelegateOverrides: () => ZalgoPromise, getExports: () => X, |}; const getDefaultOverrides =

(): ParentDelegateOverrides

=> { // $FlowFixMe return {}; }; type ParentOptions = {| uid: string, options: NormalizedComponentOptionsType, overrides?: ParentDelegateOverrides

, parentWin?: CrossDomainWindowType, |}; export function parentComponent({ uid, options, overrides = getDefaultOverrides(), parentWin = window, }: ParentOptions): ParentComponent { const { propsDef, containerTemplate, prerenderTemplate, tag, name, attributes, dimensions, autoResize, url, domain: domainMatch, validate, exports: xports, } = options; const initPromise = new ZalgoPromise(); const handledErrors = []; const clean = cleanup(); const state = {}; const inputProps = {}; let internalState = { visible: true, }; const event = overrides.event ? overrides.event : eventEmitter(); const props: PropsType

= overrides.props ? overrides.props : getDefaultProps(); let currentProxyWin: ?ProxyWindow; let currentProxyContainer: ?ProxyObject; let childComponent: ?ChildExportsType

; let currentChildDomain: ?string; let currentContainer: HTMLElement | void; let isRenderFinished: boolean = false; const onErrorOverride: ?OnError = overrides.onError; let getProxyContainerOverride: ?GetProxyContainer = overrides.getProxyContainer; let showOverride: ?Show = overrides.show; let hideOverride: ?Hide = overrides.hide; const closeOverride: ?Close = overrides.close; let renderContainerOverride: ?RenderContainer = overrides.renderContainer; let getProxyWindowOverride: ?GetProxyWindow = overrides.getProxyWindow; let setProxyWinOverride: ?SetProxyWin = overrides.setProxyWin; let openFrameOverride: ?OpenFrame = overrides.openFrame; let openPrerenderFrameOverride: ?OpenPrerenderFrame = overrides.openPrerenderFrame; let prerenderOverride: ?Prerender = overrides.prerender; let openOverride: ?Open = overrides.open; let openPrerenderOverride: ?OpenPrerender = overrides.openPrerender; let watchForUnloadOverride: ?WatchForUnload = overrides.watchForUnload; const getInternalStateOverride: ?GetInternalState = overrides.getInternalState; const setInternalStateOverride: ?SetInternalState = overrides.setInternalState; const getDimensions = (): CssDimensionsType => { if (typeof dimensions === "function") { return dimensions({ props }); } return dimensions; }; const resolveInitPromise = () => { return ZalgoPromise.try(() => { if (overrides.resolveInitPromise) { return overrides.resolveInitPromise(); } return initPromise.resolve(); }); }; const rejectInitPromise = (err: mixed) => { return ZalgoPromise.try(() => { if (overrides.rejectInitPromise) { return overrides.rejectInitPromise(err); } return initPromise.reject(err); }); }; const getPropsForChild = ( initialChildDomain: string ): ZalgoPromise> => { const result = {}; for (const key of Object.keys(props)) { const prop = propsDef[key]; if (prop && prop.sendToChild === false) { continue; } const trustedChild: boolean = prop && prop.trustedDomains && prop.trustedDomains.length > 0 ? prop.trustedDomains.reduce((acc, val) => { return acc || matchDomain(val, initialChildDomain); }, false) : matchDomain(initialChildDomain, getDomain(window)); // let trustedDomains override sameDomain prop if (prop && prop.sameDomain && !trustedChild) { continue; } // sameDomain was not set and trusted domains must match if (prop && prop.trustedDomains && !trustedChild) { continue; } result[key] = props[key]; } // $FlowFixMe return ZalgoPromise.hash(result); }; const setupEvents = () => { event.on(EVENT.RENDER, () => props.onRender()); event.on(EVENT.PRERENDER, () => props.onPrerender()); event.on(EVENT.DISPLAY, () => props.onDisplay()); event.on(EVENT.RENDERED, () => props.onRendered()); event.on(EVENT.PRERENDERED, () => props.onPrerendered()); event.on(EVENT.CLOSE, () => props.onClose()); event.on(EVENT.DESTROY, () => props.onDestroy()); event.on(EVENT.RESIZE, () => props.onResize()); event.on(EVENT.FOCUS, () => props.onFocus()); event.on(EVENT.BFCACHE_CACHE, () => props.onBfcacheCache()); event.on(EVENT.BFCACHE_RESTORE, (data) => props.onBfcacheRestore(data)); event.on(EVENT.PROPS, (newProps) => props.onProps(newProps)); event.on(EVENT.ERROR, (err) => { if (props && props.onError) { return props.onError(err); } else { return rejectInitPromise(err).then(() => { setTimeout(() => { throw err; }, 1); }); } }); clean.register(event.reset); }; const getInternalState = () => { return ZalgoPromise.try(() => { if (getInternalStateOverride) { return getInternalStateOverride(); } return internalState; }); }; const setInternalState = (newInternalState) => { return ZalgoPromise.try(() => { if (setInternalStateOverride) { return setInternalStateOverride(newInternalState); } internalState = { ...internalState, ...newInternalState }; return internalState; }); }; const getProxyWindow = (): ZalgoPromise => { if (getProxyWindowOverride) { return getProxyWindowOverride(); } return ZalgoPromise.try(() => { const windowProp = props.window; if (windowProp) { const proxyWin = toProxyWindow(windowProp); clean.register(() => windowProp.close()); return proxyWin; } return new ProxyWindow({ send }); }); }; const setProxyWin = (proxyWin: ProxyWindow): ZalgoPromise => { if (setProxyWinOverride) { return setProxyWinOverride(proxyWin); } return ZalgoPromise.try(() => { currentProxyWin = proxyWin; }); }; const show = (): ZalgoPromise => { if (showOverride) { return showOverride(); } return ZalgoPromise.hash({ setState: setInternalState({ visible: true }), showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null, }).then(noop); }; const hide = (): ZalgoPromise => { if (hideOverride) { return hideOverride(); } return ZalgoPromise.hash({ setState: setInternalState({ visible: false }), showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null, }).then(noop); }; const getUrl = (): string => { if (typeof url === "function") { return url({ props }); } return url; }; const getAttributes = (): AttributesType => { if (typeof attributes === "function") { return attributes({ props }); } return attributes; }; const buildQuery = (): ZalgoPromise<{| [string]: string | boolean |}> => { return serializeProps(propsDef, props, METHOD.GET); }; const buildBody = (): ZalgoPromise<{| [string]: string | boolean |}> => { return serializeProps(propsDef, props, METHOD.POST); }; const buildUrl = (): ZalgoPromise => { return buildQuery().then((query) => { return extendUrl(normalizeMockUrl(getUrl()), { query }); }); }; const getInitialChildDomain = (): string => { return getDomainFromUrl(getUrl()); }; const getDomainMatcher = (): DomainMatcher => { if (domainMatch) { return domainMatch; } return getInitialChildDomain(); }; const openFrame = ( context: $Values, { windowName }: {| windowName: string |} ): ZalgoPromise> => { if (openFrameOverride) { return openFrameOverride(context, { windowName }); } return ZalgoPromise.try(() => { if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) { // $FlowFixMe const attrs = { name: windowName, title: name, ...getAttributes().iframe, }; return getProxyObject(iframe({ attributes: attrs })); } }); }; const openPrerenderFrame = ( context: $Values ): ZalgoPromise> => { if (openPrerenderFrameOverride) { return openPrerenderFrameOverride(context); } return ZalgoPromise.try(() => { if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) { // $FlowFixMe const attrs = { name: `__${ZOID}_prerender_frame__${name}_${uniqueID()}__`, title: `prerender__${name}`, ...getAttributes().iframe, }; return getProxyObject( iframe({ attributes: attrs, }) ); } }); }; const openPrerender = ( context: $Values, proxyWin: ProxyWindow, proxyPrerenderFrame: ?ProxyObject ): ZalgoPromise => { if (openPrerenderOverride) { return openPrerenderOverride(context, proxyWin, proxyPrerenderFrame); } return ZalgoPromise.try(() => { if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) { if (!proxyPrerenderFrame) { throw new Error(`Expected proxy frame to be passed`); } return proxyPrerenderFrame.get().then((prerenderFrame) => { clean.register(() => destroyElement(prerenderFrame)); return awaitFrameWindow(prerenderFrame) .then((prerenderFrameWindow) => { return assertSameDomain(prerenderFrameWindow); }) .then((win) => { return toProxyWindow(win); }); }); } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) { return proxyWin; } else { throw new Error(`No render context available for ${context}`); } }); }; const focus = (): ZalgoPromise => { return ZalgoPromise.try(() => { if (currentProxyWin) { return ZalgoPromise.all([ event.trigger(EVENT.FOCUS), currentProxyWin.focus(), ]).then(noop); } }); }; const getCurrentWindowReferenceUID = (): string => { const global = getGlobal(window); global.windows = global.windows || {}; global.windows[uid] = window; clean.register(() => { delete global.windows[uid]; }); return uid; }; const getWindowRef = ( target: CrossDomainWindowType, initialChildDomain: string, context: $Values, proxyWin: ProxyWindow ): WindowRef => { if (initialChildDomain === getDomain(window)) { return { type: WINDOW_REFERENCE.GLOBAL, uid: getCurrentWindowReferenceUID(), }; } if (target !== window) { throw new Error( `Can not construct cross-domain window reference for different target window` ); } if (props.window) { const actualComponentWindow = proxyWin.getWindow(); if (!actualComponentWindow) { throw new Error( `Can not construct cross-domain window reference for lazy window prop` ); } if (getAncestor(actualComponentWindow) !== window) { throw new Error( `Can not construct cross-domain window reference for window prop with different ancestor` ); } } if (context === CONTEXT.POPUP) { return { type: WINDOW_REFERENCE.OPENER }; } else if (context === CONTEXT.IFRAME) { return { type: WINDOW_REFERENCE.PARENT, distance: getDistanceFromTop(window), }; } throw new Error(`Can not construct window reference for child`); }; const runTimeout = (): ZalgoPromise => { return ZalgoPromise.try(() => { const timeout = props.timeout; if (timeout) { return initPromise.timeout( timeout, new Error(`Loading component timed out after ${timeout} milliseconds`) ); } }); }; const initChild = ( childDomain: string, childExports: ChildExportsType

): ZalgoPromise => { return ZalgoPromise.try(() => { currentChildDomain = childDomain; childComponent = childExports; currentProxyWin ?.isPopup() .then((isPopup) => { if (childExports?.name !== "" && isPopup) { currentProxyWin?.setName(childExports?.name); } }) .finally(() => { resolveInitPromise(); clean.register(() => childExports.close.fireAndForget().catch(noop)); }); }); }; const resize = ({ width, height, }: {| width?: ?number, height?: ?number, |}): ZalgoPromise => { return ZalgoPromise.try(() => { event.trigger(EVENT.RESIZE, { width, height }); }); }; const destroy = (err: mixed): ZalgoPromise => { // eslint-disable-next-line promise/no-promise-in-callback return ZalgoPromise.try(() => { return event.trigger(EVENT.DESTROY); }) .catch(noop) .then(() => { return clean.all(err); }) .then(() => { const error = err || new Error(COMPONENT_ERROR.COMPONENT_DESTROYED); if ( (currentContainer && isElementClosed(currentContainer)) || // $FlowFixMe Object.values(COMPONENT_ERROR).includes(error.message) ) { initPromise.resolve(); } else { initPromise.asyncReject(error); } }); }; const close = memoize((err?: mixed): ZalgoPromise => { return ZalgoPromise.try(() => { if (closeOverride) { // $FlowFixMe const source = closeOverride.__source__; if (isWindowClosed(source)) { return; } return closeOverride(); } return ZalgoPromise.try(() => { return event.trigger(EVENT.CLOSE); }).then(() => { return destroy(err || new Error(COMPONENT_ERROR.COMPONENT_CLOSED)); }); }); }); const open = ( context: $Values, { proxyWin, proxyFrame, windowName, }: {| proxyWin: ProxyWindow, proxyFrame: ?ProxyObject, windowName: string, |} ): ZalgoPromise => { if (openOverride) { return openOverride(context, { proxyWin, proxyFrame, windowName }); } return ZalgoPromise.try(() => { if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) { if (!proxyFrame) { throw new Error(`Expected proxy frame to be passed`); } return proxyFrame.get().then((frame) => { return awaitFrameWindow(frame).then((win) => { clean.register(() => destroyElement(frame)); clean.register(() => cleanUpWindow(win)); return win; }); }); } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) { let { width = DEFAULT_DIMENSIONS.WIDTH, height = DEFAULT_DIMENSIONS.HEIGHT, } = getDimensions(); width = normalizeDimension(width, window.outerWidth); height = normalizeDimension(height, window.outerWidth); // $FlowFixMe const attrs = { name: windowName, width, height, ...getAttributes().popup, }; const win = popup("", attrs); clean.register(() => closeWindow(win)); clean.register(() => cleanUpWindow(win)); return win; } else { throw new Error(`No render context available for ${context}`); } }).then((win) => { proxyWin.setWindow(win, { send }); return proxyWin.setName(windowName).then(() => { return proxyWin; }); }); }; const watchForUnload = () => { return ZalgoPromise.try(() => { const eventname = "onpagehide" in window ? "pagehide" : "unload"; let bfcacheEnterTime: ?number = null; const unloadWindowListener = addEventListener( window, eventname, (evt) => { const persisted = evt instanceof PageTransitionEvent && evt.persisted; if (persisted) { bfcacheEnterTime = Date.now(); event.trigger(EVENT.BFCACHE_CACHE); } destroy(new Error(COMPONENT_ERROR.NAVIGATED_AWAY)); } ); if ("onpageshow" in window) { const pageshowListener = addEventListener(window, "pageshow", (evt) => { const persisted = evt instanceof PageTransitionEvent && evt.persisted; if (persisted) { // Flow can't narrow ?number through closures in ternaries, so capture locally first const enterTime = bfcacheEnterTime; const cachedDurationMs = enterTime !== null && enterTime !== undefined ? Date.now() - enterTime : null; bfcacheEnterTime = null; event.trigger(EVENT.BFCACHE_RESTORE, { cachedDurationMs }); } }); clean.register(pageshowListener.cancel); } const closeParentWindowListener = onCloseWindow(parentWin, destroy, 3000); clean.register(closeParentWindowListener.cancel); clean.register(unloadWindowListener.cancel); if (watchForUnloadOverride) { return watchForUnloadOverride(); } }); }; const watchForClose = ( proxyWin: ProxyWindow, context: $Values ): ZalgoPromise => { let cancelled = false; clean.register(() => { cancelled = true; }); return ZalgoPromise.delay(2000) .then(() => { return proxyWin.isClosed(); }) .then((isClosed) => { if (!cancelled) { if (context === CONTEXT.POPUP && isClosed) { return close(new Error("Detected popup close")); } const isCurrentContainerClosed: boolean = Boolean( currentContainer && isElementClosed(currentContainer) ); if ( context === CONTEXT.IFRAME && isClosed && (isCurrentContainerClosed || isRenderFinished) ) { return close(new Error(COMPONENT_ERROR.IFRAME_CLOSE)); } return watchForClose(proxyWin, context); } }); }; const checkWindowClose = (proxyWin: ProxyWindow): ZalgoPromise => { let closed = false; return proxyWin .isClosed() .then((isClosed) => { if (isClosed) { closed = true; return close(new Error(COMPONENT_ERROR.WINDOW_CLOSED)); } return ZalgoPromise.delay(200) .then(() => proxyWin.isClosed()) .then((secondIsClosed) => { if (secondIsClosed) { closed = true; return close(new Error(COMPONENT_ERROR.WINDOW_CLOSED)); } }); }) .then(() => { return closed; }); }; const onError = (err: mixed): ZalgoPromise => { if (onErrorOverride) { return onErrorOverride(err); } return ZalgoPromise.try(() => { if (handledErrors.indexOf(err) !== -1) { return; } handledErrors.push(err); initPromise.asyncReject(err); return event.trigger(EVENT.ERROR, err); }); }; const exportsPromise: ZalgoPromise = new ZalgoPromise(); const getExports = (): X => { return xports({ getExports: () => exportsPromise, }); }; const xport = (actualExports: X): ZalgoPromise => { return ZalgoPromise.try(() => { exportsPromise.resolve(actualExports); }); }; initChild.onError = onError; const buildParentExports = (win: ProxyWindow): ParentExportsType => { const checkClose = () => checkWindowClose(win); function init(childExports: ChildExportsType

): ZalgoPromise { return initChild(this.origin, childExports); } return { init, close, checkClose, resize, onError, show, hide, export: xport, }; }; const buildInitialChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, context, }: {| proxyWin: ProxyWindow, initialChildDomain: string, childDomainMatch: DomainMatcher, context: $Values, |} = {}): ZalgoPromise> => { return getPropsForChild(initialChildDomain).then((childProps) => { return { uid, context, tag, childDomainMatch, version: __ZOID__.__VERSION__, props: childProps, exports: buildParentExports(proxyWin), }; }); }; const buildSerializedChildPayload = ({ proxyWin, initialChildDomain, childDomainMatch, target = window, context, }: {| proxyWin: ProxyWindow, initialChildDomain: string, childDomainMatch: DomainMatcher, target: CrossDomainWindowType, context: $Values, |} = {}): ZalgoPromise => { return buildInitialChildPayload({ proxyWin, initialChildDomain, childDomainMatch, context, }).then((childPayload) => { const { serializedData, cleanReference } = crossDomainSerialize({ data: childPayload, metaData: { windowRef: getWindowRef( target, initialChildDomain, context, proxyWin ), }, sender: { domain: getDomain(window), }, receiver: { win: proxyWin, domain: childDomainMatch, }, passByReference: initialChildDomain === getDomain(), }); clean.register(cleanReference); return serializedData; }); }; const buildWindowName = ({ proxyWin, initialChildDomain, childDomainMatch, target, context, }: {| proxyWin: ProxyWindow, initialChildDomain: string, childDomainMatch: DomainMatcher, target: CrossDomainWindowType, context: $Values, |}): ZalgoPromise => { return buildSerializedChildPayload({ proxyWin, initialChildDomain, childDomainMatch, target, context, }).then((serializedPayload) => { return buildChildWindowName({ name, serializedPayload }); }); }; const renderTemplate = ( renderer: (RenderOptionsType

) => ?HTMLElement, { context, container, doc, frame, prerenderFrame, }: {| context: $Values, container?: HTMLElement, doc: Document, frame?: ?HTMLIFrameElement, prerenderFrame?: ?HTMLIFrameElement, |} ): ?HTMLElement => { return renderer({ uid, container, context, doc, frame, prerenderFrame, focus, close, state, props, tag, dimensions: getDimensions(), event, }); }; const prerender = ( proxyPrerenderWin: ProxyWindow, { context }: {| context: $Values |} ): ZalgoPromise => { if (prerenderOverride) { return prerenderOverride(proxyPrerenderWin, { context }); } return ZalgoPromise.try(() => { if (!prerenderTemplate) { return; } event.trigger(EVENT.PRERENDER); let prerenderWindow = proxyPrerenderWin.getWindow(); if ( !prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow) ) { return; } prerenderWindow = assertSameDomain(prerenderWindow); const doc = prerenderWindow.document; const el = renderTemplate(prerenderTemplate, { context, doc }); if (!el) { return; } if (el.ownerDocument !== doc) { throw new Error( `Expected prerender template to have been created with document from child window` ); } writeElementToWindow(prerenderWindow, el); let { width = false, height = false, element = "body" } = autoResize; element = getElementSafe(element, doc); if (element && (width || height)) { const prerenderResizeListener = onResize( element, ({ width: newWidth, height: newHeight }) => { resize({ width: width ? newWidth : undefined, height: height ? newHeight : undefined, }); }, { width, height, win: prerenderWindow } ); event.on(EVENT.RENDERED, prerenderResizeListener.cancel); } event.trigger(EVENT.PRERENDERED); }); }; const renderContainer: RenderContainer = ( proxyContainer: ProxyObject, { proxyFrame, proxyPrerenderFrame, context, rerender, }: RenderContainerOptions ): ZalgoPromise> => { if (renderContainerOverride) { return renderContainerOverride(proxyContainer, { proxyFrame, proxyPrerenderFrame, context, rerender, }); } return ZalgoPromise.hash({ container: proxyContainer.get(), // $FlowFixMe frame: proxyFrame ? proxyFrame.get() : null, // $FlowFixMe prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null, internalState: getInternalState(), }).then( ({ container, frame, prerenderFrame, internalState: { visible } }) => { const innerContainer = renderTemplate(containerTemplate, { context, container, frame, prerenderFrame, doc: document, }); if (innerContainer) { if (!visible) { hideElement(innerContainer); } appendChild(container, innerContainer); const containerWatcher = watchElementForClose(innerContainer, () => { const removeError = new Error( `Detected container element removed from DOM` ); return ZalgoPromise.delay(1).then(() => { if (isElementClosed(innerContainer)) { close(removeError); } else { clean.all(removeError); return rerender().then(resolveInitPromise, rejectInitPromise); } }); }); clean.register(() => containerWatcher.cancel()); clean.register(() => destroyElement(innerContainer)); currentProxyContainer = getProxyObject(innerContainer); return currentProxyContainer; } } ); }; const getBridgeUrl = (): ?string => { if (typeof options.bridgeUrl === "function") { return options.bridgeUrl({ props }); } return options.bridgeUrl; }; const openBridge = ( proxyWin: ProxyWindow, initialChildDomain: string, context: $Values ): ?ZalgoPromise => { if (__POST_ROBOT__.__IE_POPUP_SUPPORT__) { return ZalgoPromise.try(() => { return proxyWin.awaitWindow(); }).then((win) => { if ( !bridge || !bridge.needsBridge({ win, domain: initialChildDomain }) || bridge.hasBridge(initialChildDomain, initialChildDomain) ) { return; } const bridgeUrl = getBridgeUrl(); if (!bridgeUrl) { throw new Error(`Bridge needed to render ${context}`); } const bridgeDomain = getDomainFromUrl(bridgeUrl); bridge.linkUrl(win, initialChildDomain); return bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain); }); } }; const getHelpers = (): ParentHelpers

=> { return { state, event, close, focus, resize, onError, // eslint-disable-next-line no-use-before-define updateProps, show, hide, }; }; const getProps = () => props; const getDefaultPropsInput = (): PropsInputType

=> { // $FlowFixMe return {}; }; const setProps = ( newInputProps: PropsInputType

= getDefaultPropsInput() ) => { if (__DEBUG__ && validate) { validate({ props: newInputProps }); } const container = currentContainer; const helpers = getHelpers(); extend(inputProps, newInputProps); // $FlowFixMe extendProps(propsDef, props, inputProps, helpers, container); }; const updateProps = (newProps: PropsInputType

): ZalgoPromise => { setProps(newProps); return initPromise.then(() => { const child = childComponent; const proxyWin = currentProxyWin; const childDomain = currentChildDomain; if (!child || !proxyWin || !childDomain) { return; } return getPropsForChild(childDomain).then((childProps) => { return child.updateProps(childProps).catch((err) => { return checkWindowClose(proxyWin).then((closed) => { if (!closed) { throw err; } }); }); }); }); }; const getProxyContainer: GetProxyContainer = ( container: ContainerReferenceType ): ZalgoPromise> => { if (getProxyContainerOverride) { return getProxyContainerOverride(container); } return ZalgoPromise.try(() => { return elementReady(container); }).then((containerElement) => { if (isShadowElement(containerElement)) { containerElement = insertShadowSlot(containerElement); } currentContainer = containerElement; return getProxyObject(containerElement); }); }; const delegate = ( context: $Values, target: CrossDomainWindowType ): ZalgoPromise => { const delegateProps = {}; for (const propName of Object.keys(props)) { const propDef = propsDef[propName]; if (propDef && propDef.allowDelegate) { delegateProps[propName] = props[propName]; } } const childOverridesPromise = send( target, `${POST_MESSAGE.DELEGATE}_${name}`, { uid, overrides: { props: delegateProps, event, close, onError, getInternalState, setInternalState, resolveInitPromise, rejectInitPromise, }, } ) .then(({ data: { parent } }) => { const parentComp: ParentComponent = parent; clean.register((err) => { if (!isWindowClosed(target)) { return parentComp.destroy(err); } }); return parentComp.getDelegateOverrides(); }) .catch((err) => { throw new Error( `Unable to delegate rendering. Possibly the component is not loaded in the target window.\n\n${stringifyError( err )}` ); }); getProxyContainerOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.getProxyContainer(...args) ); renderContainerOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.renderContainer(...args) ); showOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.show(...args) ); hideOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.hide(...args) ); watchForUnloadOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.watchForUnload(...args) ); if (context === CONTEXT.IFRAME && __ZOID__.__IFRAME_SUPPORT__) { getProxyWindowOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.getProxyWindow(...args) ); openFrameOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.openFrame(...args) ); openPrerenderFrameOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.openPrerenderFrame(...args) ); prerenderOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.prerender(...args) ); openOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.open(...args) ); openPrerenderOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.openPrerender(...args) ); } else if (context === CONTEXT.POPUP && __ZOID__.__POPUP_SUPPORT__) { setProxyWinOverride = (...args) => childOverridesPromise.then((childOverrides) => childOverrides.setProxyWin(...args) ); } return childOverridesPromise; }; const getDelegateOverrides = (): ZalgoPromise => { return ZalgoPromise.try(() => { return { getProxyContainer, show, hide, renderContainer, getProxyWindow, watchForUnload, openFrame, openPrerenderFrame, prerender, open, openPrerender, setProxyWin, }; }); }; const checkAllowRender = ( target: CrossDomainWindowType, childDomainMatch: DomainMatcher, container: ContainerReferenceType ) => { if (target === window) { return; } if (!isSameTopWindow(window, target)) { throw new Error(`Can only renderTo an adjacent frame`); } const origin = getDomain(); if (!matchDomain(childDomainMatch, origin) && !isSameDomain(target)) { throw new Error( `Can not render remotely to ${childDomainMatch.toString()} - can only render to ${origin}` ); } if (container && typeof container !== "string") { throw new Error( `Container passed to renderTo must be a string selector, got ${typeof container} }` ); } }; const init = () => { setupEvents(); }; const render = ({ target, container, context, rerender, }: RenderOptions): ZalgoPromise => { return ZalgoPromise.try(() => { const initialChildDomain = getInitialChildDomain(); const childDomainMatch = getDomainMatcher(); checkAllowRender(target, childDomainMatch, container); const delegatePromise = ZalgoPromise.try(() => { if (target !== window) { return delegate(context, target); } }); const windowProp = props.window; const watchForUnloadPromise = watchForUnload(); const buildBodyPromise = buildBody(); const onRenderPromise = event.trigger(EVENT.RENDER); const getProxyContainerPromise = getProxyContainer(container); const getProxyWindowPromise = getProxyWindow(); const finalSetPropsPromise = getProxyContainerPromise.then(() => { return setProps(); }); const buildUrlPromise = finalSetPropsPromise.then(() => { return buildUrl(); }); const buildWindowNamePromise = getProxyWindowPromise.then((proxyWin) => { return buildWindowName({ proxyWin, initialChildDomain, childDomainMatch, target, context, }); }); const openFramePromise = buildWindowNamePromise.then((windowName) => openFrame(context, { windowName }) ); const openPrerenderFramePromise = openPrerenderFrame(context); const renderContainerPromise = ZalgoPromise.hash({ proxyContainer: getProxyContainerPromise, proxyFrame: openFramePromise, proxyPrerenderFrame: openPrerenderFramePromise, }) .then(({ proxyContainer, proxyFrame, proxyPrerenderFrame }) => { return renderContainer(proxyContainer, { context, proxyFrame, proxyPrerenderFrame, rerender, }); }) .then((proxyContainer) => { return proxyContainer; }); const openPromise = ZalgoPromise.hash({ windowName: buildWindowNamePromise, proxyFrame: openFramePromise, proxyWin: getProxyWindowPromise, }).then(({ windowName, proxyWin, proxyFrame }) => { return windowProp ? proxyWin : open(context, { windowName, proxyWin, proxyFrame }); }); const openPrerenderPromise = ZalgoPromise.hash({ proxyWin: openPromise, proxyPrerenderFrame: openPrerenderFramePromise, }).then(({ proxyWin, proxyPrerenderFrame }) => { return openPrerender(context, proxyWin, proxyPrerenderFrame); }); const setStatePromise = openPromise.then((proxyWin) => { currentProxyWin = proxyWin; return setProxyWin(proxyWin); }); const prerenderPromise = ZalgoPromise.hash({ proxyPrerenderWin: openPrerenderPromise, state: setStatePromise, }).then(({ proxyPrerenderWin }) => { return prerender(proxyPrerenderWin, { context }); }); const setWindowNamePromise = ZalgoPromise.hash({ proxyWin: openPromise, windowName: buildWindowNamePromise, }).then(({ proxyWin, windowName }) => { if (windowProp) { return proxyWin.setName(windowName); } }); const getMethodPromise = ZalgoPromise.hash({ body: buildBodyPromise, }).then(({ body }) => { if (options.method) { return options.method; } if (Object.keys(body).length) { return METHOD.POST; } return METHOD.GET; }); const loadUrlPromise = ZalgoPromise.hash({ proxyWin: openPromise, windowUrl: buildUrlPromise, body: buildBodyPromise, method: getMethodPromise, windowName: setWindowNamePromise, prerender: prerenderPromise, }).then(({ proxyWin, windowUrl, body, method }) => { return proxyWin.setLocation(windowUrl, { method, body }); }); const watchForClosePromise = openPromise.then((proxyWin) => { watchForClose(proxyWin, context); }); const onDisplayPromise = ZalgoPromise.hash({ container: renderContainerPromise, prerender: prerenderPromise, }).then(() => { return event.trigger(EVENT.DISPLAY); }); const openBridgePromise = openPromise.then((proxyWin) => { return openBridge(proxyWin, initialChildDomain, context); }); const runTimeoutPromise = loadUrlPromise.then(() => { return runTimeout(); }); const onRenderedPromise = initPromise.then(() => { isRenderFinished = true; return event.trigger(EVENT.RENDERED); }); return ZalgoPromise.hash({ initPromise, buildUrlPromise, onRenderPromise, getProxyContainerPromise, openFramePromise, openPrerenderFramePromise, renderContainerPromise, openPromise, openPrerenderPromise, setStatePromise, prerenderPromise, loadUrlPromise, buildWindowNamePromise, setWindowNamePromise, watchForClosePromise, onDisplayPromise, openBridgePromise, runTimeoutPromise, onRenderedPromise, delegatePromise, watchForUnloadPromise, finalSetPropsPromise, }); }) .catch((err) => { return ZalgoPromise.all([onError(err), destroy(err)]).then( () => { throw err; }, () => { throw err; } ); }) .then(noop); }; return { init, render, destroy, getProps, setProps, export: xport, getHelpers, getDelegateOverrides, getExports, }; } ================================================ FILE: src/parent/props.js ================================================ /* @flow */ import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { dotify, isDefined, base64encode, noop } from "@krakenjs/belter/src"; import { eachProp, mapProps, type PropsInputType, type PropsType, type PropsDefinitionType, } from "../component/props"; import { PROP_SERIALIZATION, METHOD, PROP_TYPE } from "../constants"; import type { ParentHelpers } from "./index"; export function extendProps( propsDef: PropsDefinitionType, existingProps: PropsType

, inputProps: PropsInputType

, helpers: ParentHelpers

, container: HTMLElement | void ) { const { state, close, focus, event, onError } = helpers; // $FlowFixMe eachProp(inputProps, propsDef, (key, propDef, val) => { let valueDetermined = false; let value = val; const getDerivedValue = () => { if (!propDef) { return value; } const alias = propDef.alias; if (alias && !isDefined(val) && isDefined(inputProps[alias])) { value = inputProps[alias]; } if (propDef.value) { value = propDef.value({ props: existingProps, state, close, focus, event, onError, container, }); } if (propDef.default && !isDefined(value) && !isDefined(inputProps[key])) { value = propDef.default({ props: existingProps, state, close, focus, event, onError, container, }); } if (isDefined(value)) { if ( propDef.type === PROP_TYPE.ARRAY ? !Array.isArray(value) : typeof value !== propDef.type ) { throw new TypeError(`Prop is not of type ${propDef.type}: ${key}`); } } else { if (propDef.required !== false && !isDefined(inputProps[key])) { throw new Error(`Expected prop "${key}" to be defined`); } } if (__DEBUG__ && isDefined(value) && propDef.validate) { // $FlowFixMe propDef.validate({ value, props: inputProps }); } if (isDefined(value) && propDef.decorate) { // $FlowFixMe value = propDef.decorate({ // $FlowFixMe value, props: existingProps, state, close, focus, event, onError, container, }); } return value; }; const getter = () => { if (valueDetermined) { return value; } valueDetermined = true; return getDerivedValue(); }; Object.defineProperty(existingProps, key, { configurable: true, enumerable: true, get: getter, }); }); // $FlowFixMe eachProp(existingProps, propsDef, noop); } export function serializeProps( propsDef: PropsDefinitionType, props: PropsType

, method: $Values ): ZalgoPromise<{ [string]: string | boolean }> { const params = {}; return ZalgoPromise.all( mapProps(props, propsDef, (key, propDef, value) => { return ZalgoPromise.resolve().then(() => { if (value === null || typeof value === "undefined" || !propDef) { return; } const getParam = { [METHOD.GET]: propDef.queryParam, [METHOD.POST]: propDef.bodyParam, }[method]; const getValue = { [METHOD.GET]: propDef.queryValue, [METHOD.POST]: propDef.bodyValue, }[method]; if (!getParam) { return; } return ZalgoPromise.hash({ finalParam: ZalgoPromise.try(() => { if (typeof getParam === "function") { // $FlowFixMe[incompatible-call] return getParam({ value }); } else if (typeof getParam === "string") { return getParam; } else { return key; } }), finalValue: ZalgoPromise.try(() => { if (typeof getValue === "function" && isDefined(value)) { // $FlowFixMe[incompatible-call] // $FlowFixMe[incompatible-return] return getValue({ value }); } else { // $FlowFixMe[incompatible-return] return value; } }), }).then(({ finalParam, finalValue }) => { let result; if (typeof finalValue === "boolean") { result = finalValue.toString(); } else if (typeof finalValue === "string") { result = finalValue.toString(); } else if (typeof finalValue === "object" && finalValue !== null) { if (propDef.serialization === PROP_SERIALIZATION.JSON) { result = JSON.stringify(finalValue); } else if (propDef.serialization === PROP_SERIALIZATION.BASE64) { result = base64encode(JSON.stringify(finalValue)); } else if ( propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization ) { result = dotify(finalValue, key); for (const dotkey of Object.keys(result)) { params[dotkey] = result[dotkey]; } return; } } else if (typeof finalValue === "number") { result = finalValue.toString(); } params[finalParam] = result; }); }); }) ).then(() => { return params; }); } ================================================ FILE: src/types.js ================================================ /* @flow */ // export something to force webpack to see this as an ES module export const TYPES = true; export type DimensionsType = {| width: number, height: number, |}; export type CssDimensionsType = {| width: string, height: string, |}; export type CancelableType = {| cancel: () => void, |}; export type StringMatcherType = string | $ReadOnlyArray | RegExp; export type ContainerReferenceType = string | HTMLElement; ================================================ FILE: test/babel.config.js ================================================ /* @flow */ // eslint-disable-next-line import/no-commonjs module.exports = { extends: "@krakenjs/babel-config-grumbler/babelrc-browser", }; ================================================ FILE: test/common.js ================================================ /* @flow */ import { ZalgoPromise } from "@krakenjs/zalgo-promise/src"; import { isWindowClosed, type CrossDomainWindowType, type SameDomainWindowType, } from "@krakenjs/cross-domain-utils/src"; import { createElement, destroyElement, uniqueID } from "@krakenjs/belter/src"; export function monkeyPatchFunction( obj: Object, name: string, handler: ({| call: () => T, args: A |}) => void ): {| cancel: () => void |} { const original = obj[name]; if (!original.monkeyPatch) { original.monkeyPatch = { handlers: [], }; obj[name] = function monkeyPatched(): T { let called = false; let result; const call = () => { if (!called) { called = true; result = original.apply(this, arguments); } return result; }; for (const monkeyHandler of original.monkeyPatch.handlers) { monkeyHandler({ args: arguments, call }); } return call(); }; } original.monkeyPatch.handlers.push(handler); const cancel = () => { original.monkeyPatch.handlers.splice( original.monkeyPatch.handlers.indexOf(handler), 1 ); }; return { cancel, }; } type OnWindowOpenOptions = {| win?: SameDomainWindowType, doc?: HTMLElement, time?: number, namePattern?: RegExp, |}; type OnWindowOpenResult = {| win: SameDomainWindowType, url: ?string, name: ?string, iframe: ?{| element: HTMLIFrameElement, |}, popup: ?{| args: [string, ?string, ?string], |}, |}; export function onWindowOpen({ win = window, doc = win.document, time = 500, namePattern = /.*/, }: OnWindowOpenOptions = {}): ZalgoPromise { return new ZalgoPromise((resolve, reject) => { const winOpenMonkeyPatch = monkeyPatchFunction( win, "open", ({ call, args }) => { const popup = call(); const [url, name] = args; if (name.match(namePattern)) { resolve({ win: popup, url, name, popup: { args }, iframe: null }); winOpenMonkeyPatch.cancel(); } } ); const createElementMonkeyPatch = monkeyPatchFunction( doc, "createElement", ({ call, args: [tagName] }) => { const el = call(); if (tagName && tagName.toLowerCase() === "iframe") { // eslint-disable-next-line prefer-const let timeout; const cleanup = () => { createElementMonkeyPatch.cancel(); // eslint-disable-next-line no-use-before-define appendChildMonkeyPatch.cancel(); clearTimeout(timeout); }; const check = () => { if ( el.contentWindow && el.name.match(/^__zoid_/) && el.name.match(namePattern) ) { cleanup(); resolve({ win: el.contentWindow, url: el.src, name: el.name, iframe: { element: el }, popup: null, }); } }; const appendChildMonkeyPatch = monkeyPatchFunction( win.HTMLElement.prototype, "appendChild", ({ call: callAppend }) => { callAppend(); check(); } ); timeout = setTimeout(() => { cleanup(); return reject(new Error(`Window not opened in ${time}ms`)); }, time); } } ); }).then(({ win: openedWindow, iframe, popup, name, url }) => { if (!openedWindow || isWindowClosed(openedWindow)) { throw new Error(`Expected win to be open`); } return { win: openedWindow, name, url, iframe, popup }; }); } let isClick = false; let clickTimeout; function doClick() { isClick = true; clearTimeout(clickTimeout); clickTimeout = setTimeout(() => { isClick = false; }, 1); } const HTMLElementClick = window.HTMLElement.prototype.click; window.HTMLElement.prototype.click = function overrideHTMLElementClick(): void { doClick(); return HTMLElementClick.apply(this, arguments); }; const windowOpen = window.open; window.open = function patchedWindowOpen(): CrossDomainWindowType { if (!isClick) { const win: Object = { closed: true, close() { // pass }, location: { href: "", pathname: "", protocol: "", host: "", hostname: "", }, }; win.parent = win.top = win; win.opener = window; return win; } return windowOpen.apply(this, arguments); }; export function runOnClick(handler: () => T): T { const testButton = createElement( "button", { id: "testButton" }, document.body ); let didError = false; let result; let error; testButton.addEventListener("click", () => { try { result = handler(); } catch (err) { didError = true; error = err; } }); testButton.click(); destroyElement(testButton); if (didError) { throw error; } else { // $FlowFixMe return result; } } export function getContainer({ parent, shadow = false, slots = false, nested = false, }: {| parent?: ?HTMLElement, shadow?: boolean, slots?: boolean, nested?: boolean, |} = {}): {| container: HTMLElement, destroy: () => void |} { const parentContainer = (parent = parent || document.body); if (!parentContainer) { throw new Error(`Expected body to be present`); } const container = document.createElement("div"); parentContainer.appendChild(container); if (!shadow) { return { container, destroy: () => { parentContainer.removeChild(container); }, }; } const customElementName = `zoid-custom-element-${uniqueID()}`; const customSlotName = `zoid-custom-slot-${uniqueID()}`; const innerWrapperName = `zoid-inner-wrapper-${uniqueID()}`; const shadowContainer = document.createElement(slots ? "slot" : "div"); shadowContainer.setAttribute("name", customSlotName); customElements.define( customElementName, class extends HTMLElement { connectedCallback() { this.attachShadow({ mode: "open" }); const shadowRoot = this.shadowRoot; if (!shadowRoot) { throw new Error(`Expected container to have shadowRoot`); } shadowRoot.appendChild(shadowContainer); } } ); customElements.define( innerWrapperName, class extends HTMLElement { connectedCallback() { const shadowRoot = this.attachShadow({ mode: "open" }); shadowRoot.appendChild(shadowContainer); } } ); const customElement = document.createElement(customElementName); parentContainer.appendChild(customElement); if (nested) { const innerWrapper = document.createElement(innerWrapperName); const customElementShadowRoot = customElement.shadowRoot; if (customElementShadowRoot) { customElementShadowRoot.appendChild(innerWrapper); } const innerWrapperShadowRoot = innerWrapper.shadowRoot; const innerWrapperContainer = document.createElement("div"); if (innerWrapperShadowRoot) { innerWrapperShadowRoot.appendChild(innerWrapperContainer); } return { container: innerWrapperContainer, destroy: () => { parentContainer.removeChild(customElement); }, }; } if (!slots) { return { container: shadowContainer, destroy: () => { parentContainer.removeChild(customElement); }, }; } const slotProviderElement = document.createElement("div"); slotProviderElement.setAttribute("slot", customSlotName); parentContainer.appendChild(slotProviderElement); return { container: slotProviderElement, destroy: () => { parentContainer.removeChild(slotProviderElement); parentContainer.removeChild(customElement); }, }; } export function getBody(win?: SameDomainWindowType = window): HTMLBodyElement { if (!win.document.body) { throw new Error(`Window has no body`); } return win.document.body; } // eslint-disable-next-line no-restricted-globals, promise/no-native export function loadScript(url: string): Promise { const scriptElement = document.createElement("script"); scriptElement.setAttribute("src", url); getBody().prepend(scriptElement); // eslint-disable-next-line no-restricted-globals, promise/no-native const scriptPromise = new Promise((resolve) => { scriptElement.addEventListener("load", () => resolve()); }); return scriptPromise; } ================================================ FILE: test/index.js ================================================ /* @flow */ import "./test"; ================================================ FILE: test/lib/angular-12/angular-12-common.js ================================================ /** * @license Angular v12.2.1 * (c) 2010-2021 Google LLC. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) : typeof define === 'function' && define.amd ? define('@angular/common', ['exports', '@angular/core'], factory) : (global = global || self, factory((global.ng = global.ng || {}, global.ng.common = {}), global.ng.core)); }(this, (function (exports, i0) { 'use strict'; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _DOM = null; function getDOM() { return _DOM; } function setDOM(adapter) { _DOM = adapter; } function setRootDomAdapter(adapter) { if (!_DOM) { _DOM = adapter; } } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. * * @security Tread carefully! Interacting with the DOM directly is dangerous and * can introduce XSS risks. */ var DomAdapter = /** @class */ (function () { function DomAdapter() { } return DomAdapter; }()); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || from); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A DI Token representing the main rendering context. In a browser this is the DOM Document. * * Note: Document might not be available in the Application Context when Application and Rendering * Contexts are not the same (e.g. when running the application in a Web Worker). * * @publicApi */ var DOCUMENT = new i0.InjectionToken('DocumentToken'); /** * This class should not be used directly by an application developer. Instead, use * {@link Location}. * * `PlatformLocation` encapsulates all calls to DOM APIs, which allows the Router to be * platform-agnostic. * This means that we can have different implementation of `PlatformLocation` for the different * platforms that Angular supports. For example, `@angular/platform-browser` provides an * implementation specific to the browser environment, while `@angular/platform-server` provides * one suitable for use with server-side rendering. * * The `PlatformLocation` class is used directly by all implementations of {@link LocationStrategy} * when they need to interact with the DOM APIs like pushState, popState, etc. * * {@link LocationStrategy} in turn is used by the {@link Location} service which is used directly * by the {@link Router} in order to navigate between routes. Since all interactions between {@link * Router} / * {@link Location} / {@link LocationStrategy} and DOM APIs flow through the `PlatformLocation` * class, they are all platform-agnostic. * * @publicApi */ var PlatformLocation = /** @class */ (function () { function PlatformLocation() { } PlatformLocation.prototype.historyGo = function (relativePosition) { throw new Error('Not implemented'); }; return PlatformLocation; }()); PlatformLocation.ɵprov = i0.ɵɵdefineInjectable({ factory: useBrowserPlatformLocation, token: PlatformLocation, providedIn: "platform" }); PlatformLocation.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'platform', // See #23917 useFactory: useBrowserPlatformLocation },] } ]; function useBrowserPlatformLocation() { return i0.ɵɵinject(BrowserPlatformLocation); } /** * @description * Indicates when a location is initialized. * * @publicApi */ var LOCATION_INITIALIZED = new i0.InjectionToken('Location Initialized'); /** * `PlatformLocation` encapsulates all of the direct calls to platform APIs. * This class should not be used directly by an application developer. Instead, use * {@link Location}. */ var BrowserPlatformLocation = /** @class */ (function (_super) { __extends(BrowserPlatformLocation, _super); function BrowserPlatformLocation(_doc) { var _this = _super.call(this) || this; _this._doc = _doc; _this._init(); return _this; } // This is moved to its own method so that `MockPlatformLocationStrategy` can overwrite it /** @internal */ BrowserPlatformLocation.prototype._init = function () { this.location = window.location; this._history = window.history; }; BrowserPlatformLocation.prototype.getBaseHrefFromDOM = function () { return getDOM().getBaseHref(this._doc); }; BrowserPlatformLocation.prototype.onPopState = function (fn) { var window = getDOM().getGlobalEventTarget(this._doc, 'window'); window.addEventListener('popstate', fn, false); return function () { return window.removeEventListener('popstate', fn); }; }; BrowserPlatformLocation.prototype.onHashChange = function (fn) { var window = getDOM().getGlobalEventTarget(this._doc, 'window'); window.addEventListener('hashchange', fn, false); return function () { return window.removeEventListener('hashchange', fn); }; }; Object.defineProperty(BrowserPlatformLocation.prototype, "href", { get: function () { return this.location.href; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserPlatformLocation.prototype, "protocol", { get: function () { return this.location.protocol; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserPlatformLocation.prototype, "hostname", { get: function () { return this.location.hostname; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserPlatformLocation.prototype, "port", { get: function () { return this.location.port; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserPlatformLocation.prototype, "pathname", { get: function () { return this.location.pathname; }, set: function (newPath) { this.location.pathname = newPath; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserPlatformLocation.prototype, "search", { get: function () { return this.location.search; }, enumerable: false, configurable: true }); Object.defineProperty(BrowserPlatformLocation.prototype, "hash", { get: function () { return this.location.hash; }, enumerable: false, configurable: true }); BrowserPlatformLocation.prototype.pushState = function (state, title, url) { if (supportsState()) { this._history.pushState(state, title, url); } else { this.location.hash = url; } }; BrowserPlatformLocation.prototype.replaceState = function (state, title, url) { if (supportsState()) { this._history.replaceState(state, title, url); } else { this.location.hash = url; } }; BrowserPlatformLocation.prototype.forward = function () { this._history.forward(); }; BrowserPlatformLocation.prototype.back = function () { this._history.back(); }; BrowserPlatformLocation.prototype.historyGo = function (relativePosition) { if (relativePosition === void 0) { relativePosition = 0; } this._history.go(relativePosition); }; BrowserPlatformLocation.prototype.getState = function () { return this._history.state; }; return BrowserPlatformLocation; }(PlatformLocation)); BrowserPlatformLocation.ɵprov = i0.ɵɵdefineInjectable({ factory: createBrowserPlatformLocation, token: BrowserPlatformLocation, providedIn: "platform" }); BrowserPlatformLocation.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'platform', // See #23917 useFactory: createBrowserPlatformLocation, },] } ]; BrowserPlatformLocation.ctorParameters = function () { return [ { type: undefined, decorators: [{ type: i0.Inject, args: [DOCUMENT,] }] } ]; }; function supportsState() { return !!window.history.pushState; } function createBrowserPlatformLocation() { return new BrowserPlatformLocation(i0.ɵɵinject(DOCUMENT)); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Joins two parts of a URL with a slash if needed. * * @param start URL string * @param end URL string * * * @returns The joined URL string. */ function joinWithSlash(start, end) { if (start.length == 0) { return end; } if (end.length == 0) { return start; } var slashes = 0; if (start.endsWith('/')) { slashes++; } if (end.startsWith('/')) { slashes++; } if (slashes == 2) { return start + end.substring(1); } if (slashes == 1) { return start + end; } return start + '/' + end; } /** * Removes a trailing slash from a URL string if needed. * Looks for the first occurrence of either `#`, `?`, or the end of the * line as `/` characters and removes the trailing slash if one exists. * * @param url URL string. * * @returns The URL string, modified if needed. */ function stripTrailingSlash(url) { var match = url.match(/#|\?|$/); var pathEndIdx = match && match.index || url.length; var droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0); return url.slice(0, droppedSlashIdx) + url.slice(pathEndIdx); } /** * Normalizes URL parameters by prepending with `?` if needed. * * @param params String of URL parameters. * * @returns The normalized URL parameters string. */ function normalizeQueryParams(params) { return params && params[0] !== '?' ? '?' + params : params; } /** * Enables the `Location` service to read route state from the browser's URL. * Angular provides two strategies: * `HashLocationStrategy` and `PathLocationStrategy`. * * Applications should use the `Router` or `Location` services to * interact with application route state. * * For instance, `HashLocationStrategy` produces URLs like * http://example.com#/foo, * and `PathLocationStrategy` produces * http://example.com/foo as an equivalent URL. * * See these two classes for more. * * @publicApi */ var LocationStrategy = /** @class */ (function () { function LocationStrategy() { } LocationStrategy.prototype.historyGo = function (relativePosition) { throw new Error('Not implemented'); }; return LocationStrategy; }()); LocationStrategy.ɵprov = i0.ɵɵdefineInjectable({ factory: provideLocationStrategy, token: LocationStrategy, providedIn: "root" }); LocationStrategy.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'root', useFactory: provideLocationStrategy },] } ]; function provideLocationStrategy(platformLocation) { // See #23917 var location = i0.ɵɵinject(DOCUMENT).location; return new PathLocationStrategy(i0.ɵɵinject(PlatformLocation), location && location.origin || ''); } /** * A predefined [DI token](guide/glossary#di-token) for the base href * to be used with the `PathLocationStrategy`. * The base href is the URL prefix that should be preserved when generating * and recognizing URLs. * * @usageNotes * * The following example shows how to use this token to configure the root app injector * with a base href value, so that the DI framework can supply the dependency anywhere in the app. * * ```typescript * import {Component, NgModule} from '@angular/core'; * import {APP_BASE_HREF} from '@angular/common'; * * @NgModule({ * providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}] * }) * class AppModule {} * ``` * * @publicApi */ var APP_BASE_HREF = new i0.InjectionToken('appBaseHref'); /** * @description * A {@link LocationStrategy} used to configure the {@link Location} service to * represent its state in the * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the * browser's URL. * * If you're using `PathLocationStrategy`, you must provide a {@link APP_BASE_HREF} * or add a `` element to the document. * * For instance, if you provide an `APP_BASE_HREF` of `'/my/app/'` and call * `location.go('/foo')`, the browser's URL will become * `example.com/my/app/foo`. To ensure all relative URIs resolve correctly, * the `` and/or `APP_BASE_HREF` should end with a `/`. * * Similarly, if you add `` to the document and call * `location.go('/foo')`, the browser's URL will become * `example.com/my/app/foo`. * * Note that when using `PathLocationStrategy`, neither the query nor * the fragment in the `` will be preserved, as outlined * by the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2). * * @usageNotes * * ### Example * * {@example common/location/ts/path_location_component.ts region='LocationComponent'} * * @publicApi */ var PathLocationStrategy = /** @class */ (function (_super) { __extends(PathLocationStrategy, _super); function PathLocationStrategy(_platformLocation, href) { var _this = _super.call(this) || this; _this._platformLocation = _platformLocation; _this._removeListenerFns = []; if (href == null) { href = _this._platformLocation.getBaseHrefFromDOM(); } if (href == null) { throw new Error("No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document."); } _this._baseHref = href; return _this; } PathLocationStrategy.prototype.ngOnDestroy = function () { while (this._removeListenerFns.length) { this._removeListenerFns.pop()(); } }; PathLocationStrategy.prototype.onPopState = function (fn) { this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn)); }; PathLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; }; PathLocationStrategy.prototype.prepareExternalUrl = function (internal) { return joinWithSlash(this._baseHref, internal); }; PathLocationStrategy.prototype.path = function (includeHash) { if (includeHash === void 0) { includeHash = false; } var pathname = this._platformLocation.pathname + normalizeQueryParams(this._platformLocation.search); var hash = this._platformLocation.hash; return hash && includeHash ? "" + pathname + hash : pathname; }; PathLocationStrategy.prototype.pushState = function (state, title, url, queryParams) { var externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams)); this._platformLocation.pushState(state, title, externalUrl); }; PathLocationStrategy.prototype.replaceState = function (state, title, url, queryParams) { var externalUrl = this.prepareExternalUrl(url + normalizeQueryParams(queryParams)); this._platformLocation.replaceState(state, title, externalUrl); }; PathLocationStrategy.prototype.forward = function () { this._platformLocation.forward(); }; PathLocationStrategy.prototype.back = function () { this._platformLocation.back(); }; PathLocationStrategy.prototype.historyGo = function (relativePosition) { if (relativePosition === void 0) { relativePosition = 0; } var _a, _b; (_b = (_a = this._platformLocation).historyGo) === null || _b === void 0 ? void 0 : _b.call(_a, relativePosition); }; return PathLocationStrategy; }(LocationStrategy)); PathLocationStrategy.decorators = [ { type: i0.Injectable } ]; PathLocationStrategy.ctorParameters = function () { return [ { type: PlatformLocation }, { type: String, decorators: [{ type: i0.Optional }, { type: i0.Inject, args: [APP_BASE_HREF,] }] } ]; }; /** * @description * A {@link LocationStrategy} used to configure the {@link Location} service to * represent its state in the * [hash fragment](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) * of the browser's URL. * * For instance, if you call `location.go('/foo')`, the browser's URL will become * `example.com#/foo`. * * @usageNotes * * ### Example * * {@example common/location/ts/hash_location_component.ts region='LocationComponent'} * * @publicApi */ var HashLocationStrategy = /** @class */ (function (_super) { __extends(HashLocationStrategy, _super); function HashLocationStrategy(_platformLocation, _baseHref) { var _this = _super.call(this) || this; _this._platformLocation = _platformLocation; _this._baseHref = ''; _this._removeListenerFns = []; if (_baseHref != null) { _this._baseHref = _baseHref; } return _this; } HashLocationStrategy.prototype.ngOnDestroy = function () { while (this._removeListenerFns.length) { this._removeListenerFns.pop()(); } }; HashLocationStrategy.prototype.onPopState = function (fn) { this._removeListenerFns.push(this._platformLocation.onPopState(fn), this._platformLocation.onHashChange(fn)); }; HashLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; }; HashLocationStrategy.prototype.path = function (includeHash) { if (includeHash === void 0) { includeHash = false; } // the hash value is always prefixed with a `#` // and if it is empty then it will stay empty var path = this._platformLocation.hash; if (path == null) path = '#'; return path.length > 0 ? path.substring(1) : path; }; HashLocationStrategy.prototype.prepareExternalUrl = function (internal) { var url = joinWithSlash(this._baseHref, internal); return url.length > 0 ? ('#' + url) : url; }; HashLocationStrategy.prototype.pushState = function (state, title, path, queryParams) { var url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams)); if (url.length == 0) { url = this._platformLocation.pathname; } this._platformLocation.pushState(state, title, url); }; HashLocationStrategy.prototype.replaceState = function (state, title, path, queryParams) { var url = this.prepareExternalUrl(path + normalizeQueryParams(queryParams)); if (url.length == 0) { url = this._platformLocation.pathname; } this._platformLocation.replaceState(state, title, url); }; HashLocationStrategy.prototype.forward = function () { this._platformLocation.forward(); }; HashLocationStrategy.prototype.back = function () { this._platformLocation.back(); }; HashLocationStrategy.prototype.historyGo = function (relativePosition) { if (relativePosition === void 0) { relativePosition = 0; } var _a, _b; (_b = (_a = this._platformLocation).historyGo) === null || _b === void 0 ? void 0 : _b.call(_a, relativePosition); }; return HashLocationStrategy; }(LocationStrategy)); HashLocationStrategy.decorators = [ { type: i0.Injectable } ]; HashLocationStrategy.ctorParameters = function () { return [ { type: PlatformLocation }, { type: String, decorators: [{ type: i0.Optional }, { type: i0.Inject, args: [APP_BASE_HREF,] }] } ]; }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @description * * A service that applications can use to interact with a browser's URL. * * Depending on the `LocationStrategy` used, `Location` persists * to the URL's path or the URL's hash segment. * * @usageNotes * * It's better to use the `Router.navigate()` service to trigger route changes. Use * `Location` only if you need to interact with or create normalized URLs outside of * routing. * * `Location` is responsible for normalizing the URL against the application's base href. * A normalized URL is absolute from the URL host, includes the application's base href, and has no * trailing slash: * - `/my/app/user/123` is normalized * - `my/app/user/123` **is not** normalized * - `/my/app/user/123/` **is not** normalized * * ### Example * * * * @publicApi */ var Location = /** @class */ (function () { function Location(platformStrategy, platformLocation) { var _this = this; /** @internal */ this._subject = new i0.EventEmitter(); /** @internal */ this._urlChangeListeners = []; this._platformStrategy = platformStrategy; var browserBaseHref = this._platformStrategy.getBaseHref(); this._platformLocation = platformLocation; this._baseHref = stripTrailingSlash(_stripIndexHtml(browserBaseHref)); this._platformStrategy.onPopState(function (ev) { _this._subject.emit({ 'url': _this.path(true), 'pop': true, 'state': ev.state, 'type': ev.type, }); }); } /** * Normalizes the URL path for this location. * * @param includeHash True to include an anchor fragment in the path. * * @returns The normalized URL path. */ // TODO: vsavkin. Remove the boolean flag and always include hash once the deprecated router is // removed. Location.prototype.path = function (includeHash) { if (includeHash === void 0) { includeHash = false; } return this.normalize(this._platformStrategy.path(includeHash)); }; /** * Reports the current state of the location history. * @returns The current value of the `history.state` object. */ Location.prototype.getState = function () { return this._platformLocation.getState(); }; /** * Normalizes the given path and compares to the current normalized path. * * @param path The given URL path. * @param query Query parameters. * * @returns True if the given URL path is equal to the current normalized path, false * otherwise. */ Location.prototype.isCurrentPathEqualTo = function (path, query) { if (query === void 0) { query = ''; } return this.path() == this.normalize(path + normalizeQueryParams(query)); }; /** * Normalizes a URL path by stripping any trailing slashes. * * @param url String representing a URL. * * @returns The normalized URL string. */ Location.prototype.normalize = function (url) { return Location.stripTrailingSlash(_stripBaseHref(this._baseHref, _stripIndexHtml(url))); }; /** * Normalizes an external URL path. * If the given URL doesn't begin with a leading slash (`'/'`), adds one * before normalizing. Adds a hash if `HashLocationStrategy` is * in use, or the `APP_BASE_HREF` if the `PathLocationStrategy` is in use. * * @param url String representing a URL. * * @returns A normalized platform-specific URL. */ Location.prototype.prepareExternalUrl = function (url) { if (url && url[0] !== '/') { url = '/' + url; } return this._platformStrategy.prepareExternalUrl(url); }; // TODO: rename this method to pushState /** * Changes the browser's URL to a normalized version of a given URL, and pushes a * new item onto the platform's history. * * @param path URL path to normalize. * @param query Query parameters. * @param state Location history state. * */ Location.prototype.go = function (path, query, state) { if (query === void 0) { query = ''; } if (state === void 0) { state = null; } this._platformStrategy.pushState(state, '', path, query); this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state); }; /** * Changes the browser's URL to a normalized version of the given URL, and replaces * the top item on the platform's history stack. * * @param path URL path to normalize. * @param query Query parameters. * @param state Location history state. */ Location.prototype.replaceState = function (path, query, state) { if (query === void 0) { query = ''; } if (state === void 0) { state = null; } this._platformStrategy.replaceState(state, '', path, query); this._notifyUrlChangeListeners(this.prepareExternalUrl(path + normalizeQueryParams(query)), state); }; /** * Navigates forward in the platform's history. */ Location.prototype.forward = function () { this._platformStrategy.forward(); }; /** * Navigates back in the platform's history. */ Location.prototype.back = function () { this._platformStrategy.back(); }; /** * Navigate to a specific page from session history, identified by its relative position to the * current page. * * @param relativePosition Position of the target page in the history relative to the current * page. * A negative value moves backwards, a positive value moves forwards, e.g. `location.historyGo(2)` * moves forward two pages and `location.historyGo(-2)` moves back two pages. When we try to go * beyond what's stored in the history session, we stay in the current page. Same behaviour occurs * when `relativePosition` equals 0. * @see https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history */ Location.prototype.historyGo = function (relativePosition) { if (relativePosition === void 0) { relativePosition = 0; } var _a, _b; (_b = (_a = this._platformStrategy).historyGo) === null || _b === void 0 ? void 0 : _b.call(_a, relativePosition); }; /** * Registers a URL change listener. Use to catch updates performed by the Angular * framework that are not detectible through "popstate" or "hashchange" events. * * @param fn The change handler function, which take a URL and a location history state. */ Location.prototype.onUrlChange = function (fn) { var _this = this; this._urlChangeListeners.push(fn); if (!this._urlChangeSubscription) { this._urlChangeSubscription = this.subscribe(function (v) { _this._notifyUrlChangeListeners(v.url, v.state); }); } }; /** @internal */ Location.prototype._notifyUrlChangeListeners = function (url, state) { if (url === void 0) { url = ''; } this._urlChangeListeners.forEach(function (fn) { return fn(url, state); }); }; /** * Subscribes to the platform's `popState` events. * * Note: `Location.go()` does not trigger the `popState` event in the browser. Use * `Location.onUrlChange()` to subscribe to URL changes instead. * * @param value Event that is triggered when the state history changes. * @param exception The exception to throw. * * @see [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate) * * @returns Subscribed events. */ Location.prototype.subscribe = function (onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); }; return Location; }()); /** * Normalizes URL parameters by prepending with `?` if needed. * * @param params String of URL parameters. * * @returns The normalized URL parameters string. */ Location.normalizeQueryParams = normalizeQueryParams; /** * Joins two parts of a URL with a slash if needed. * * @param start URL string * @param end URL string * * * @returns The joined URL string. */ Location.joinWithSlash = joinWithSlash; /** * Removes a trailing slash from a URL string if needed. * Looks for the first occurrence of either `#`, `?`, or the end of the * line as `/` characters and removes the trailing slash if one exists. * * @param url URL string. * * @returns The URL string, modified if needed. */ Location.stripTrailingSlash = stripTrailingSlash; Location.ɵprov = i0.ɵɵdefineInjectable({ factory: createLocation, token: Location, providedIn: "root" }); Location.decorators = [ { type: i0.Injectable, args: [{ providedIn: 'root', // See #23917 useFactory: createLocation, },] } ]; Location.ctorParameters = function () { return [ { type: LocationStrategy }, { type: PlatformLocation } ]; }; function createLocation() { return new Location(i0.ɵɵinject(LocationStrategy), i0.ɵɵinject(PlatformLocation)); } function _stripBaseHref(baseHref, url) { return baseHref && url.startsWith(baseHref) ? url.substring(baseHref.length) : url; } function _stripIndexHtml(url) { return url.replace(/\/index.html$/, ''); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** @internal */ var CURRENCIES_EN = { "ADP": [undefined, undefined, 0], "AFN": [undefined, undefined, 0], "ALL": [undefined, undefined, 0], "AMD": [undefined, undefined, 2], "AOA": [undefined, "Kz"], "ARS": [undefined, "$"], "AUD": ["A$", "$"], "BAM": [undefined, "KM"], "BBD": [undefined, "$"], "BDT": [undefined, "৳"], "BHD": [undefined, undefined, 3], "BIF": [undefined, undefined, 0], "BMD": [undefined, "$"], "BND": [undefined, "$"], "BOB": [undefined, "Bs"], "BRL": ["R$"], "BSD": [undefined, "$"], "BWP": [undefined, "P"], "BYN": [undefined, "р.", 2], "BYR": [undefined, undefined, 0], "BZD": [undefined, "$"], "CAD": ["CA$", "$", 2], "CHF": [undefined, undefined, 2], "CLF": [undefined, undefined, 4], "CLP": [undefined, "$", 0], "CNY": ["CN¥", "¥"], "COP": [undefined, "$", 2], "CRC": [undefined, "₡", 2], "CUC": [undefined, "$"], "CUP": [undefined, "$"], "CZK": [undefined, "Kč", 2], "DJF": [undefined, undefined, 0], "DKK": [undefined, "kr", 2], "DOP": [undefined, "$"], "EGP": [undefined, "E£"], "ESP": [undefined, "₧", 0], "EUR": ["€"], "FJD": [undefined, "$"], "FKP": [undefined, "£"], "GBP": ["£"], "GEL": [undefined, "₾"], "GIP": [undefined, "£"], "GNF": [undefined, "FG", 0], "GTQ": [undefined, "Q"], "GYD": [undefined, "$", 2], "HKD": ["HK$", "$"], "HNL": [undefined, "L"], "HRK": [undefined, "kn"], "HUF": [undefined, "Ft", 2], "IDR": [undefined, "Rp", 2], "ILS": ["₪"], "INR": ["₹"], "IQD": [undefined, undefined, 0], "IRR": [undefined, undefined, 0], "ISK": [undefined, "kr", 0], "ITL": [undefined, undefined, 0], "JMD": [undefined, "$"], "JOD": [undefined, undefined, 3], "JPY": ["¥", undefined, 0], "KHR": [undefined, "៛"], "KMF": [undefined, "CF", 0], "KPW": [undefined, "₩", 0], "KRW": ["₩", undefined, 0], "KWD": [undefined, undefined, 3], "KYD": [undefined, "$"], "KZT": [undefined, "₸"], "LAK": [undefined, "₭", 0], "LBP": [undefined, "L£", 0], "LKR": [undefined, "Rs"], "LRD": [undefined, "$"], "LTL": [undefined, "Lt"], "LUF": [undefined, undefined, 0], "LVL": [undefined, "Ls"], "LYD": [undefined, undefined, 3], "MGA": [undefined, "Ar", 0], "MGF": [undefined, undefined, 0], "MMK": [undefined, "K", 0], "MNT": [undefined, "₮", 2], "MRO": [undefined, undefined, 0], "MUR": [undefined, "Rs", 2], "MXN": ["MX$", "$"], "MYR": [undefined, "RM"], "NAD": [undefined, "$"], "NGN": [undefined, "₦"], "NIO": [undefined, "C$"], "NOK": [undefined, "kr", 2], "NPR": [undefined, "Rs"], "NZD": ["NZ$", "$"], "OMR": [undefined, undefined, 3], "PHP": [undefined, "₱"], "PKR": [undefined, "Rs", 2], "PLN": [undefined, "zł"], "PYG": [undefined, "₲", 0], "RON": [undefined, "lei"], "RSD": [undefined, undefined, 0], "RUB": [undefined, "₽"], "RUR": [undefined, "р."], "RWF": [undefined, "RF", 0], "SBD": [undefined, "$"], "SEK": [undefined, "kr", 2], "SGD": [undefined, "$"], "SHP": [undefined, "£"], "SLL": [undefined, undefined, 0], "SOS": [undefined, undefined, 0], "SRD": [undefined, "$"], "SSP": [undefined, "£"], "STD": [undefined, undefined, 0], "STN": [undefined, "Db"], "SYP": [undefined, "£", 0], "THB": [undefined, "฿"], "TMM": [undefined, undefined, 0], "TND": [undefined, undefined, 3], "TOP": [undefined, "T$"], "TRL": [undefined, undefined, 0], "TRY": [undefined, "₺"], "TTD": [undefined, "$"], "TWD": ["NT$", "$", 2], "TZS": [undefined, undefined, 2], "UAH": [undefined, "₴"], "UGX": [undefined, undefined, 0], "USD": ["$"], "UYI": [undefined, undefined, 0], "UYU": [undefined, "$"], "UYW": [undefined, undefined, 4], "UZS": [undefined, undefined, 2], "VEF": [undefined, "Bs", 2], "VND": ["₫", undefined, 0], "VUV": [undefined, undefined, 0], "XAF": ["FCFA", undefined, 0], "XCD": ["EC$", "$"], "XOF": ["CFA", undefined, 0], "XPF": ["CFPF", undefined, 0], "XXX": ["¤"], "YER": [undefined, undefined, 0], "ZAR": [undefined, "R"], "ZMK": [undefined, undefined, 0], "ZMW": [undefined, "ZK"], "ZWD": [undefined, undefined, 0] }; (function (NumberFormatStyle) { NumberFormatStyle[NumberFormatStyle["Decimal"] = 0] = "Decimal"; NumberFormatStyle[NumberFormatStyle["Percent"] = 1] = "Percent"; NumberFormatStyle[NumberFormatStyle["Currency"] = 2] = "Currency"; NumberFormatStyle[NumberFormatStyle["Scientific"] = 3] = "Scientific"; })(exports.NumberFormatStyle || (exports.NumberFormatStyle = {})); (function (Plural) { Plural[Plural["Zero"] = 0] = "Zero"; Plural[Plural["One"] = 1] = "One"; Plural[Plural["Two"] = 2] = "Two"; Plural[Plural["Few"] = 3] = "Few"; Plural[Plural["Many"] = 4] = "Many"; Plural[Plural["Other"] = 5] = "Other"; })(exports.Plural || (exports.Plural = {})); (function (FormStyle) { FormStyle[FormStyle["Format"] = 0] = "Format"; FormStyle[FormStyle["Standalone"] = 1] = "Standalone"; })(exports.FormStyle || (exports.FormStyle = {})); (function (TranslationWidth) { /** 1 character for `en-US`. For example: 'S' */ TranslationWidth[TranslationWidth["Narrow"] = 0] = "Narrow"; /** 3 characters for `en-US`. For example: 'Sun' */ TranslationWidth[TranslationWidth["Abbreviated"] = 1] = "Abbreviated"; /** Full length for `en-US`. For example: "Sunday" */ TranslationWidth[TranslationWidth["Wide"] = 2] = "Wide"; /** 2 characters for `en-US`, For example: "Su" */ TranslationWidth[TranslationWidth["Short"] = 3] = "Short"; })(exports.TranslationWidth || (exports.TranslationWidth = {})); (function (FormatWidth) { /** * For `en-US`, 'M/d/yy, h:mm a'` * (Example: `6/15/15, 9:03 AM`) */ FormatWidth[FormatWidth["Short"] = 0] = "Short"; /** * For `en-US`, `'MMM d, y, h:mm:ss a'` * (Example: `Jun 15, 2015, 9:03:01 AM`) */ FormatWidth[FormatWidth["Medium"] = 1] = "Medium"; /** * For `en-US`, `'MMMM d, y, h:mm:ss a z'` * (Example: `June 15, 2015 at 9:03:01 AM GMT+1`) */ FormatWidth[FormatWidth["Long"] = 2] = "Long"; /** * For `en-US`, `'EEEE, MMMM d, y, h:mm:ss a zzzz'` * (Example: `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00`) */ FormatWidth[FormatWidth["Full"] = 3] = "Full"; })(exports.FormatWidth || (exports.FormatWidth = {})); (function (NumberSymbol) { /** * Decimal separator. * For `en-US`, the dot character. * Example: 2,345`.`67 */ NumberSymbol[NumberSymbol["Decimal"] = 0] = "Decimal"; /** * Grouping separator, typically for thousands. * For `en-US`, the comma character. * Example: 2`,`345.67 */ NumberSymbol[NumberSymbol["Group"] = 1] = "Group"; /** * List-item separator. * Example: "one, two, and three" */ NumberSymbol[NumberSymbol["List"] = 2] = "List"; /** * Sign for percentage (out of 100). * Example: 23.4% */ NumberSymbol[NumberSymbol["PercentSign"] = 3] = "PercentSign"; /** * Sign for positive numbers. * Example: +23 */ NumberSymbol[NumberSymbol["PlusSign"] = 4] = "PlusSign"; /** * Sign for negative numbers. * Example: -23 */ NumberSymbol[NumberSymbol["MinusSign"] = 5] = "MinusSign"; /** * Computer notation for exponential value (n times a power of 10). * Example: 1.2E3 */ NumberSymbol[NumberSymbol["Exponential"] = 6] = "Exponential"; /** * Human-readable format of exponential. * Example: 1.2x103 */ NumberSymbol[NumberSymbol["SuperscriptingExponent"] = 7] = "SuperscriptingExponent"; /** * Sign for permille (out of 1000). * Example: 23.4‰ */ NumberSymbol[NumberSymbol["PerMille"] = 8] = "PerMille"; /** * Infinity, can be used with plus and minus. * Example: ∞, +∞, -∞ */ NumberSymbol[NumberSymbol["Infinity"] = 9] = "Infinity"; /** * Not a number. * Example: NaN */ NumberSymbol[NumberSymbol["NaN"] = 10] = "NaN"; /** * Symbol used between time units. * Example: 10:52 */ NumberSymbol[NumberSymbol["TimeSeparator"] = 11] = "TimeSeparator"; /** * Decimal separator for currency values (fallback to `Decimal`). * Example: $2,345.67 */ NumberSymbol[NumberSymbol["CurrencyDecimal"] = 12] = "CurrencyDecimal"; /** * Group separator for currency values (fallback to `Group`). * Example: $2,345.67 */ NumberSymbol[NumberSymbol["CurrencyGroup"] = 13] = "CurrencyGroup"; })(exports.NumberSymbol || (exports.NumberSymbol = {})); (function (WeekDay) { WeekDay[WeekDay["Sunday"] = 0] = "Sunday"; WeekDay[WeekDay["Monday"] = 1] = "Monday"; WeekDay[WeekDay["Tuesday"] = 2] = "Tuesday"; WeekDay[WeekDay["Wednesday"] = 3] = "Wednesday"; WeekDay[WeekDay["Thursday"] = 4] = "Thursday"; WeekDay[WeekDay["Friday"] = 5] = "Friday"; WeekDay[WeekDay["Saturday"] = 6] = "Saturday"; })(exports.WeekDay || (exports.WeekDay = {})); /** * Retrieves the locale ID from the currently loaded locale. * The loaded locale could be, for example, a global one rather than a regional one. * @param locale A locale code, such as `fr-FR`. * @returns The locale code. For example, `fr`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleId(locale) { return i0.ɵfindLocaleData(locale)[i0.ɵLocaleDataIndex.LocaleId]; } /** * Retrieves day period strings for the given locale. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized period strings. For example, `[AM, PM]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDayPeriods(locale, formStyle, width) { var data = i0.ɵfindLocaleData(locale); var amPmData = [ data[i0.ɵLocaleDataIndex.DayPeriodsFormat], data[i0.ɵLocaleDataIndex.DayPeriodsStandalone] ]; var amPm = getLastDefinedValue(amPmData, formStyle); return getLastDefinedValue(amPm, width); } /** * Retrieves days of the week for the given locale, using the Gregorian calendar. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized name strings. * For example,`[Sunday, Monday, ... Saturday]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDayNames(locale, formStyle, width) { var data = i0.ɵfindLocaleData(locale); var daysData = [data[i0.ɵLocaleDataIndex.DaysFormat], data[i0.ɵLocaleDataIndex.DaysStandalone]]; var days = getLastDefinedValue(daysData, formStyle); return getLastDefinedValue(days, width); } /** * Retrieves months of the year for the given locale, using the Gregorian calendar. * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns An array of localized name strings. * For example, `[January, February, ...]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleMonthNames(locale, formStyle, width) { var data = i0.ɵfindLocaleData(locale); var monthsData = [data[i0.ɵLocaleDataIndex.MonthsFormat], data[i0.ɵLocaleDataIndex.MonthsStandalone]]; var months = getLastDefinedValue(monthsData, formStyle); return getLastDefinedValue(months, width); } /** * Retrieves Gregorian-calendar eras for the given locale. * @param locale A locale code for the locale format rules to use. * @param width The required character width. * @returns An array of localized era strings. * For example, `[AD, BC]` for `en-US`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleEraNames(locale, width) { var data = i0.ɵfindLocaleData(locale); var erasData = data[i0.ɵLocaleDataIndex.Eras]; return getLastDefinedValue(erasData, width); } /** * Retrieves the first day of the week for the given locale. * * @param locale A locale code for the locale format rules to use. * @returns A day index number, using the 0-based week-day index for `en-US` * (Sunday = 0, Monday = 1, ...). * For example, for `fr-FR`, returns 1 to indicate that the first day is Monday. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleFirstDayOfWeek(locale) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.FirstDayOfWeek]; } /** * Range of week days that are considered the week-end for the given locale. * * @param locale A locale code for the locale format rules to use. * @returns The range of day values, `[startDay, endDay]`. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleWeekEndRange(locale) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.WeekendRange]; } /** * Retrieves a localized date-value formating string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formating string. * @see `FormatWidth` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDateFormat(locale, width) { var data = i0.ɵfindLocaleData(locale); return getLastDefinedValue(data[i0.ɵLocaleDataIndex.DateFormat], width); } /** * Retrieves a localized time-value formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see `FormatWidth` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * @publicApi */ function getLocaleTimeFormat(locale, width) { var data = i0.ɵfindLocaleData(locale); return getLastDefinedValue(data[i0.ɵLocaleDataIndex.TimeFormat], width); } /** * Retrieves a localized date-time formatting string. * * @param locale A locale code for the locale format rules to use. * @param width The format type. * @returns The localized formatting string. * @see `FormatWidth` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleDateTimeFormat(locale, width) { var data = i0.ɵfindLocaleData(locale); var dateTimeFormatData = data[i0.ɵLocaleDataIndex.DateTimeFormat]; return getLastDefinedValue(dateTimeFormatData, width); } /** * Retrieves a localized number symbol that can be used to replace placeholders in number formats. * @param locale The locale code. * @param symbol The symbol to localize. * @returns The character for the localized symbol. * @see `NumberSymbol` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleNumberSymbol(locale, symbol) { var data = i0.ɵfindLocaleData(locale); var res = data[i0.ɵLocaleDataIndex.NumberSymbols][symbol]; if (typeof res === 'undefined') { if (symbol === exports.NumberSymbol.CurrencyDecimal) { return data[i0.ɵLocaleDataIndex.NumberSymbols][exports.NumberSymbol.Decimal]; } else if (symbol === exports.NumberSymbol.CurrencyGroup) { return data[i0.ɵLocaleDataIndex.NumberSymbols][exports.NumberSymbol.Group]; } } return res; } /** * Retrieves a number format for a given locale. * * Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00` * when used to format the number 12345.678 could result in "12'345,678". That would happen if the * grouping separator for your language is an apostrophe, and the decimal separator is a comma. * * Important: The characters `.` `,` `0` `#` (and others below) are special placeholders * that stand for the decimal separator, and so on, and are NOT real characters. * You must NOT "translate" the placeholders. For example, don't change `.` to `,` even though in * your language the decimal point is written with a comma. The symbols should be replaced by the * local equivalents, using the appropriate `NumberSymbol` for your language. * * Here are the special characters used in number patterns: * * | Symbol | Meaning | * |--------|---------| * | . | Replaced automatically by the character used for the decimal point. | * | , | Replaced by the "grouping" (thousands) separator. | * | 0 | Replaced by a digit (or zero if there aren't enough digits). | * | # | Replaced by a digit (or nothing if there aren't enough). | * | ¤ | Replaced by a currency symbol, such as $ or USD. | * | % | Marks a percent format. The % symbol may change position, but must be retained. | * | E | Marks a scientific format. The E symbol may change position, but must be retained. | * | ' | Special characters used as literal characters are quoted with ASCII single quotes. | * * @param locale A locale code for the locale format rules to use. * @param type The type of numeric value to be formatted (such as `Decimal` or `Currency`.) * @returns The localized format string. * @see `NumberFormatStyle` * @see [CLDR website](http://cldr.unicode.org/translation/number-patterns) * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleNumberFormat(locale, type) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.NumberFormats][type]; } /** * Retrieves the symbol used to represent the currency for the main country * corresponding to a given locale. For example, '$' for `en-US`. * * @param locale A locale code for the locale format rules to use. * @returns The localized symbol character, * or `null` if the main country cannot be determined. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleCurrencySymbol(locale) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.CurrencySymbol] || null; } /** * Retrieves the name of the currency for the main country corresponding * to a given locale. For example, 'US Dollar' for `en-US`. * @param locale A locale code for the locale format rules to use. * @returns The currency name, * or `null` if the main country cannot be determined. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleCurrencyName(locale) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.CurrencyName] || null; } /** * Retrieves the default currency code for the given locale. * * The default is defined as the first currency which is still in use. * * @param locale The code of the locale whose currency code we want. * @returns The code of the default currency for the given locale. * * @publicApi */ function getLocaleCurrencyCode(locale) { return i0.ɵgetLocaleCurrencyCode(locale); } /** * Retrieves the currency values for a given locale. * @param locale A locale code for the locale format rules to use. * @returns The currency values. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) */ function getLocaleCurrencies(locale) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.Currencies]; } /** * @alias core/ɵgetLocalePluralCase * @publicApi */ var getLocalePluralCase = i0.ɵgetLocalePluralCase; function checkFullData(data) { if (!data[i0.ɵLocaleDataIndex.ExtraData]) { throw new Error("Missing extra locale data for the locale \"" + data[i0.ɵLocaleDataIndex .LocaleId] + "\". Use \"registerLocaleData\" to load new data. See the \"I18n guide\" on angular.io to know more."); } } /** * Retrieves locale-specific rules used to determine which day period to use * when more than one period is defined for a locale. * * There is a rule for each defined day period. The * first rule is applied to the first day period and so on. * Fall back to AM/PM when no rules are available. * * A rule can specify a period as time range, or as a single time value. * * This functionality is only available when you have loaded the full locale data. * See the ["I18n guide"](guide/i18n#i18n-pipes). * * @param locale A locale code for the locale format rules to use. * @returns The rules for the locale, a single time value or array of *from-time, to-time*, * or null if no periods are available. * * @see `getLocaleExtraDayPeriods()` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleExtraDayPeriodRules(locale) { var data = i0.ɵfindLocaleData(locale); checkFullData(data); var rules = data[i0.ɵLocaleDataIndex.ExtraData][2 /* ExtraDayPeriodsRules */] || []; return rules.map(function (rule) { if (typeof rule === 'string') { return extractTime(rule); } return [extractTime(rule[0]), extractTime(rule[1])]; }); } /** * Retrieves locale-specific day periods, which indicate roughly how a day is broken up * in different languages. * For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight. * * This functionality is only available when you have loaded the full locale data. * See the ["I18n guide"](guide/i18n#i18n-pipes). * * @param locale A locale code for the locale format rules to use. * @param formStyle The required grammatical form. * @param width The required character width. * @returns The translated day-period strings. * @see `getLocaleExtraDayPeriodRules()` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLocaleExtraDayPeriods(locale, formStyle, width) { var data = i0.ɵfindLocaleData(locale); checkFullData(data); var dayPeriodsData = [ data[i0.ɵLocaleDataIndex.ExtraData][0 /* ExtraDayPeriodFormats */], data[i0.ɵLocaleDataIndex.ExtraData][1 /* ExtraDayPeriodStandalone */] ]; var dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || []; return getLastDefinedValue(dayPeriods, width) || []; } /** * Retrieves the writing direction of a specified locale * @param locale A locale code for the locale format rules to use. * @publicApi * @returns 'rtl' or 'ltr' * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) */ function getLocaleDirection(locale) { var data = i0.ɵfindLocaleData(locale); return data[i0.ɵLocaleDataIndex.Directionality]; } /** * Retrieves the first value that is defined in an array, going backwards from an index position. * * To avoid repeating the same data (as when the "format" and "standalone" forms are the same) * add the first value to the locale data arrays, and add other values only if they are different. * * @param data The data array to retrieve from. * @param index A 0-based index into the array to start from. * @returns The value immediately before the given index position. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getLastDefinedValue(data, index) { for (var i = index; i > -1; i--) { if (typeof data[i] !== 'undefined') { return data[i]; } } throw new Error('Locale data API: locale data undefined'); } /** * Extracts the hours and minutes from a string like "15:45" */ function extractTime(time) { var _a = __read(time.split(':'), 2), h = _a[0], m = _a[1]; return { hours: +h, minutes: +m }; } /** * Retrieves the currency symbol for a given currency code. * * For example, for the default `en-US` locale, the code `USD` can * be represented by the narrow symbol `$` or the wide symbol `US$`. * * @param code The currency code. * @param format The format, `wide` or `narrow`. * @param locale A locale code for the locale format rules to use. * * @returns The symbol, or the currency code if no symbol is available. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getCurrencySymbol(code, format, locale) { if (locale === void 0) { locale = 'en'; } var currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || []; var symbolNarrow = currency[1 /* SymbolNarrow */]; if (format === 'narrow' && typeof symbolNarrow === 'string') { return symbolNarrow; } return currency[0 /* Symbol */] || code; } // Most currencies have cents, that's why the default is 2 var DEFAULT_NB_OF_CURRENCY_DIGITS = 2; /** * Reports the number of decimal digits for a given currency. * The value depends upon the presence of cents in that particular currency. * * @param code The currency code. * @returns The number of decimal digits, typically 0 or 2. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function getNumberOfCurrencyDigits(code) { var digits; var currency = CURRENCIES_EN[code]; if (currency) { digits = currency[2 /* NbOfDigits */]; } return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS; } var ISO8601_DATE_REGEX = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 var NAMED_FORMATS = {}; var DATE_FORMATS_SPLIT = /((?:[^BEGHLMOSWYZabcdhmswyz']+)|(?:'(?:[^']|'')*')|(?:G{1,5}|y{1,4}|Y{1,4}|M{1,5}|L{1,5}|w{1,2}|W{1}|d{1,2}|E{1,6}|c{1,6}|a{1,5}|b{1,5}|B{1,5}|h{1,2}|H{1,2}|m{1,2}|s{1,2}|S{1,3}|z{1,4}|Z{1,5}|O{1,4}))([\s\S]*)/; var ZoneWidth; (function (ZoneWidth) { ZoneWidth[ZoneWidth["Short"] = 0] = "Short"; ZoneWidth[ZoneWidth["ShortGMT"] = 1] = "ShortGMT"; ZoneWidth[ZoneWidth["Long"] = 2] = "Long"; ZoneWidth[ZoneWidth["Extended"] = 3] = "Extended"; })(ZoneWidth || (ZoneWidth = {})); var DateType; (function (DateType) { DateType[DateType["FullYear"] = 0] = "FullYear"; DateType[DateType["Month"] = 1] = "Month"; DateType[DateType["Date"] = 2] = "Date"; DateType[DateType["Hours"] = 3] = "Hours"; DateType[DateType["Minutes"] = 4] = "Minutes"; DateType[DateType["Seconds"] = 5] = "Seconds"; DateType[DateType["FractionalSeconds"] = 6] = "FractionalSeconds"; DateType[DateType["Day"] = 7] = "Day"; })(DateType || (DateType = {})); var TranslationType; (function (TranslationType) { TranslationType[TranslationType["DayPeriods"] = 0] = "DayPeriods"; TranslationType[TranslationType["Days"] = 1] = "Days"; TranslationType[TranslationType["Months"] = 2] = "Months"; TranslationType[TranslationType["Eras"] = 3] = "Eras"; })(TranslationType || (TranslationType = {})); /** * @ngModule CommonModule * @description * * Formats a date according to locale rules. * * @param value The date to format, as a Date, or a number (milliseconds since UTC epoch) * or an [ISO date-time string](https://www.w3.org/TR/NOTE-datetime). * @param format The date-time components to include. See `DatePipe` for details. * @param locale A locale code for the locale format rules to use. * @param timezone The time zone. A time zone offset from GMT (such as `'+0430'`), * or a standard UTC/GMT or continental US time zone abbreviation. * If not specified, uses host system settings. * * @returns The formatted date string. * * @see `DatePipe` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function formatDate(value, format, locale, timezone) { var date = toDate(value); var namedFormat = getNamedFormat(locale, format); format = namedFormat || format; var parts = []; var match; while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = parts.concat(match.slice(1)); var part = parts.pop(); if (!part) { break; } format = part; } else { parts.push(format); break; } } var dateTimezoneOffset = date.getTimezoneOffset(); if (timezone) { dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); date = convertTimezoneToLocal(date, timezone, true); } var text = ''; parts.forEach(function (value) { var dateFormatter = getDateFormatter(value); text += dateFormatter ? dateFormatter(date, locale, dateTimezoneOffset) : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); }); return text; } /** * Create a new Date object with the given date value, and the time set to midnight. * * We cannot use `new Date(year, month, date)` because it maps years between 0 and 99 to 1900-1999. * See: https://github.com/angular/angular/issues/40377 * * Note that this function returns a Date object whose time is midnight in the current locale's * timezone. In the future we might want to change this to be midnight in UTC, but this would be a * considerable breaking change. */ function createDate(year, month, date) { // The `newDate` is set to midnight (UTC) on January 1st 1970. // - In PST this will be December 31st 1969 at 4pm. // - In GMT this will be January 1st 1970 at 1am. // Note that they even have different years, dates and months! var newDate = new Date(0); // `setFullYear()` allows years like 0001 to be set correctly. This function does not // change the internal time of the date. // Consider calling `setFullYear(2019, 8, 20)` (September 20, 2019). // - In PST this will now be September 20, 2019 at 4pm // - In GMT this will now be September 20, 2019 at 1am newDate.setFullYear(year, month, date); // We want the final date to be at local midnight, so we reset the time. // - In PST this will now be September 20, 2019 at 12am // - In GMT this will now be September 20, 2019 at 12am newDate.setHours(0, 0, 0); return newDate; } function getNamedFormat(locale, format) { var localeId = getLocaleId(locale); NAMED_FORMATS[localeId] = NAMED_FORMATS[localeId] || {}; if (NAMED_FORMATS[localeId][format]) { return NAMED_FORMATS[localeId][format]; } var formatValue = ''; switch (format) { case 'shortDate': formatValue = getLocaleDateFormat(locale, exports.FormatWidth.Short); break; case 'mediumDate': formatValue = getLocaleDateFormat(locale, exports.FormatWidth.Medium); break; case 'longDate': formatValue = getLocaleDateFormat(locale, exports.FormatWidth.Long); break; case 'fullDate': formatValue = getLocaleDateFormat(locale, exports.FormatWidth.Full); break; case 'shortTime': formatValue = getLocaleTimeFormat(locale, exports.FormatWidth.Short); break; case 'mediumTime': formatValue = getLocaleTimeFormat(locale, exports.FormatWidth.Medium); break; case 'longTime': formatValue = getLocaleTimeFormat(locale, exports.FormatWidth.Long); break; case 'fullTime': formatValue = getLocaleTimeFormat(locale, exports.FormatWidth.Full); break; case 'short': var shortTime = getNamedFormat(locale, 'shortTime'); var shortDate = getNamedFormat(locale, 'shortDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, exports.FormatWidth.Short), [shortTime, shortDate]); break; case 'medium': var mediumTime = getNamedFormat(locale, 'mediumTime'); var mediumDate = getNamedFormat(locale, 'mediumDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, exports.FormatWidth.Medium), [mediumTime, mediumDate]); break; case 'long': var longTime = getNamedFormat(locale, 'longTime'); var longDate = getNamedFormat(locale, 'longDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, exports.FormatWidth.Long), [longTime, longDate]); break; case 'full': var fullTime = getNamedFormat(locale, 'fullTime'); var fullDate = getNamedFormat(locale, 'fullDate'); formatValue = formatDateTime(getLocaleDateTimeFormat(locale, exports.FormatWidth.Full), [fullTime, fullDate]); break; } if (formatValue) { NAMED_FORMATS[localeId][format] = formatValue; } return formatValue; } function formatDateTime(str, opt_values) { if (opt_values) { str = str.replace(/\{([^}]+)}/g, function (match, key) { return (opt_values != null && key in opt_values) ? opt_values[key] : match; }); } return str; } function padNumber(num, digits, minusSign, trim, negWrap) { if (minusSign === void 0) { minusSign = '-'; } var neg = ''; if (num < 0 || (negWrap && num <= 0)) { if (negWrap) { num = -num + 1; } else { num = -num; neg = minusSign; } } var strNum = String(num); while (strNum.length < digits) { strNum = '0' + strNum; } if (trim) { strNum = strNum.substr(strNum.length - digits); } return neg + strNum; } function formatFractionalSeconds(milliseconds, digits) { var strMs = padNumber(milliseconds, 3); return strMs.substr(0, digits); } /** * Returns a date formatter that transforms a date into its locale digit representation */ function dateGetter(name, size, offset, trim, negWrap) { if (offset === void 0) { offset = 0; } if (trim === void 0) { trim = false; } if (negWrap === void 0) { negWrap = false; } return function (date, locale) { var part = getDatePart(name, date); if (offset > 0 || part > -offset) { part += offset; } if (name === DateType.Hours) { if (part === 0 && offset === -12) { part = 12; } } else if (name === DateType.FractionalSeconds) { return formatFractionalSeconds(part, size); } var localeMinus = getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign); return padNumber(part, size, localeMinus, trim, negWrap); }; } function getDatePart(part, date) { switch (part) { case DateType.FullYear: return date.getFullYear(); case DateType.Month: return date.getMonth(); case DateType.Date: return date.getDate(); case DateType.Hours: return date.getHours(); case DateType.Minutes: return date.getMinutes(); case DateType.Seconds: return date.getSeconds(); case DateType.FractionalSeconds: return date.getMilliseconds(); case DateType.Day: return date.getDay(); default: throw new Error("Unknown DateType value \"" + part + "\"."); } } /** * Returns a date formatter that transforms a date into its locale string representation */ function dateStrGetter(name, width, form, extended) { if (form === void 0) { form = exports.FormStyle.Format; } if (extended === void 0) { extended = false; } return function (date, locale) { return getDateTranslation(date, locale, name, width, form, extended); }; } /** * Returns the locale translation of a date for a given form, type and width */ function getDateTranslation(date, locale, name, width, form, extended) { switch (name) { case TranslationType.Months: return getLocaleMonthNames(locale, form, width)[date.getMonth()]; case TranslationType.Days: return getLocaleDayNames(locale, form, width)[date.getDay()]; case TranslationType.DayPeriods: var currentHours_1 = date.getHours(); var currentMinutes_1 = date.getMinutes(); if (extended) { var rules = getLocaleExtraDayPeriodRules(locale); var dayPeriods = getLocaleExtraDayPeriods(locale, form, width); var index = rules.findIndex(function (rule) { if (Array.isArray(rule)) { // morning, afternoon, evening, night var _a = __read(rule, 2), from = _a[0], to = _a[1]; var afterFrom = currentHours_1 >= from.hours && currentMinutes_1 >= from.minutes; var beforeTo = (currentHours_1 < to.hours || (currentHours_1 === to.hours && currentMinutes_1 < to.minutes)); // We must account for normal rules that span a period during the day (e.g. 6am-9am) // where `from` is less (earlier) than `to`. But also rules that span midnight (e.g. // 10pm - 5am) where `from` is greater (later!) than `to`. // // In the first case the current time must be BOTH after `from` AND before `to` // (e.g. 8am is after 6am AND before 10am). // // In the second case the current time must be EITHER after `from` OR before `to` // (e.g. 4am is before 5am but not after 10pm; and 11pm is not before 5am but it is // after 10pm). if (from.hours < to.hours) { if (afterFrom && beforeTo) { return true; } } else if (afterFrom || beforeTo) { return true; } } else { // noon or midnight if (rule.hours === currentHours_1 && rule.minutes === currentMinutes_1) { return true; } } return false; }); if (index !== -1) { return dayPeriods[index]; } } // if no rules for the day periods, we use am/pm by default return getLocaleDayPeriods(locale, form, width)[currentHours_1 < 12 ? 0 : 1]; case TranslationType.Eras: return getLocaleEraNames(locale, width)[date.getFullYear() <= 0 ? 0 : 1]; default: // This default case is not needed by TypeScript compiler, as the switch is exhaustive. // However Closure Compiler does not understand that and reports an error in typed mode. // The `throw new Error` below works around the problem, and the unexpected: never variable // makes sure tsc still checks this code is unreachable. var unexpected = name; throw new Error("unexpected translation type " + unexpected); } } /** * Returns a date formatter that transforms a date and an offset into a timezone with ISO8601 or * GMT format depending on the width (eg: short = +0430, short:GMT = GMT+4, long = GMT+04:30, * extended = +04:30) */ function timeZoneGetter(width) { return function (date, locale, offset) { var zone = -1 * offset; var minusSign = getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign); var hours = zone > 0 ? Math.floor(zone / 60) : Math.ceil(zone / 60); switch (width) { case ZoneWidth.Short: return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + padNumber(Math.abs(zone % 60), 2, minusSign); case ZoneWidth.ShortGMT: return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 1, minusSign); case ZoneWidth.Long: return 'GMT' + ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign); case ZoneWidth.Extended: if (offset === 0) { return 'Z'; } else { return ((zone >= 0) ? '+' : '') + padNumber(hours, 2, minusSign) + ':' + padNumber(Math.abs(zone % 60), 2, minusSign); } default: throw new Error("Unknown zone width \"" + width + "\""); } }; } var JANUARY = 0; var THURSDAY = 4; function getFirstThursdayOfYear(year) { var firstDayOfYear = createDate(year, JANUARY, 1).getDay(); return createDate(year, 0, 1 + ((firstDayOfYear <= THURSDAY) ? THURSDAY : THURSDAY + 7) - firstDayOfYear); } function getThursdayThisWeek(datetime) { return createDate(datetime.getFullYear(), datetime.getMonth(), datetime.getDate() + (THURSDAY - datetime.getDay())); } function weekGetter(size, monthBased) { if (monthBased === void 0) { monthBased = false; } return function (date, locale) { var result; if (monthBased) { var nbDaysBefore1stDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).getDay() - 1; var today = date.getDate(); result = 1 + Math.floor((today + nbDaysBefore1stDayOfMonth) / 7); } else { var thisThurs = getThursdayThisWeek(date); // Some days of a year are part of next year according to ISO 8601. // Compute the firstThurs from the year of this week's Thursday var firstThurs = getFirstThursdayOfYear(thisThurs.getFullYear()); var diff = thisThurs.getTime() - firstThurs.getTime(); result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week } return padNumber(result, size, getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign)); }; } /** * Returns a date formatter that provides the week-numbering year for the input date. */ function weekNumberingYearGetter(size, trim) { if (trim === void 0) { trim = false; } return function (date, locale) { var thisThurs = getThursdayThisWeek(date); var weekNumberingYear = thisThurs.getFullYear(); return padNumber(weekNumberingYear, size, getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign), trim); }; } var DATE_FORMATS = {}; // Based on CLDR formats: // See complete list: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table // See also explanations: http://cldr.unicode.org/translation/date-time // TODO(ocombe): support all missing cldr formats: U, Q, D, F, e, j, J, C, A, v, V, X, x function getDateFormatter(format) { if (DATE_FORMATS[format]) { return DATE_FORMATS[format]; } var formatter; switch (format) { // Era name (AD/BC) case 'G': case 'GG': case 'GGG': formatter = dateStrGetter(TranslationType.Eras, exports.TranslationWidth.Abbreviated); break; case 'GGGG': formatter = dateStrGetter(TranslationType.Eras, exports.TranslationWidth.Wide); break; case 'GGGGG': formatter = dateStrGetter(TranslationType.Eras, exports.TranslationWidth.Narrow); break; // 1 digit representation of the year, e.g. (AD 1 => 1, AD 199 => 199) case 'y': formatter = dateGetter(DateType.FullYear, 1, 0, false, true); break; // 2 digit representation of the year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) case 'yy': formatter = dateGetter(DateType.FullYear, 2, 0, true, true); break; // 3 digit representation of the year, padded (000-999). (e.g. AD 2001 => 01, AD 2010 => 10) case 'yyy': formatter = dateGetter(DateType.FullYear, 3, 0, false, true); break; // 4 digit representation of the year (e.g. AD 1 => 0001, AD 2010 => 2010) case 'yyyy': formatter = dateGetter(DateType.FullYear, 4, 0, false, true); break; // 1 digit representation of the week-numbering year, e.g. (AD 1 => 1, AD 199 => 199) case 'Y': formatter = weekNumberingYearGetter(1); break; // 2 digit representation of the week-numbering year, padded (00-99). (e.g. AD 2001 => 01, AD // 2010 => 10) case 'YY': formatter = weekNumberingYearGetter(2, true); break; // 3 digit representation of the week-numbering year, padded (000-999). (e.g. AD 1 => 001, AD // 2010 => 2010) case 'YYY': formatter = weekNumberingYearGetter(3); break; // 4 digit representation of the week-numbering year (e.g. AD 1 => 0001, AD 2010 => 2010) case 'YYYY': formatter = weekNumberingYearGetter(4); break; // Month of the year (1-12), numeric case 'M': case 'L': formatter = dateGetter(DateType.Month, 1, 1); break; case 'MM': case 'LL': formatter = dateGetter(DateType.Month, 2, 1); break; // Month of the year (January, ...), string, format case 'MMM': formatter = dateStrGetter(TranslationType.Months, exports.TranslationWidth.Abbreviated); break; case 'MMMM': formatter = dateStrGetter(TranslationType.Months, exports.TranslationWidth.Wide); break; case 'MMMMM': formatter = dateStrGetter(TranslationType.Months, exports.TranslationWidth.Narrow); break; // Month of the year (January, ...), string, standalone case 'LLL': formatter = dateStrGetter(TranslationType.Months, exports.TranslationWidth.Abbreviated, exports.FormStyle.Standalone); break; case 'LLLL': formatter = dateStrGetter(TranslationType.Months, exports.TranslationWidth.Wide, exports.FormStyle.Standalone); break; case 'LLLLL': formatter = dateStrGetter(TranslationType.Months, exports.TranslationWidth.Narrow, exports.FormStyle.Standalone); break; // Week of the year (1, ... 52) case 'w': formatter = weekGetter(1); break; case 'ww': formatter = weekGetter(2); break; // Week of the month (1, ...) case 'W': formatter = weekGetter(1, true); break; // Day of the month (1-31) case 'd': formatter = dateGetter(DateType.Date, 1); break; case 'dd': formatter = dateGetter(DateType.Date, 2); break; // Day of the Week StandAlone (1, 1, Mon, Monday, M, Mo) case 'c': case 'cc': formatter = dateGetter(DateType.Day, 1); break; case 'ccc': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Abbreviated, exports.FormStyle.Standalone); break; case 'cccc': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Wide, exports.FormStyle.Standalone); break; case 'ccccc': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Narrow, exports.FormStyle.Standalone); break; case 'cccccc': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Short, exports.FormStyle.Standalone); break; // Day of the Week case 'E': case 'EE': case 'EEE': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Abbreviated); break; case 'EEEE': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Wide); break; case 'EEEEE': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Narrow); break; case 'EEEEEE': formatter = dateStrGetter(TranslationType.Days, exports.TranslationWidth.Short); break; // Generic period of the day (am-pm) case 'a': case 'aa': case 'aaa': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Abbreviated); break; case 'aaaa': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Wide); break; case 'aaaaa': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Narrow); break; // Extended period of the day (midnight, at night, ...), standalone case 'b': case 'bb': case 'bbb': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Abbreviated, exports.FormStyle.Standalone, true); break; case 'bbbb': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Wide, exports.FormStyle.Standalone, true); break; case 'bbbbb': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Narrow, exports.FormStyle.Standalone, true); break; // Extended period of the day (midnight, night, ...), standalone case 'B': case 'BB': case 'BBB': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Abbreviated, exports.FormStyle.Format, true); break; case 'BBBB': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Wide, exports.FormStyle.Format, true); break; case 'BBBBB': formatter = dateStrGetter(TranslationType.DayPeriods, exports.TranslationWidth.Narrow, exports.FormStyle.Format, true); break; // Hour in AM/PM, (1-12) case 'h': formatter = dateGetter(DateType.Hours, 1, -12); break; case 'hh': formatter = dateGetter(DateType.Hours, 2, -12); break; // Hour of the day (0-23) case 'H': formatter = dateGetter(DateType.Hours, 1); break; // Hour in day, padded (00-23) case 'HH': formatter = dateGetter(DateType.Hours, 2); break; // Minute of the hour (0-59) case 'm': formatter = dateGetter(DateType.Minutes, 1); break; case 'mm': formatter = dateGetter(DateType.Minutes, 2); break; // Second of the minute (0-59) case 's': formatter = dateGetter(DateType.Seconds, 1); break; case 'ss': formatter = dateGetter(DateType.Seconds, 2); break; // Fractional second case 'S': formatter = dateGetter(DateType.FractionalSeconds, 1); break; case 'SS': formatter = dateGetter(DateType.FractionalSeconds, 2); break; case 'SSS': formatter = dateGetter(DateType.FractionalSeconds, 3); break; // Timezone ISO8601 short format (-0430) case 'Z': case 'ZZ': case 'ZZZ': formatter = timeZoneGetter(ZoneWidth.Short); break; // Timezone ISO8601 extended format (-04:30) case 'ZZZZZ': formatter = timeZoneGetter(ZoneWidth.Extended); break; // Timezone GMT short format (GMT+4) case 'O': case 'OO': case 'OOO': // Should be location, but fallback to format O instead because we don't have the data yet case 'z': case 'zz': case 'zzz': formatter = timeZoneGetter(ZoneWidth.ShortGMT); break; // Timezone GMT long format (GMT+0430) case 'OOOO': case 'ZZZZ': // Should be location, but fallback to format O instead because we don't have the data yet case 'zzzz': formatter = timeZoneGetter(ZoneWidth.Long); break; default: return null; } DATE_FORMATS[format] = formatter; return formatter; } function timezoneToOffset(timezone, fallback) { // Support: IE 11 only, Edge 13-15+ // IE/Edge do not "understand" colon (`:`) in timezone timezone = timezone.replace(/:/g, ''); var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; } function addDateMinutes(date, minutes) { date = new Date(date.getTime()); date.setMinutes(date.getMinutes() + minutes); return date; } function convertTimezoneToLocal(date, timezone, reverse) { var reverseValue = reverse ? -1 : 1; var dateTimezoneOffset = date.getTimezoneOffset(); var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); return addDateMinutes(date, reverseValue * (timezoneOffset - dateTimezoneOffset)); } /** * Converts a value to date. * * Supported input formats: * - `Date` * - number: timestamp * - string: numeric (e.g. "1234"), ISO and date strings in a format supported by * [Date.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse). * Note: ISO strings without time return a date without timeoffset. * * Throws if unable to convert to a date. */ function toDate(value) { if (isDate(value)) { return value; } if (typeof value === 'number' && !isNaN(value)) { return new Date(value); } if (typeof value === 'string') { value = value.trim(); if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) { /* For ISO Strings without time the day, month and year must be extracted from the ISO String before Date creation to avoid time offset and errors in the new Date. If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new date, some browsers (e.g. IE 9) will throw an invalid Date error. If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset is applied. Note: ISO months are 0 for January, 1 for February, ... */ var _a = __read(value.split('-').map(function (val) { return +val; }), 3), y = _a[0], _b = _a[1], m = _b === void 0 ? 1 : _b, _c = _a[2], d = _c === void 0 ? 1 : _c; return createDate(y, m - 1, d); } var parsedNb = parseFloat(value); // any string that only contains numbers, like "1234" but not like "1234hello" if (!isNaN(value - parsedNb)) { return new Date(parsedNb); } var match = void 0; if (match = value.match(ISO8601_DATE_REGEX)) { return isoStringToDate(match); } } var date = new Date(value); if (!isDate(date)) { throw new Error("Unable to convert \"" + value + "\" into a date"); } return date; } /** * Converts a date in ISO8601 to a Date. * Used instead of `Date.parse` because of browser discrepancies. */ function isoStringToDate(match) { var date = new Date(0); var tzHour = 0; var tzMin = 0; // match[8] means that the string contains "Z" (UTC) or a timezone like "+01:00" or "+0100" var dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear; var timeSetter = match[8] ? date.setUTCHours : date.setHours; // if there is a timezone defined like "+01:00" or "+0100" if (match[9]) { tzHour = Number(match[9] + match[10]); tzMin = Number(match[9] + match[11]); } dateSetter.call(date, Number(match[1]), Number(match[2]) - 1, Number(match[3])); var h = Number(match[4] || 0) - tzHour; var m = Number(match[5] || 0) - tzMin; var s = Number(match[6] || 0); // The ECMAScript specification (https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.11) // defines that `DateTime` milliseconds should always be rounded down, so that `999.9ms` // becomes `999ms`. var ms = Math.floor(parseFloat('0.' + (match[7] || 0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } function isDate(value) { return value instanceof Date && !isNaN(value.valueOf()); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/; var MAX_DIGITS = 22; var DECIMAL_SEP = '.'; var ZERO_CHAR = '0'; var PATTERN_SEP = ';'; var GROUP_SEP = ','; var DIGIT_CHAR = '#'; var CURRENCY_CHAR = '¤'; var PERCENT_CHAR = '%'; /** * Transforms a number to a locale string based on a style and a format. */ function formatNumberToLocaleString(value, pattern, locale, groupSymbol, decimalSymbol, digitsInfo, isPercent) { if (isPercent === void 0) { isPercent = false; } var formattedText = ''; var isZero = false; if (!isFinite(value)) { formattedText = getLocaleNumberSymbol(locale, exports.NumberSymbol.Infinity); } else { var parsedNumber = parseNumber(value); if (isPercent) { parsedNumber = toPercent(parsedNumber); } var minInt = pattern.minInt; var minFraction = pattern.minFrac; var maxFraction = pattern.maxFrac; if (digitsInfo) { var parts = digitsInfo.match(NUMBER_FORMAT_REGEXP); if (parts === null) { throw new Error(digitsInfo + " is not a valid digit info"); } var minIntPart = parts[1]; var minFractionPart = parts[3]; var maxFractionPart = parts[5]; if (minIntPart != null) { minInt = parseIntAutoRadix(minIntPart); } if (minFractionPart != null) { minFraction = parseIntAutoRadix(minFractionPart); } if (maxFractionPart != null) { maxFraction = parseIntAutoRadix(maxFractionPart); } else if (minFractionPart != null && minFraction > maxFraction) { maxFraction = minFraction; } } roundNumber(parsedNumber, minFraction, maxFraction); var digits = parsedNumber.digits; var integerLen = parsedNumber.integerLen; var exponent = parsedNumber.exponent; var decimals = []; isZero = digits.every(function (d) { return !d; }); // pad zeros for small numbers for (; integerLen < minInt; integerLen++) { digits.unshift(0); } // pad zeros for small numbers for (; integerLen < 0; integerLen++) { digits.unshift(0); } // extract decimals digits if (integerLen > 0) { decimals = digits.splice(integerLen, digits.length); } else { decimals = digits; digits = [0]; } // format the integer digits with grouping separators var groups = []; if (digits.length >= pattern.lgSize) { groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); } while (digits.length > pattern.gSize) { groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); } if (digits.length) { groups.unshift(digits.join('')); } formattedText = groups.join(getLocaleNumberSymbol(locale, groupSymbol)); // append the decimal digits if (decimals.length) { formattedText += getLocaleNumberSymbol(locale, decimalSymbol) + decimals.join(''); } if (exponent) { formattedText += getLocaleNumberSymbol(locale, exports.NumberSymbol.Exponential) + '+' + exponent; } } if (value < 0 && !isZero) { formattedText = pattern.negPre + formattedText + pattern.negSuf; } else { formattedText = pattern.posPre + formattedText + pattern.posSuf; } return formattedText; } /** * @ngModule CommonModule * @description * * Formats a number as currency using locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param currency A string containing the currency symbol or its name, * such as "$" or "Canadian Dollar". Used in output string, but does not affect the operation * of the function. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) * currency code, such as `USD` for the US dollar and `EUR` for the euro. * Used to determine the number of digits in the decimal part. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted currency value. * * @see `formatNumber()` * @see `DecimalPipe` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function formatCurrency(value, locale, currency, currencyCode, digitsInfo) { var format = getLocaleNumberFormat(locale, exports.NumberFormatStyle.Currency); var pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign)); pattern.minFrac = getNumberOfCurrencyDigits(currencyCode); pattern.maxFrac = pattern.minFrac; var res = formatNumberToLocaleString(value, pattern, locale, exports.NumberSymbol.CurrencyGroup, exports.NumberSymbol.CurrencyDecimal, digitsInfo); return res .replace(CURRENCY_CHAR, currency) // if we have 2 time the currency character, the second one is ignored .replace(CURRENCY_CHAR, '') // If there is a spacing between currency character and the value and // the currency character is supressed by passing an empty string, the // spacing character would remain as part of the string. Then we // should remove it. .trim(); } /** * @ngModule CommonModule * @description * * Formats a number as a percentage according to locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted percentage value. * * @see `formatNumber()` * @see `DecimalPipe` * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * @publicApi * */ function formatPercent(value, locale, digitsInfo) { var format = getLocaleNumberFormat(locale, exports.NumberFormatStyle.Percent); var pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign)); var res = formatNumberToLocaleString(value, pattern, locale, exports.NumberSymbol.Group, exports.NumberSymbol.Decimal, digitsInfo, true); return res.replace(new RegExp(PERCENT_CHAR, 'g'), getLocaleNumberSymbol(locale, exports.NumberSymbol.PercentSign)); } /** * @ngModule CommonModule * @description * * Formats a number as text, with group sizing, separator, and other * parameters based on the locale. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitsInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `DecimalPipe` for more details. * * @returns The formatted text string. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) * * @publicApi */ function formatNumber(value, locale, digitsInfo) { var format = getLocaleNumberFormat(locale, exports.NumberFormatStyle.Decimal); var pattern = parseNumberFormat(format, getLocaleNumberSymbol(locale, exports.NumberSymbol.MinusSign)); return formatNumberToLocaleString(value, pattern, locale, exports.NumberSymbol.Group, exports.NumberSymbol.Decimal, digitsInfo); } function parseNumberFormat(format, minusSign) { if (minusSign === void 0) { minusSign = '-'; } var p = { minInt: 1, minFrac: 0, maxFrac: 0, posPre: '', posSuf: '', negPre: '', negSuf: '', gSize: 0, lgSize: 0 }; var patternParts = format.split(PATTERN_SEP); var positive = patternParts[0]; var negative = patternParts[1]; var positiveParts = positive.indexOf(DECIMAL_SEP) !== -1 ? positive.split(DECIMAL_SEP) : [ positive.substring(0, positive.lastIndexOf(ZERO_CHAR) + 1), positive.substring(positive.lastIndexOf(ZERO_CHAR) + 1) ], integer = positiveParts[0], fraction = positiveParts[1] || ''; p.posPre = integer.substr(0, integer.indexOf(DIGIT_CHAR)); for (var i = 0; i < fraction.length; i++) { var ch = fraction.charAt(i); if (ch === ZERO_CHAR) { p.minFrac = p.maxFrac = i + 1; } else if (ch === DIGIT_CHAR) { p.maxFrac = i + 1; } else { p.posSuf += ch; } } var groups = integer.split(GROUP_SEP); p.gSize = groups[1] ? groups[1].length : 0; p.lgSize = (groups[2] || groups[1]) ? (groups[2] || groups[1]).length : 0; if (negative) { var trunkLen = positive.length - p.posPre.length - p.posSuf.length, pos = negative.indexOf(DIGIT_CHAR); p.negPre = negative.substr(0, pos).replace(/'/g, ''); p.negSuf = negative.substr(pos + trunkLen).replace(/'/g, ''); } else { p.negPre = minusSign + p.posPre; p.negSuf = p.posSuf; } return p; } // Transforms a parsed number into a percentage by multiplying it by 100 function toPercent(parsedNumber) { // if the number is 0, don't do anything if (parsedNumber.digits[0] === 0) { return parsedNumber; } // Getting the current number of decimals var fractionLen = parsedNumber.digits.length - parsedNumber.integerLen; if (parsedNumber.exponent) { parsedNumber.exponent += 2; } else { if (fractionLen === 0) { parsedNumber.digits.push(0, 0); } else if (fractionLen === 1) { parsedNumber.digits.push(0); } parsedNumber.integerLen += 2; } return parsedNumber; } /** * Parses a number. * Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/ */ function parseNumber(num) { var numStr = Math.abs(num) + ''; var exponent = 0, digits, integerLen; var i, j, zeros; // Decimal point? if ((integerLen = numStr.indexOf(DECIMAL_SEP)) > -1) { numStr = numStr.replace(DECIMAL_SEP, ''); } // Exponential form? if ((i = numStr.search(/e/i)) > 0) { // Work out the exponent. if (integerLen < 0) integerLen = i; integerLen += +numStr.slice(i + 1); numStr = numStr.substring(0, i); } else if (integerLen < 0) { // There was no decimal point or exponent so it is an integer. integerLen = numStr.length; } // Count the number of leading zeros. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } if (i === (zeros = numStr.length)) { // The digits are all zero. digits = [0]; integerLen = 1; } else { // Count the number of trailing zeros zeros--; while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; // Trailing zeros are insignificant so ignore them integerLen -= i; digits = []; // Convert string to array of digits without leading/trailing zeros. for (j = 0; i <= zeros; i++, j++) { digits[j] = Number(numStr.charAt(i)); } } // If the number overflows the maximum allowed digits then use an exponent. if (integerLen > MAX_DIGITS) { digits = digits.splice(0, MAX_DIGITS - 1); exponent = integerLen - 1; integerLen = 1; } return { digits: digits, exponent: exponent, integerLen: integerLen }; } /** * Round the parsed number to the specified number of decimal places * This function changes the parsedNumber in-place */ function roundNumber(parsedNumber, minFrac, maxFrac) { if (minFrac > maxFrac) { throw new Error("The minimum number of digits after fraction (" + minFrac + ") is higher than the maximum (" + maxFrac + ")."); } var digits = parsedNumber.digits; var fractionLen = digits.length - parsedNumber.integerLen; var fractionSize = Math.min(Math.max(minFrac, fractionLen), maxFrac); // The index of the digit to where rounding is to occur var roundAt = fractionSize + parsedNumber.integerLen; var digit = digits[roundAt]; if (roundAt > 0) { // Drop fractional digits beyond `roundAt` digits.splice(Math.max(parsedNumber.integerLen, roundAt)); // Set non-fractional digits beyond `roundAt` to 0 for (var j = roundAt; j < digits.length; j++) { digits[j] = 0; } } else { // We rounded to zero so reset the parsedNumber fractionLen = Math.max(0, fractionLen); parsedNumber.integerLen = 1; digits.length = Math.max(1, roundAt = fractionSize + 1); digits[0] = 0; for (var i = 1; i < roundAt; i++) digits[i] = 0; } if (digit >= 5) { if (roundAt - 1 < 0) { for (var k = 0; k > roundAt; k--) { digits.unshift(0); parsedNumber.integerLen++; } digits.unshift(1); parsedNumber.integerLen++; } else { digits[roundAt - 1]++; } } // Pad out with zeros to get the required fraction length for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); var dropTrailingZeros = fractionSize !== 0; // Minimal length = nb of decimals required + current nb of integers // Any number besides that is optional and can be removed if it's a trailing 0 var minLen = minFrac + parsedNumber.integerLen; // Do any carrying, e.g. a digit was rounded up to 10 var carry = digits.reduceRight(function (carry, d, i, digits) { d = d + carry; digits[i] = d < 10 ? d : d - 10; // d % 10 if (dropTrailingZeros) { // Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52) if (digits[i] === 0 && i >= minLen) { digits.pop(); } else { dropTrailingZeros = false; } } return d >= 10 ? 1 : 0; // Math.floor(d / 10); }, 0); if (carry) { digits.unshift(carry); parsedNumber.integerLen++; } } function parseIntAutoRadix(text) { var result = parseInt(text); if (isNaN(result)) { throw new Error('Invalid integer literal when parsing ' + text); } return result; } /** * @publicApi */ var NgLocalization = /** @class */ (function () { function NgLocalization() { } return NgLocalization; }()); /** * Returns the plural category for a given value. * - "=value" when the case exists, * - the plural category otherwise */ function getPluralCategory(value, cases, ngLocalization, locale) { var key = "=" + value; if (cases.indexOf(key) > -1) { return key; } key = ngLocalization.getPluralCategory(value, locale); if (cases.indexOf(key) > -1) { return key; } if (cases.indexOf('other') > -1) { return 'other'; } throw new Error("No plural message found for value \"" + value + "\""); } /** * Returns the plural case based on the locale * * @publicApi */ var NgLocaleLocalization = /** @class */ (function (_super) { __extends(NgLocaleLocalization, _super); function NgLocaleLocalization(locale) { var _this = _super.call(this) || this; _this.locale = locale; return _this; } NgLocaleLocalization.prototype.getPluralCategory = function (value, locale) { var plural = getLocalePluralCase(locale || this.locale)(value); switch (plural) { case exports.Plural.Zero: return 'zero'; case exports.Plural.One: return 'one'; case exports.Plural.Two: return 'two'; case exports.Plural.Few: return 'few'; case exports.Plural.Many: return 'many'; default: return 'other'; } }; return NgLocaleLocalization; }(NgLocalization)); NgLocaleLocalization.decorators = [ { type: i0.Injectable } ]; NgLocaleLocalization.ctorParameters = function () { return [ { type: String, decorators: [{ type: i0.Inject, args: [i0.LOCALE_ID,] }] } ]; }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Register global data to be used internally by Angular. See the * ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale data. * * The signature registerLocaleData(data: any, extraData?: any) is deprecated since v5.1 * * @publicApi */ function registerLocaleData(data, localeId, extraData) { return i0.ɵregisterLocaleData(data, localeId, extraData); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function parseCookieValue(cookieStr, name) { var e_1, _a; name = encodeURIComponent(name); try { for (var _b = __values(cookieStr.split(';')), _c = _b.next(); !_c.done; _c = _b.next()) { var cookie = _c.value; var eqIndex = cookie.indexOf('='); var _d = __read(eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)], 2), cookieName = _d[0], cookieValue = _d[1]; if (cookieName.trim() === name) { return decodeURIComponent(cookieValue); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return null; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @usageNotes * ``` * ... * * ... * * ... * * ... * * ... * ``` * * @description * * Adds and removes CSS classes on an HTML element. * * The CSS classes are updated as follows, depending on the type of the expression evaluation: * - `string` - the CSS classes listed in the string (space delimited) are added, * - `Array` - the CSS classes declared as Array elements are added, * - `Object` - keys are CSS classes that get added when the expression given in the value * evaluates to a truthy value, otherwise they are removed. * * @publicApi */ var NgClass = /** @class */ (function () { function NgClass(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) { this._iterableDiffers = _iterableDiffers; this._keyValueDiffers = _keyValueDiffers; this._ngEl = _ngEl; this._renderer = _renderer; this._iterableDiffer = null; this._keyValueDiffer = null; this._initialClasses = []; this._rawClass = null; } Object.defineProperty(NgClass.prototype, "klass", { set: function (value) { this._removeClasses(this._initialClasses); this._initialClasses = typeof value === 'string' ? value.split(/\s+/) : []; this._applyClasses(this._initialClasses); this._applyClasses(this._rawClass); }, enumerable: false, configurable: true }); Object.defineProperty(NgClass.prototype, "ngClass", { set: function (value) { this._removeClasses(this._rawClass); this._applyClasses(this._initialClasses); this._iterableDiffer = null; this._keyValueDiffer = null; this._rawClass = typeof value === 'string' ? value.split(/\s+/) : value; if (this._rawClass) { if (i0.ɵisListLikeIterable(this._rawClass)) { this._iterableDiffer = this._iterableDiffers.find(this._rawClass).create(); } else { this._keyValueDiffer = this._keyValueDiffers.find(this._rawClass).create(); } } }, enumerable: false, configurable: true }); NgClass.prototype.ngDoCheck = function () { if (this._iterableDiffer) { var iterableChanges = this._iterableDiffer.diff(this._rawClass); if (iterableChanges) { this._applyIterableChanges(iterableChanges); } } else if (this._keyValueDiffer) { var keyValueChanges = this._keyValueDiffer.diff(this._rawClass); if (keyValueChanges) { this._applyKeyValueChanges(keyValueChanges); } } }; NgClass.prototype._applyKeyValueChanges = function (changes) { var _this = this; changes.forEachAddedItem(function (record) { return _this._toggleClass(record.key, record.currentValue); }); changes.forEachChangedItem(function (record) { return _this._toggleClass(record.key, record.currentValue); }); changes.forEachRemovedItem(function (record) { if (record.previousValue) { _this._toggleClass(record.key, false); } }); }; NgClass.prototype._applyIterableChanges = function (changes) { var _this = this; changes.forEachAddedItem(function (record) { if (typeof record.item === 'string') { _this._toggleClass(record.item, true); } else { throw new Error("NgClass can only toggle CSS classes expressed as strings, got " + i0.ɵstringify(record.item)); } }); changes.forEachRemovedItem(function (record) { return _this._toggleClass(record.item, false); }); }; /** * Applies a collection of CSS classes to the DOM element. * * For argument of type Set and Array CSS class names contained in those collections are always * added. * For argument of type Map CSS class name in the map's key is toggled based on the value (added * for truthy and removed for falsy). */ NgClass.prototype._applyClasses = function (rawClassVal) { var _this = this; if (rawClassVal) { if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) { rawClassVal.forEach(function (klass) { return _this._toggleClass(klass, true); }); } else { Object.keys(rawClassVal).forEach(function (klass) { return _this._toggleClass(klass, !!rawClassVal[klass]); }); } } }; /** * Removes a collection of CSS classes from the DOM element. This is mostly useful for cleanup * purposes. */ NgClass.prototype._removeClasses = function (rawClassVal) { var _this = this; if (rawClassVal) { if (Array.isArray(rawClassVal) || rawClassVal instanceof Set) { rawClassVal.forEach(function (klass) { return _this._toggleClass(klass, false); }); } else { Object.keys(rawClassVal).forEach(function (klass) { return _this._toggleClass(klass, false); }); } } }; NgClass.prototype._toggleClass = function (klass, enabled) { var _this = this; klass = klass.trim(); if (klass) { klass.split(/\s+/g).forEach(function (klass) { if (enabled) { _this._renderer.addClass(_this._ngEl.nativeElement, klass); } else { _this._renderer.removeClass(_this._ngEl.nativeElement, klass); } }); } }; return NgClass; }()); NgClass.decorators = [ { type: i0.Directive, args: [{ selector: '[ngClass]' },] } ]; NgClass.ctorParameters = function () { return [ { type: i0.IterableDiffers }, { type: i0.KeyValueDiffers }, { type: i0.ElementRef }, { type: i0.Renderer2 } ]; }; NgClass.propDecorators = { klass: [{ type: i0.Input, args: ['class',] }], ngClass: [{ type: i0.Input, args: ['ngClass',] }] }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Instantiates a single {@link Component} type and inserts its Host View into current View. * `NgComponentOutlet` provides a declarative approach for dynamic component creation. * * `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and * any existing component will get destroyed. * * @usageNotes * * ### Fine tune control * * You can control the component creation process by using the following optional attributes: * * * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for * the Component. Defaults to the injector of the current view container. * * * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content * section of the component, if exists. * * * `ngComponentOutletNgModuleFactory`: Optional module factory to allow dynamically loading other * module, then load a component from that module. * * ### Syntax * * Simple * ``` * * ``` * * Customized injector/content * ``` * * * ``` * * Customized ngModuleFactory * ``` * * * ``` * * ### A simple example * * {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'} * * A more complete example with additional options: * * {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'} * * @publicApi * @ngModule CommonModule */ var NgComponentOutlet = /** @class */ (function () { function NgComponentOutlet(_viewContainerRef) { this._viewContainerRef = _viewContainerRef; this._componentRef = null; this._moduleRef = null; } NgComponentOutlet.prototype.ngOnChanges = function (changes) { this._viewContainerRef.clear(); this._componentRef = null; if (this.ngComponentOutlet) { var elInjector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector; if (changes['ngComponentOutletNgModuleFactory']) { if (this._moduleRef) this._moduleRef.destroy(); if (this.ngComponentOutletNgModuleFactory) { var parentModule = elInjector.get(i0.NgModuleRef); this._moduleRef = this.ngComponentOutletNgModuleFactory.create(parentModule.injector); } else { this._moduleRef = null; } } var componentFactoryResolver = this._moduleRef ? this._moduleRef.componentFactoryResolver : elInjector.get(i0.ComponentFactoryResolver); var componentFactory = componentFactoryResolver.resolveComponentFactory(this.ngComponentOutlet); this._componentRef = this._viewContainerRef.createComponent(componentFactory, this._viewContainerRef.length, elInjector, this.ngComponentOutletContent); } }; NgComponentOutlet.prototype.ngOnDestroy = function () { if (this._moduleRef) this._moduleRef.destroy(); }; return NgComponentOutlet; }()); NgComponentOutlet.decorators = [ { type: i0.Directive, args: [{ selector: '[ngComponentOutlet]' },] } ]; NgComponentOutlet.ctorParameters = function () { return [ { type: i0.ViewContainerRef } ]; }; NgComponentOutlet.propDecorators = { ngComponentOutlet: [{ type: i0.Input }], ngComponentOutletInjector: [{ type: i0.Input }], ngComponentOutletContent: [{ type: i0.Input }], ngComponentOutletNgModuleFactory: [{ type: i0.Input }] }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @publicApi */ var NgForOfContext = /** @class */ (function () { function NgForOfContext($implicit, ngForOf, index, count) { this.$implicit = $implicit; this.ngForOf = ngForOf; this.index = index; this.count = count; } Object.defineProperty(NgForOfContext.prototype, "first", { get: function () { return this.index === 0; }, enumerable: false, configurable: true }); Object.defineProperty(NgForOfContext.prototype, "last", { get: function () { return this.index === this.count - 1; }, enumerable: false, configurable: true }); Object.defineProperty(NgForOfContext.prototype, "even", { get: function () { return this.index % 2 === 0; }, enumerable: false, configurable: true }); Object.defineProperty(NgForOfContext.prototype, "odd", { get: function () { return !this.even; }, enumerable: false, configurable: true }); return NgForOfContext; }()); /** * A [structural directive](guide/structural-directives) that renders * a template for each item in a collection. * The directive is placed on an element, which becomes the parent * of the cloned templates. * * The `ngForOf` directive is generally used in the * [shorthand form](guide/structural-directives#asterisk) `*ngFor`. * In this form, the template to be rendered for each iteration is the content * of an anchor element containing the directive. * * The following example shows the shorthand syntax with some options, * contained in an `

  • ` element. * * ``` *
  • ...
  • * ``` * * The shorthand form expands into a long form that uses the `ngForOf` selector * on an `` element. * The content of the `` element is the `
  • ` element that held the * short-form directive. * * Here is the expanded version of the short-form example. * * ``` * *
  • ...
  • *
    * ``` * * Angular automatically expands the shorthand syntax as it compiles the template. * The context for each embedded view is logically merged to the current component * context according to its lexical position. * * When using the shorthand syntax, Angular allows only [one structural directive * on an element](guide/built-in-directives#one-per-element). * If you want to iterate conditionally, for example, * put the `*ngIf` on a container element that wraps the `*ngFor` element. * For futher discussion, see * [Structural Directives](guide/built-in-directives#one-per-element). * * @usageNotes * * ### Local variables * * `NgForOf` provides exported values that can be aliased to local variables. * For example: * * ``` *
  • * {{i}}/{{users.length}}. {{user}} default *
  • * ``` * * The following exported values can be aliased to local variables: * * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`). * - `ngForOf: NgIterable`: The value of the iterable expression. Useful when the expression is * more complex then a property access, for example when using the async pipe (`userStreams | * async`). * - `index: number`: The index of the current item in the iterable. * - `count: number`: The length of the iterable. * - `first: boolean`: True when the item is the first item in the iterable. * - `last: boolean`: True when the item is the last item in the iterable. * - `even: boolean`: True when the item has an even index in the iterable. * - `odd: boolean`: True when the item has an odd index in the iterable. * * ### Change propagation * * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * * Angular uses object identity to track insertions and deletions within the iterator and reproduce * those changes in the DOM. This has important implications for animations and any stateful * controls that are present, such as `` elements that accept user input. Inserted rows can * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state * such as user input. * For more on animations, see [Transitions and Triggers](guide/transition-and-triggers). * * The identities of elements in the iterator can change while the data does not. * This can happen, for example, if the iterator is produced from an RPC to the server, and that * RPC is re-run. Even if the data hasn't changed, the second response produces objects with * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old * elements were deleted and all new elements inserted). * * To avoid this expensive operation, you can customize the default tracking algorithm. * by supplying the `trackBy` option to `NgForOf`. * `trackBy` takes a function that has two arguments: `index` and `item`. * If `trackBy` is given, Angular tracks changes by the return value of the function. * * @see [Structural Directives](guide/structural-directives) * @ngModule CommonModule * @publicApi */ var NgForOf = /** @class */ (function () { function NgForOf(_viewContainer, _template, _differs) { this._viewContainer = _viewContainer; this._template = _template; this._differs = _differs; this._ngForOf = null; this._ngForOfDirty = true; this._differ = null; } Object.defineProperty(NgForOf.prototype, "ngForOf", { /** * The value of the iterable expression, which can be used as a * [template input variable](guide/structural-directives#shorthand). */ set: function (ngForOf) { this._ngForOf = ngForOf; this._ngForOfDirty = true; }, enumerable: false, configurable: true }); Object.defineProperty(NgForOf.prototype, "ngForTrackBy", { get: function () { return this._trackByFn; }, /** * Specifies a custom `TrackByFunction` to compute the identity of items in an iterable. * * If a custom `TrackByFunction` is not provided, `NgForOf` will use the item's [object * identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) * as the key. * * `NgForOf` uses the computed key to associate items in an iterable with DOM elements * it produces for these items. * * A custom `TrackByFunction` is useful to provide good user experience in cases when items in an * iterable rendered using `NgForOf` have a natural identifier (for example, custom ID or a * primary key), and this iterable could be updated with new object instances that still * represent the same underlying entity (for example, when data is re-fetched from the server, * and the iterable is recreated and re-rendered, but most of the data is still the same). * * @see `TrackByFunction` */ set: function (fn) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') { // TODO(vicb): use a log service once there is a public one available if (console && console.warn) { console.warn("trackBy must be a function, but received " + JSON.stringify(fn) + ". " + "See https://angular.io/api/common/NgForOf#change-propagation for more information."); } } this._trackByFn = fn; }, enumerable: false, configurable: true }); Object.defineProperty(NgForOf.prototype, "ngForTemplate", { /** * A reference to the template that is stamped out for each item in the iterable. * @see [template reference variable](guide/template-reference-variables) */ set: function (value) { // TODO(TS2.1): make TemplateRef>> once we move to TS v2.1 // The current type is too restrictive; a template that just uses index, for example, // should be acceptable. if (value) { this._template = value; } }, enumerable: false, configurable: true }); /** * Applies the changes when needed. */ NgForOf.prototype.ngDoCheck = function () { if (this._ngForOfDirty) { this._ngForOfDirty = false; // React on ngForOf changes only once all inputs have been initialized var value = this._ngForOf; if (!this._differ && value) { try { this._differ = this._differs.find(value).create(this.ngForTrackBy); } catch (_a) { throw new Error("Cannot find a differ supporting object '" + value + "' of type '" + getTypeName(value) + "'. NgFor only supports binding to Iterables such as Arrays."); } } } if (this._differ) { var changes = this._differ.diff(this._ngForOf); if (changes) this._applyChanges(changes); } }; NgForOf.prototype._applyChanges = function (changes) { var _this = this; var insertTuples = []; changes.forEachOperation(function (item, adjustedPreviousIndex, currentIndex) { if (item.previousIndex == null) { // NgForOf is never "null" or "undefined" here because the differ detected // that a new item needs to be inserted from the iterable. This implies that // there is an iterable value for "_ngForOf". var view = _this._viewContainer.createEmbeddedView(_this._template, new NgForOfContext(null, _this._ngForOf, -1, -1), currentIndex === null ? undefined : currentIndex); var tuple = new RecordViewTuple(item, view); insertTuples.push(tuple); } else if (currentIndex == null) { _this._viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex); } else if (adjustedPreviousIndex !== null) { var view = _this._viewContainer.get(adjustedPreviousIndex); _this._viewContainer.move(view, currentIndex); var tuple = new RecordViewTuple(item, view); insertTuples.push(tuple); } }); for (var i = 0; i < insertTuples.length; i++) { this._perViewChange(insertTuples[i].view, insertTuples[i].record); } for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) { var viewRef = this._viewContainer.get(i); viewRef.context.index = i; viewRef.context.count = ilen; viewRef.context.ngForOf = this._ngForOf; } changes.forEachIdentityChange(function (record) { var viewRef = _this._viewContainer.get(record.currentIndex); viewRef.context.$implicit = record.item; }); }; NgForOf.prototype._perViewChange = function (view, record) { view.context.$implicit = record.item; }; /** * Asserts the correct type of the context for the template that `NgForOf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgForOf` structural directive renders its template with a specific context type. */ NgForOf.ngTemplateContextGuard = function (dir, ctx) { return true; }; return NgForOf; }()); NgForOf.decorators = [ { type: i0.Directive, args: [{ selector: '[ngFor][ngForOf]' },] } ]; NgForOf.ctorParameters = function () { return [ { type: i0.ViewContainerRef }, { type: i0.TemplateRef }, { type: i0.IterableDiffers } ]; }; NgForOf.propDecorators = { ngForOf: [{ type: i0.Input }], ngForTrackBy: [{ type: i0.Input }], ngForTemplate: [{ type: i0.Input }] }; var RecordViewTuple = /** @class */ (function () { function RecordViewTuple(record, view) { this.record = record; this.view = view; } return RecordViewTuple; }()); function getTypeName(type) { return type['name'] || typeof type; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A structural directive that conditionally includes a template based on the value of * an expression coerced to Boolean. * When the expression evaluates to true, Angular renders the template * provided in a `then` clause, and when false or null, * Angular renders the template provided in an optional `else` clause. The default * template for the `else` clause is blank. * * A [shorthand form](guide/structural-directives#asterisk) of the directive, * `*ngIf="condition"`, is generally used, provided * as an attribute of the anchor element for the inserted template. * Angular expands this into a more explicit version, in which the anchor element * is contained in an `` element. * * Simple form with shorthand syntax: * * ``` *
    Content to render when condition is true.
    * ``` * * Simple form with expanded syntax: * * ``` *
    Content to render when condition is * true.
    * ``` * * Form with an "else" block: * * ``` *
    Content to render when condition is true.
    * Content to render when condition is false. * ``` * * Shorthand form with "then" and "else" blocks: * * ``` *
    * Content to render when condition is true. * Content to render when condition is false. * ``` * * Form with storing the value locally: * * ``` *
    {{value}}
    * Content to render when value is null. * ``` * * @usageNotes * * The `*ngIf` directive is most commonly used to conditionally show an inline template, * as seen in the following example. * The default `else` template is blank. * * {@example common/ngIf/ts/module.ts region='NgIfSimple'} * * ### Showing an alternative template using `else` * * To display a template when `expression` evaluates to false, use an `else` template * binding as shown in the following example. * The `else` binding points to an `` element labeled `#elseBlock`. * The template can be defined anywhere in the component view, but is typically placed right after * `ngIf` for readability. * * {@example common/ngIf/ts/module.ts region='NgIfElse'} * * ### Using an external `then` template * * In the previous example, the then-clause template is specified inline, as the content of the * tag that contains the `ngIf` directive. You can also specify a template that is defined * externally, by referencing a labeled `` element. When you do this, you can * change which template to use at runtime, as shown in the following example. * * {@example common/ngIf/ts/module.ts region='NgIfThenElse'} * * ### Storing a conditional result in a variable * * You might want to show a set of properties from the same object. If you are waiting * for asynchronous data, the object can be undefined. * In this case, you can use `ngIf` and store the result of the condition in a local * variable as shown in the following example. * * {@example common/ngIf/ts/module.ts region='NgIfAs'} * * This code uses only one `AsyncPipe`, so only one subscription is created. * The conditional statement stores the result of `userStream|async` in the local variable `user`. * You can then bind the local `user` repeatedly. * * The conditional displays the data only if `userStream` returns a value, * so you don't need to use the * safe-navigation-operator (`?.`) * to guard against null values when accessing properties. * You can display an alternative template while waiting for the data. * * ### Shorthand syntax * * The shorthand syntax `*ngIf` expands into two separate template specifications * for the "then" and "else" clauses. For example, consider the following shorthand statement, * that is meant to show a loading page while waiting for data to be loaded. * * ``` *
    * ... *
    * * *
    Loading...
    *
    * ``` * * You can see that the "else" clause references the `` * with the `#loading` label, and the template for the "then" clause * is provided as the content of the anchor element. * * However, when Angular expands the shorthand syntax, it creates * another `` tag, with `ngIf` and `ngIfElse` directives. * The anchor element containing the template for the "then" clause becomes * the content of this unlabeled `` tag. * * ``` * *
    * ... *
    *
    * * *
    Loading...
    *
    * ``` * * The presence of the implicit template object has implications for the nesting of * structural directives. For more on this subject, see * [Structural Directives](https://angular.io/guide/built-in-directives#one-per-element). * * @ngModule CommonModule * @publicApi */ var NgIf = /** @class */ (function () { function NgIf(_viewContainer, templateRef) { this._viewContainer = _viewContainer; this._context = new NgIfContext(); this._thenTemplateRef = null; this._elseTemplateRef = null; this._thenViewRef = null; this._elseViewRef = null; this._thenTemplateRef = templateRef; } Object.defineProperty(NgIf.prototype, "ngIf", { /** * The Boolean expression to evaluate as the condition for showing a template. */ set: function (condition) { this._context.$implicit = this._context.ngIf = condition; this._updateView(); }, enumerable: false, configurable: true }); Object.defineProperty(NgIf.prototype, "ngIfThen", { /** * A template to show if the condition expression evaluates to true. */ set: function (templateRef) { assertTemplate('ngIfThen', templateRef); this._thenTemplateRef = templateRef; this._thenViewRef = null; // clear previous view if any. this._updateView(); }, enumerable: false, configurable: true }); Object.defineProperty(NgIf.prototype, "ngIfElse", { /** * A template to show if the condition expression evaluates to false. */ set: function (templateRef) { assertTemplate('ngIfElse', templateRef); this._elseTemplateRef = templateRef; this._elseViewRef = null; // clear previous view if any. this._updateView(); }, enumerable: false, configurable: true }); NgIf.prototype._updateView = function () { if (this._context.$implicit) { if (!this._thenViewRef) { this._viewContainer.clear(); this._elseViewRef = null; if (this._thenTemplateRef) { this._thenViewRef = this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context); } } } else { if (!this._elseViewRef) { this._viewContainer.clear(); this._thenViewRef = null; if (this._elseTemplateRef) { this._elseViewRef = this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context); } } } }; /** * Asserts the correct type of the context for the template that `NgIf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgIf` structural directive renders its template with a specific context type. */ NgIf.ngTemplateContextGuard = function (dir, ctx) { return true; }; return NgIf; }()); NgIf.decorators = [ { type: i0.Directive, args: [{ selector: '[ngIf]' },] } ]; NgIf.ctorParameters = function () { return [ { type: i0.ViewContainerRef }, { type: i0.TemplateRef } ]; }; NgIf.propDecorators = { ngIf: [{ type: i0.Input }], ngIfThen: [{ type: i0.Input }], ngIfElse: [{ type: i0.Input }] }; /** * @publicApi */ var NgIfContext = /** @class */ (function () { function NgIfContext() { this.$implicit = null; this.ngIf = null; } return NgIfContext; }()); function assertTemplate(property, templateRef) { var isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView); if (!isTemplateRefOrNull) { throw new Error(property + " must be a TemplateRef, but received '" + i0.ɵstringify(templateRef) + "'."); } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var SwitchView = /** @class */ (function () { function SwitchView(_viewContainerRef, _templateRef) { this._viewContainerRef = _viewContainerRef; this._templateRef = _templateRef; this._created = false; } SwitchView.prototype.create = function () { this._created = true; this._viewContainerRef.createEmbeddedView(this._templateRef); }; SwitchView.prototype.destroy = function () { this._created = false; this._viewContainerRef.clear(); }; SwitchView.prototype.enforceState = function (created) { if (created && !this._created) { this.create(); } else if (!created && this._created) { this.destroy(); } }; return SwitchView; }()); /** * @ngModule CommonModule * * @description * The `[ngSwitch]` directive on a container specifies an expression to match against. * The expressions to match are provided by `ngSwitchCase` directives on views within the container. * - Every view that matches is rendered. * - If there are no matches, a view with the `ngSwitchDefault` directive is rendered. * - Elements within the `[NgSwitch]` statement but outside of any `NgSwitchCase` * or `ngSwitchDefault` directive are preserved at the location. * * @usageNotes * Define a container element for the directive, and specify the switch expression * to match against as an attribute: * * ``` * * ``` * * Within the container, `*ngSwitchCase` statements specify the match expressions * as attributes. Include `*ngSwitchDefault` as the final case. * * ``` * * ... * ... * ... * * ``` * * ### Usage Examples * * The following example shows how to use more than one case to display the same view: * * ``` * * * ... * ... * ... * * ... * * ``` * * The following example shows how cases can be nested: * ``` * * ... * ... * ... * * * * * * ... * * ``` * * @publicApi * @see `NgSwitchCase` * @see `NgSwitchDefault` * @see [Structural Directives](guide/structural-directives) * */ var NgSwitch = /** @class */ (function () { function NgSwitch() { this._defaultUsed = false; this._caseCount = 0; this._lastCaseCheckIndex = 0; this._lastCasesMatched = false; } Object.defineProperty(NgSwitch.prototype, "ngSwitch", { set: function (newValue) { this._ngSwitch = newValue; if (this._caseCount === 0) { this._updateDefaultCases(true); } }, enumerable: false, configurable: true }); /** @internal */ NgSwitch.prototype._addCase = function () { return this._caseCount++; }; /** @internal */ NgSwitch.prototype._addDefault = function (view) { if (!this._defaultViews) { this._defaultViews = []; } this._defaultViews.push(view); }; /** @internal */ NgSwitch.prototype._matchCase = function (value) { var matched = value == this._ngSwitch; this._lastCasesMatched = this._lastCasesMatched || matched; this._lastCaseCheckIndex++; if (this._lastCaseCheckIndex === this._caseCount) { this._updateDefaultCases(!this._lastCasesMatched); this._lastCaseCheckIndex = 0; this._lastCasesMatched = false; } return matched; }; NgSwitch.prototype._updateDefaultCases = function (useDefault) { if (this._defaultViews && useDefault !== this._defaultUsed) { this._defaultUsed = useDefault; for (var i = 0; i < this._defaultViews.length; i++) { var defaultView = this._defaultViews[i]; defaultView.enforceState(useDefault); } } }; return NgSwitch; }()); NgSwitch.decorators = [ { type: i0.Directive, args: [{ selector: '[ngSwitch]' },] } ]; NgSwitch.propDecorators = { ngSwitch: [{ type: i0.Input }] }; /** * @ngModule CommonModule * * @description * Provides a switch case expression to match against an enclosing `ngSwitch` expression. * When the expressions match, the given `NgSwitchCase` template is rendered. * If multiple match expressions match the switch expression value, all of them are displayed. * * @usageNotes * * Within a switch container, `*ngSwitchCase` statements specify the match expressions * as attributes. Include `*ngSwitchDefault` as the final case. * * ``` * * ... * ... * ... * * ``` * * Each switch-case statement contains an in-line HTML template or template reference * that defines the subtree to be selected if the value of the match expression * matches the value of the switch expression. * * Unlike JavaScript, which uses strict equality, Angular uses loose equality. * This means that the empty string, `""` matches 0. * * @publicApi * @see `NgSwitch` * @see `NgSwitchDefault` * */ var NgSwitchCase = /** @class */ (function () { function NgSwitchCase(viewContainer, templateRef, ngSwitch) { this.ngSwitch = ngSwitch; if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) { throwNgSwitchProviderNotFoundError('ngSwitchCase', 'NgSwitchCase'); } ngSwitch._addCase(); this._view = new SwitchView(viewContainer, templateRef); } /** * Performs case matching. For internal use only. */ NgSwitchCase.prototype.ngDoCheck = function () { this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); }; return NgSwitchCase; }()); NgSwitchCase.decorators = [ { type: i0.Directive, args: [{ selector: '[ngSwitchCase]' },] } ]; NgSwitchCase.ctorParameters = function () { return [ { type: i0.ViewContainerRef }, { type: i0.TemplateRef }, { type: NgSwitch, decorators: [{ type: i0.Optional }, { type: i0.Host }] } ]; }; NgSwitchCase.propDecorators = { ngSwitchCase: [{ type: i0.Input }] }; /** * @ngModule CommonModule * * @description * * Creates a view that is rendered when no `NgSwitchCase` expressions * match the `NgSwitch` expression. * This statement should be the final case in an `NgSwitch`. * * @publicApi * @see `NgSwitch` * @see `NgSwitchCase` * */ var NgSwitchDefault = /** @class */ (function () { function NgSwitchDefault(viewContainer, templateRef, ngSwitch) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) { throwNgSwitchProviderNotFoundError('ngSwitchDefault', 'NgSwitchDefault'); } ngSwitch._addDefault(new SwitchView(viewContainer, templateRef)); } return NgSwitchDefault; }()); NgSwitchDefault.decorators = [ { type: i0.Directive, args: [{ selector: '[ngSwitchDefault]' },] } ]; NgSwitchDefault.ctorParameters = function () { return [ { type: i0.ViewContainerRef }, { type: i0.TemplateRef }, { type: NgSwitch, decorators: [{ type: i0.Optional }, { type: i0.Host }] } ]; }; function throwNgSwitchProviderNotFoundError(attrName, directiveName) { throw new i0.ɵRuntimeError("305" /* TEMPLATE_STRUCTURE_ERROR */, "An element with the \"" + attrName + "\" attribute " + ("(matching the \"" + directiveName + "\" directive) must be located inside an element with the \"ngSwitch\" attribute ") + "(matching \"NgSwitch\" directive)"); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @usageNotes * ``` * * there is nothing * there is one * there are a few * * ``` * * @description * * Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization. * * Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees * that match the switch expression's pluralization category. * * To use this directive you must provide a container element that sets the `[ngPlural]` attribute * to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their * expression: * - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value * matches the switch expression exactly, * - otherwise, the view will be treated as a "category match", and will only display if exact * value matches aren't found and the value maps to its category for the defined locale. * * See http://cldr.unicode.org/index/cldr-spec/plural-rules * * @publicApi */ var NgPlural = /** @class */ (function () { function NgPlural(_localization) { this._localization = _localization; this._caseViews = {}; } Object.defineProperty(NgPlural.prototype, "ngPlural", { set: function (value) { this._switchValue = value; this._updateView(); }, enumerable: false, configurable: true }); NgPlural.prototype.addCase = function (value, switchView) { this._caseViews[value] = switchView; }; NgPlural.prototype._updateView = function () { this._clearViews(); var cases = Object.keys(this._caseViews); var key = getPluralCategory(this._switchValue, cases, this._localization); this._activateView(this._caseViews[key]); }; NgPlural.prototype._clearViews = function () { if (this._activeView) this._activeView.destroy(); }; NgPlural.prototype._activateView = function (view) { if (view) { this._activeView = view; this._activeView.create(); } }; return NgPlural; }()); NgPlural.decorators = [ { type: i0.Directive, args: [{ selector: '[ngPlural]' },] } ]; NgPlural.ctorParameters = function () { return [ { type: NgLocalization } ]; }; NgPlural.propDecorators = { ngPlural: [{ type: i0.Input }] }; /** * @ngModule CommonModule * * @description * * Creates a view that will be added/removed from the parent {@link NgPlural} when the * given expression matches the plural expression according to CLDR rules. * * @usageNotes * ``` * * ... * ... * *``` * * See {@link NgPlural} for more details and example. * * @publicApi */ var NgPluralCase = /** @class */ (function () { function NgPluralCase(value, template, viewContainer, ngPlural) { this.value = value; var isANumber = !isNaN(Number(value)); ngPlural.addCase(isANumber ? "=" + value : value, new SwitchView(viewContainer, template)); } return NgPluralCase; }()); NgPluralCase.decorators = [ { type: i0.Directive, args: [{ selector: '[ngPluralCase]' },] } ]; NgPluralCase.ctorParameters = function () { return [ { type: String, decorators: [{ type: i0.Attribute, args: ['ngPluralCase',] }] }, { type: i0.TemplateRef }, { type: i0.ViewContainerRef }, { type: NgPlural, decorators: [{ type: i0.Host }] } ]; }; /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * ... * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * ... * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * ... * ``` * * @description * * An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs. * The key is a style name, with an optional `.` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ var NgStyle = /** @class */ (function () { function NgStyle(_ngEl, _differs, _renderer) { this._ngEl = _ngEl; this._differs = _differs; this._renderer = _renderer; this._ngStyle = null; this._differ = null; } Object.defineProperty(NgStyle.prototype, "ngStyle", { set: function (values) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } }, enumerable: false, configurable: true }); NgStyle.prototype.ngDoCheck = function () { if (this._differ) { var changes = this._differ.diff(this._ngStyle); if (changes) { this._applyChanges(changes); } } }; NgStyle.prototype._setStyle = function (nameAndUnit, value) { var _a = __read(nameAndUnit.split('.'), 2), name = _a[0], unit = _a[1]; value = value != null && unit ? "" + value + unit : value; if (value != null) { this._renderer.setStyle(this._ngEl.nativeElement, name, value); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name); } }; NgStyle.prototype._applyChanges = function (changes) { var _this = this; changes.forEachRemovedItem(function (record) { return _this._setStyle(record.key, null); }); changes.forEachAddedItem(function (record) { return _this._setStyle(record.key, record.currentValue); }); changes.forEachChangedItem(function (record) { return _this._setStyle(record.key, record.currentValue); }); }; return NgStyle; }()); NgStyle.decorators = [ { type: i0.Directive, args: [{ selector: '[ngStyle]' },] } ]; NgStyle.ctorParameters = function () { return [ { type: i0.ElementRef }, { type: i0.KeyValueDiffers }, { type: i0.Renderer2 } ]; }; NgStyle.propDecorators = { ngStyle: [{ type: i0.Input, args: ['ngStyle',] }] }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * * @description * * Inserts an embedded view from a prepared `TemplateRef`. * * You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`. * `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding * by the local template `let` declarations. * * @usageNotes * ``` * * ``` * * Using the key `$implicit` in the context object will set its value as default. * * ### Example * * {@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'} * * @publicApi */ var NgTemplateOutlet = /** @class */ (function () { function NgTemplateOutlet(_viewContainerRef) { this._viewContainerRef = _viewContainerRef; this._viewRef = null; /** * A context object to attach to the {@link EmbeddedViewRef}. This should be an * object, the object's keys will be available for binding by the local template `let` * declarations. * Using the key `$implicit` in the context object will set its value as default. */ this.ngTemplateOutletContext = null; /** * A string defining the template reference and optionally the context object for the template. */ this.ngTemplateOutlet = null; } NgTemplateOutlet.prototype.ngOnChanges = function (changes) { if (changes['ngTemplateOutlet']) { var viewContainerRef = this._viewContainerRef; if (this._viewRef) { viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef)); } this._viewRef = this.ngTemplateOutlet ? viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, this.ngTemplateOutletContext) : null; } else if (this._viewRef && changes['ngTemplateOutletContext'] && this.ngTemplateOutletContext) { this._viewRef.context = this.ngTemplateOutletContext; } }; return NgTemplateOutlet; }()); NgTemplateOutlet.decorators = [ { type: i0.Directive, args: [{ selector: '[ngTemplateOutlet]' },] } ]; NgTemplateOutlet.ctorParameters = function () { return [ { type: i0.ViewContainerRef } ]; }; NgTemplateOutlet.propDecorators = { ngTemplateOutletContext: [{ type: i0.Input }], ngTemplateOutlet: [{ type: i0.Input }] }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A collection of Angular directives that are likely to be used in each and every Angular * application. */ var COMMON_DIRECTIVES = [ NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function invalidPipeArgumentError(type, value) { return Error("InvalidPipeArgument: '" + value + "' for pipe '" + i0.ɵstringify(type) + "'"); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var SubscribableStrategy = /** @class */ (function () { function SubscribableStrategy() { } SubscribableStrategy.prototype.createSubscription = function (async, updateLatestValue) { return async.subscribe({ next: updateLatestValue, error: function (e) { throw e; } }); }; SubscribableStrategy.prototype.dispose = function (subscription) { subscription.unsubscribe(); }; SubscribableStrategy.prototype.onDestroy = function (subscription) { subscription.unsubscribe(); }; return SubscribableStrategy; }()); var PromiseStrategy = /** @class */ (function () { function PromiseStrategy() { } PromiseStrategy.prototype.createSubscription = function (async, updateLatestValue) { return async.then(updateLatestValue, function (e) { throw e; }); }; PromiseStrategy.prototype.dispose = function (subscription) { }; PromiseStrategy.prototype.onDestroy = function (subscription) { }; return PromiseStrategy; }()); var _promiseStrategy = new PromiseStrategy(); var _subscribableStrategy = new SubscribableStrategy(); /** * @ngModule CommonModule * @description * * Unwraps a value from an asynchronous primitive. * * The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has * emitted. When a new value is emitted, the `async` pipe marks the component to be checked for * changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid * potential memory leaks. * * @usageNotes * * ### Examples * * This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the * promise. * * {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'} * * It's also possible to use `async` with Observables. The example below binds the `time` Observable * to the view. The Observable continuously updates the view with the current time. * * {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'} * * @publicApi */ var AsyncPipe = /** @class */ (function () { function AsyncPipe(_ref) { this._ref = _ref; this._latestValue = null; this._subscription = null; this._obj = null; this._strategy = null; } AsyncPipe.prototype.ngOnDestroy = function () { if (this._subscription) { this._dispose(); } }; AsyncPipe.prototype.transform = function (obj) { if (!this._obj) { if (obj) { this._subscribe(obj); } return this._latestValue; } if (obj !== this._obj) { this._dispose(); return this.transform(obj); } return this._latestValue; }; AsyncPipe.prototype._subscribe = function (obj) { var _this = this; this._obj = obj; this._strategy = this._selectStrategy(obj); this._subscription = this._strategy.createSubscription(obj, function (value) { return _this._updateLatestValue(obj, value); }); }; AsyncPipe.prototype._selectStrategy = function (obj) { if (i0.ɵisPromise(obj)) { return _promiseStrategy; } if (i0.ɵisSubscribable(obj)) { return _subscribableStrategy; } throw invalidPipeArgumentError(AsyncPipe, obj); }; AsyncPipe.prototype._dispose = function () { this._strategy.dispose(this._subscription); this._latestValue = null; this._subscription = null; this._obj = null; }; AsyncPipe.prototype._updateLatestValue = function (async, value) { if (async === this._obj) { this._latestValue = value; this._ref.markForCheck(); } }; return AsyncPipe; }()); AsyncPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'async', pure: false },] } ]; AsyncPipe.ctorParameters = function () { return [ { type: i0.ChangeDetectorRef } ]; }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Transforms text to all lower case. * * @see `UpperCasePipe` * @see `TitleCasePipe` * @usageNotes * * The following example defines a view that allows the user to enter * text, and then uses the pipe to convert the input text to all lower case. * * * * @ngModule CommonModule * @publicApi */ var LowerCasePipe = /** @class */ (function () { function LowerCasePipe() { } LowerCasePipe.prototype.transform = function (value) { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(LowerCasePipe, value); } return value.toLowerCase(); }; return LowerCasePipe; }()); LowerCasePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'lowercase' },] } ]; // // Regex below matches any Unicode word and compatible with ES5. In ES2018 the same result // can be achieved by using /\p{L}\S*/gu and also known as Unicode Property Escapes // (https://2ality.com/2017/07/regexp-unicode-property-escapes.html). Since there is no // transpilation of this functionality down to ES5 without external tool, the only solution is // to use already transpiled form. Example can be found here - // https://mothereff.in/regexpu#input=var+regex+%3D+/%5Cp%7BL%7D/u%3B&unicodePropertyEscape=1 // var unicodeWordMatch = /(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\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\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\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\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])\S*/g; /** * Transforms text to title case. * Capitalizes the first letter of each word and transforms the * rest of the word to lower case. * Words are delimited by any whitespace character, such as a space, tab, or line-feed character. * * @see `LowerCasePipe` * @see `UpperCasePipe` * * @usageNotes * The following example shows the result of transforming various strings into title case. * * * * @ngModule CommonModule * @publicApi */ var TitleCasePipe = /** @class */ (function () { function TitleCasePipe() { } TitleCasePipe.prototype.transform = function (value) { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(TitleCasePipe, value); } return value.replace(unicodeWordMatch, (function (txt) { return txt[0].toUpperCase() + txt.substr(1).toLowerCase(); })); }; return TitleCasePipe; }()); TitleCasePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'titlecase' },] } ]; /** * Transforms text to all upper case. * @see `LowerCasePipe` * @see `TitleCasePipe` * * @ngModule CommonModule * @publicApi */ var UpperCasePipe = /** @class */ (function () { function UpperCasePipe() { } UpperCasePipe.prototype.transform = function (value) { if (value == null) return null; if (typeof value !== 'string') { throw invalidPipeArgumentError(UpperCasePipe, value); } return value.toUpperCase(); }; return UpperCasePipe; }()); UpperCasePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'uppercase' },] } ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // clang-format off /** * @ngModule CommonModule * @description * * Formats a date value according to locale rules. * * `DatePipe` is executed only when it detects a pure change to the input value. * A pure change is either a change to a primitive input value * (such as `String`, `Number`, `Boolean`, or `Symbol`), * or a changed object reference (such as `Date`, `Array`, `Function`, or `Object`). * * Note that mutating a `Date` object does not cause the pipe to be rendered again. * To ensure that the pipe is executed, you must create a new `Date` object. * * Only the `en-US` locale data comes with Angular. To localize dates * in another language, you must import the corresponding locale data. * See the [I18n guide](guide/i18n#i18n-pipes) for more information. * * @see `formatDate()` * * * @usageNotes * * The result of this pipe is not reevaluated when the input is mutated. To avoid the need to * reformat the date on every change-detection cycle, treat the date as an immutable object * and change the reference when the pipe needs to run again. * * ### Pre-defined format options * * | Option | Equivalent to | Examples (given in `en-US` locale) | * |---------------|-------------------------------------|-------------------------------------------------| * | `'short'` | `'M/d/yy, h:mm a'` | `6/15/15, 9:03 AM` | * | `'medium'` | `'MMM d, y, h:mm:ss a'` | `Jun 15, 2015, 9:03:01 AM` | * | `'long'` | `'MMMM d, y, h:mm:ss a z'` | `June 15, 2015 at 9:03:01 AM GMT+1` | * | `'full'` | `'EEEE, MMMM d, y, h:mm:ss a zzzz'` | `Monday, June 15, 2015 at 9:03:01 AM GMT+01:00` | * | `'shortDate'` | `'M/d/yy'` | `6/15/15` | * | `'mediumDate'`| `'MMM d, y'` | `Jun 15, 2015` | * | `'longDate'` | `'MMMM d, y'` | `June 15, 2015` | * | `'fullDate'` | `'EEEE, MMMM d, y'` | `Monday, June 15, 2015` | * | `'shortTime'` | `'h:mm a'` | `9:03 AM` | * | `'mediumTime'`| `'h:mm:ss a'` | `9:03:01 AM` | * | `'longTime'` | `'h:mm:ss a z'` | `9:03:01 AM GMT+1` | * | `'fullTime'` | `'h:mm:ss a zzzz'` | `9:03:01 AM GMT+01:00` | * * ### Custom format options * * You can construct a format string using symbols to specify the components * of a date-time value, as described in the following table. * Format details depend on the locale. * Fields marked with (*) are only available in the extra data set for the given locale. * * | Field type | Format | Description | Example Value | * |-------------------- |-------------|---------------------------------------------------------------|------------------------------------------------------------| * | Era | G, GG & GGG | Abbreviated | AD | * | | GGGG | Wide | Anno Domini | * | | GGGGG | Narrow | A | * | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | * | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | * | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | * | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | * | Week-numbering year | Y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 | * | | YY | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 | * | | YYY | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 | * | | YYYY | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 | * | Month | M | Numeric: 1 digit | 9, 12 | * | | MM | Numeric: 2 digits + zero padded | 09, 12 | * | | MMM | Abbreviated | Sep | * | | MMMM | Wide | September | * | | MMMMM | Narrow | S | * | Month standalone | L | Numeric: 1 digit | 9, 12 | * | | LL | Numeric: 2 digits + zero padded | 09, 12 | * | | LLL | Abbreviated | Sep | * | | LLLL | Wide | September | * | | LLLLL | Narrow | S | * | Week of year | w | Numeric: minimum digits | 1... 53 | * | | ww | Numeric: 2 digits + zero padded | 01... 53 | * | Week of month | W | Numeric: 1 digit | 1... 5 | * | Day of month | d | Numeric: minimum digits | 1 | * | | dd | Numeric: 2 digits + zero padded | 01 | * | Week day | E, EE & EEE | Abbreviated | Tue | * | | EEEE | Wide | Tuesday | * | | EEEEE | Narrow | T | * | | EEEEEE | Short | Tu | * | Week day standalone | c, cc | Numeric: 1 digit | 2 | * | | ccc | Abbreviated | Tue | * | | cccc | Wide | Tuesday | * | | ccccc | Narrow | T | * | | cccccc | Short | Tu | * | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM | * | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem | * | | aaaaa | Narrow | a/p | * | Period* | B, BB & BBB | Abbreviated | mid. | * | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | BBBBB | Narrow | md | * | Period standalone* | b, bb & bbb | Abbreviated | mid. | * | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night | * | | bbbbb | Narrow | md | * | Hour 1-12 | h | Numeric: minimum digits | 1, 12 | * | | hh | Numeric: 2 digits + zero padded | 01, 12 | * | Hour 0-23 | H | Numeric: minimum digits | 0, 23 | * | | HH | Numeric: 2 digits + zero padded | 00, 23 | * | Minute | m | Numeric: minimum digits | 8, 59 | * | | mm | Numeric: 2 digits + zero padded | 08, 59 | * | Second | s | Numeric: minimum digits | 0... 59 | * | | ss | Numeric: 2 digits + zero padded | 00... 59 | * | Fractional seconds | S | Numeric: 1 digit | 0... 9 | * | | SS | Numeric: 2 digits + zero padded | 00... 99 | * | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 | * | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 | * | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 | * | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 | * | | ZZZZ | Long localized GMT format | GMT-8:00 | * | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 | * | | O, OO & OOO | Short localized GMT format | GMT-8 | * | | OOOO | Long localized GMT format | GMT-08:00 | * * * ### Format examples * * These examples transform a date into various formats, * assuming that `dateObj` is a JavaScript `Date` object for * year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11, * given in the local time for the `en-US` locale. * * ``` * {{ dateObj | date }} // output is 'Jun 15, 2015' * {{ dateObj | date:'medium' }} // output is 'Jun 15, 2015, 9:43:11 PM' * {{ dateObj | date:'shortTime' }} // output is '9:43 PM' * {{ dateObj | date:'mm:ss' }} // output is '43:11' * ``` * * ### Usage example * * The following component uses a date pipe to display the current date in different formats. * * ``` * @Component({ * selector: 'date-pipe', * template: `
    *

    Today is {{today | date}}

    *

    Or if you prefer, {{today | date:'fullDate'}}

    *

    The time is {{today | date:'h:mm a z'}}

    *
    ` * }) * // Get the current date and time as a date-time value. * export class DatePipeComponent { * today: number = Date.now(); * } * ``` * * @publicApi */ // clang-format on var DatePipe = /** @class */ (function () { function DatePipe(locale) { this.locale = locale; } DatePipe.prototype.transform = function (value, format, timezone, locale) { if (format === void 0) { format = 'mediumDate'; } if (value == null || value === '' || value !== value) return null; try { return formatDate(value, format, locale || this.locale, timezone); } catch (error) { throw invalidPipeArgumentError(DatePipe, error.message); } }; return DatePipe; }()); DatePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'date', pure: true },] } ]; DatePipe.ctorParameters = function () { return [ { type: String, decorators: [{ type: i0.Inject, args: [i0.LOCALE_ID,] }] } ]; }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _INTERPOLATION_REGEXP = /#/g; /** * @ngModule CommonModule * @description * * Maps a value to a string that pluralizes the value according to locale rules. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} * * @publicApi */ var I18nPluralPipe = /** @class */ (function () { function I18nPluralPipe(_localization) { this._localization = _localization; } /** * @param value the number to be formatted * @param pluralMap an object that mimics the ICU format, see * http://userguide.icu-project.org/formatparse/messages. * @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by * default). */ I18nPluralPipe.prototype.transform = function (value, pluralMap, locale) { if (value == null) return ''; if (typeof pluralMap !== 'object' || pluralMap === null) { throw invalidPipeArgumentError(I18nPluralPipe, pluralMap); } var key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale); return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString()); }; return I18nPluralPipe; }()); I18nPluralPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'i18nPlural', pure: true },] } ]; I18nPluralPipe.ctorParameters = function () { return [ { type: NgLocalization } ]; }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Generic selector that displays the string that matches the current value. * * If none of the keys of the `mapping` match the `value`, then the content * of the `other` key is returned when present, otherwise an empty string is returned. * * @usageNotes * * ### Example * * {@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'} * * @publicApi */ var I18nSelectPipe = /** @class */ (function () { function I18nSelectPipe() { } /** * @param value a string to be internationalized. * @param mapping an object that indicates the text that should be displayed * for different values of the provided `value`. */ I18nSelectPipe.prototype.transform = function (value, mapping) { if (value == null) return ''; if (typeof mapping !== 'object' || typeof value !== 'string') { throw invalidPipeArgumentError(I18nSelectPipe, mapping); } if (mapping.hasOwnProperty(value)) { return mapping[value]; } if (mapping.hasOwnProperty('other')) { return mapping['other']; } return ''; }; return I18nSelectPipe; }()); I18nSelectPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'i18nSelect', pure: true },] } ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Converts a value into its JSON-format representation. Useful for debugging. * * @usageNotes * * The following component uses a JSON pipe to convert an object * to JSON format, and displays the string in both formats for comparison. * * {@example common/pipes/ts/json_pipe.ts region='JsonPipe'} * * @publicApi */ var JsonPipe = /** @class */ (function () { function JsonPipe() { } /** * @param value A value of any type to convert into a JSON-format string. */ JsonPipe.prototype.transform = function (value) { return JSON.stringify(value, null, 2); }; return JsonPipe; }()); JsonPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'json', pure: false },] } ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function makeKeyValuePair(key, value) { return { key: key, value: value }; } /** * @ngModule CommonModule * @description * * Transforms Object or Map into an array of key value pairs. * * The output array will be ordered by keys. * By default the comparator will be by Unicode point value. * You can optionally pass a compareFn if your keys are complex types. * * @usageNotes * ### Examples * * This examples show how an Object or a Map can be iterated by ngFor with the use of this * keyvalue pipe. * * {@example common/pipes/ts/keyvalue_pipe.ts region='KeyValuePipe'} * * @publicApi */ var KeyValuePipe = /** @class */ (function () { function KeyValuePipe(differs) { this.differs = differs; this.keyValues = []; this.compareFn = defaultComparator; } KeyValuePipe.prototype.transform = function (input, compareFn) { var _this = this; if (compareFn === void 0) { compareFn = defaultComparator; } if (!input || (!(input instanceof Map) && typeof input !== 'object')) { return null; } if (!this.differ) { // make a differ for whatever type we've been passed in this.differ = this.differs.find(input).create(); } var differChanges = this.differ.diff(input); var compareFnChanged = compareFn !== this.compareFn; if (differChanges) { this.keyValues = []; differChanges.forEachItem(function (r) { _this.keyValues.push(makeKeyValuePair(r.key, r.currentValue)); }); } if (differChanges || compareFnChanged) { this.keyValues.sort(compareFn); this.compareFn = compareFn; } return this.keyValues; }; return KeyValuePipe; }()); KeyValuePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'keyvalue', pure: false },] } ]; KeyValuePipe.ctorParameters = function () { return [ { type: i0.KeyValueDiffers } ]; }; function defaultComparator(keyValueA, keyValueB) { var a = keyValueA.key; var b = keyValueB.key; // if same exit with 0; if (a === b) return 0; // make sure that undefined are at the end of the sort. if (a === undefined) return 1; if (b === undefined) return -1; // make sure that nulls are at the end of the sort. if (a === null) return 1; if (b === null) return -1; if (typeof a == 'string' && typeof b == 'string') { return a < b ? -1 : 1; } if (typeof a == 'number' && typeof b == 'number') { return a - b; } if (typeof a == 'boolean' && typeof b == 'boolean') { return a < b ? -1 : 1; } // `a` and `b` are of different types. Compare their string values. var aString = String(a); var bString = String(b); return aString == bString ? 0 : aString < bString ? -1 : 1; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Formats a value according to digit options and locale rules. * Locale determines group sizing and separator, * decimal point character, and other locale-specific configurations. * * @see `formatNumber()` * * @usageNotes * * ### digitsInfo * * The value's decimal representation is specified by the `digitsInfo` * parameter, written in the following format:
    * * ``` * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits} * ``` * * - `minIntegerDigits`: * The minimum number of integer digits before the decimal point. * Default is 1. * * - `minFractionDigits`: * The minimum number of digits after the decimal point. * Default is 0. * * - `maxFractionDigits`: * The maximum number of digits after the decimal point. * Default is 3. * * If the formatted value is truncated it will be rounded using the "to-nearest" method: * * ``` * {{3.6 | number: '1.0-0'}} * * * {{-3.6 | number:'1.0-0'}} * * ``` * * ### locale * * `locale` will format a value according to locale rules. * Locale determines group sizing and separator, * decimal point character, and other locale-specific configurations. * * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). * * ### Example * * The following code shows how the pipe transforms values * according to various format specifications, * where the caller's default locale is `en-US`. * * * * @publicApi */ var DecimalPipe = /** @class */ (function () { function DecimalPipe(_locale) { this._locale = _locale; } /** * @param value The value to be formatted. * @param digitsInfo Sets digit and decimal representation. * [See more](#digitsinfo). * @param locale Specifies what locale format rules to use. * [See more](#locale). */ DecimalPipe.prototype.transform = function (value, digitsInfo, locale) { if (!isValue(value)) return null; locale = locale || this._locale; try { var num = strToNumber(value); return formatNumber(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(DecimalPipe, error.message); } }; return DecimalPipe; }()); DecimalPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'number' },] } ]; DecimalPipe.ctorParameters = function () { return [ { type: String, decorators: [{ type: i0.Inject, args: [i0.LOCALE_ID,] }] } ]; }; /** * @ngModule CommonModule * @description * * Transforms a number to a percentage * string, formatted according to locale rules that determine group sizing and * separator, decimal-point character, and other locale-specific * configurations. * * @see `formatPercent()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * * * @publicApi */ var PercentPipe = /** @class */ (function () { function PercentPipe(_locale) { this._locale = _locale; } /** * * @param value The number to be formatted as a percentage. * @param digitsInfo Decimal representation options, specified by a string * in the following format:
    * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `0`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `0`. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). */ PercentPipe.prototype.transform = function (value, digitsInfo, locale) { if (!isValue(value)) return null; locale = locale || this._locale; try { var num = strToNumber(value); return formatPercent(num, locale, digitsInfo); } catch (error) { throw invalidPipeArgumentError(PercentPipe, error.message); } }; return PercentPipe; }()); PercentPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'percent' },] } ]; PercentPipe.ctorParameters = function () { return [ { type: String, decorators: [{ type: i0.Inject, args: [i0.LOCALE_ID,] }] } ]; }; /** * @ngModule CommonModule * @description * * Transforms a number to a currency string, formatted according to locale rules * that determine group sizing and separator, decimal-point character, * and other locale-specific configurations. * * {@a currency-code-deprecation} *
    * * **Deprecation notice:** * * The default currency code is currently always `USD` but this is deprecated from v9. * * **In v11 the default currency code will be taken from the current locale identified by * the `LOCALE_ID` token. See the [i18n guide](guide/i18n#setting-up-the-locale-of-your-app) for * more information.** * * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in * your application `NgModule`: * * ```ts * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'} * ``` * *
    * * @see `getCurrencySymbol()` * @see `formatCurrency()` * * @usageNotes * The following code shows how the pipe transforms numbers * into text strings, according to various format specifications, * where the caller's default locale is `en-US`. * * * * @publicApi */ var CurrencyPipe = /** @class */ (function () { function CurrencyPipe(_locale, _defaultCurrencyCode) { if (_defaultCurrencyCode === void 0) { _defaultCurrencyCode = 'USD'; } this._locale = _locale; this._defaultCurrencyCode = _defaultCurrencyCode; } /** * * @param value The number to be formatted as currency. * @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, * such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be * configured using the `DEFAULT_CURRENCY_CODE` injection token. * @param display The format for the currency indicator. One of the following: * - `code`: Show the code (such as `USD`). * - `symbol`(default): Show the symbol (such as `$`). * - `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their * currency. * For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the * locale has no narrow symbol, uses the standard symbol for the locale. * - String: Use the given string value instead of a code or a symbol. * For example, an empty string will suppress the currency & symbol. * - Boolean (marked deprecated in v5): `true` for symbol and false for `code`. * * @param digitsInfo Decimal representation options, specified by a string * in the following format:
    * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}. * - `minIntegerDigits`: The minimum number of integer digits before the decimal point. * Default is `1`. * - `minFractionDigits`: The minimum number of digits after the decimal point. * Default is `2`. * - `maxFractionDigits`: The maximum number of digits after the decimal point. * Default is `2`. * If not provided, the number will be formatted with the proper amount of digits, * depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies. * For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none. * @param locale A locale code for the locale format rules to use. * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default. * See [Setting your app locale](guide/i18n#setting-up-the-locale-of-your-app). */ CurrencyPipe.prototype.transform = function (value, currencyCode, display, digitsInfo, locale) { if (currencyCode === void 0) { currencyCode = this._defaultCurrencyCode; } if (display === void 0) { display = 'symbol'; } if (!isValue(value)) return null; locale = locale || this._locale; if (typeof display === 'boolean') { if ((typeof ngDevMode === 'undefined' || ngDevMode) && console && console.warn) { console.warn("Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\"."); } display = display ? 'symbol' : 'code'; } var currency = currencyCode || this._defaultCurrencyCode; if (display !== 'code') { if (display === 'symbol' || display === 'symbol-narrow') { currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale); } else { currency = display; } } try { var num = strToNumber(value); return formatCurrency(num, locale, currency, currencyCode, digitsInfo); } catch (error) { throw invalidPipeArgumentError(CurrencyPipe, error.message); } }; return CurrencyPipe; }()); CurrencyPipe.decorators = [ { type: i0.Pipe, args: [{ name: 'currency' },] } ]; CurrencyPipe.ctorParameters = function () { return [ { type: String, decorators: [{ type: i0.Inject, args: [i0.LOCALE_ID,] }] }, { type: String, decorators: [{ type: i0.Inject, args: [i0.DEFAULT_CURRENCY_CODE,] }] } ]; }; function isValue(value) { return !(value == null || value === '' || value !== value); } /** * Transforms a string into a number (if needed). */ function strToNumber(value) { // Convert strings to numbers if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) { return Number(value); } if (typeof value !== 'number') { throw new Error(value + " is not a number"); } return value; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @ngModule CommonModule * @description * * Creates a new `Array` or `String` containing a subset (slice) of the elements. * * @usageNotes * * All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()` * and `String.prototype.slice()`. * * When operating on an `Array`, the returned `Array` is always a copy even when all * the elements are being returned. * * When operating on a blank value, the pipe returns the blank value. * * ### List Example * * This `ngFor` example: * * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'} * * produces the following: * * ```html *
  • b
  • *
  • c
  • * ``` * * ### String Examples * * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_string'} * * @publicApi */ var SlicePipe = /** @class */ (function () { function SlicePipe() { } SlicePipe.prototype.transform = function (value, start, end) { if (value == null) return null; if (!this.supports(value)) { throw invalidPipeArgumentError(SlicePipe, value); } return value.slice(start, end); }; SlicePipe.prototype.supports = function (obj) { return typeof obj === 'string' || Array.isArray(obj); }; return SlicePipe; }()); SlicePipe.decorators = [ { type: i0.Pipe, args: [{ name: 'slice', pure: false },] } ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A collection of Angular pipes that are likely to be used in each and every application. */ var COMMON_PIPES = [ AsyncPipe, UpperCasePipe, LowerCasePipe, JsonPipe, SlicePipe, DecimalPipe, PercentPipe, TitleCasePipe, CurrencyPipe, DatePipe, I18nPluralPipe, I18nSelectPipe, KeyValuePipe, ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Note: This does not contain the location providers, // as they need some platform specific implementations to work. /** * Exports all the basic Angular directives and pipes, * such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on. * Re-exported by `BrowserModule`, which is included automatically in the root * `AppModule` when you create a new app with the CLI `new` command. * * * The `providers` options configure the NgModule's injector to provide * localization dependencies to members. * * The `exports` options make the declared directives and pipes available for import * by other NgModules. * * @publicApi */ var CommonModule = /** @class */ (function () { function CommonModule() { } return CommonModule; }()); CommonModule.decorators = [ { type: i0.NgModule, args: [{ declarations: [COMMON_DIRECTIVES, COMMON_PIPES], exports: [COMMON_DIRECTIVES, COMMON_PIPES], providers: [ { provide: NgLocalization, useClass: NgLocaleLocalization }, ], },] } ]; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var PLATFORM_BROWSER_ID = 'browser'; var PLATFORM_SERVER_ID = 'server'; var PLATFORM_WORKER_APP_ID = 'browserWorkerApp'; var PLATFORM_WORKER_UI_ID = 'browserWorkerUi'; /** * Returns whether a platform id represents a browser platform. * @publicApi */ function isPlatformBrowser(platformId) { return platformId === PLATFORM_BROWSER_ID; } /** * Returns whether a platform id represents a server platform. * @publicApi */ function isPlatformServer(platformId) { return platformId === PLATFORM_SERVER_ID; } /** * Returns whether a platform id represents a web worker app platform. * @publicApi */ function isPlatformWorkerApp(platformId) { return platformId === PLATFORM_WORKER_APP_ID; } /** * Returns whether a platform id represents a web worker UI platform. * @publicApi */ function isPlatformWorkerUi(platformId) { return platformId === PLATFORM_WORKER_UI_ID; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @publicApi */ var VERSION = new i0.Version('12.2.1'); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Defines a scroll position manager. Implemented by `BrowserViewportScroller`. * * @publicApi */ var ViewportScroller = /** @class */ (function () { function ViewportScroller() { } return ViewportScroller; }()); // De-sugared tree-shakable injection // See #23917 /** @nocollapse */ ViewportScroller.ɵprov = i0.ɵɵdefineInjectable({ token: ViewportScroller, providedIn: 'root', factory: function () { return new BrowserViewportScroller(i0.ɵɵinject(DOCUMENT), window); } }); /** * Manages the scroll position for a browser window. */ var BrowserViewportScroller = /** @class */ (function () { function BrowserViewportScroller(document, window) { this.document = document; this.window = window; this.offset = function () { return [0, 0]; }; } /** * Configures the top offset used when scrolling to an anchor. * @param offset A position in screen coordinates (a tuple with x and y values) * or a function that returns the top offset position. * */ BrowserViewportScroller.prototype.setOffset = function (offset) { if (Array.isArray(offset)) { this.offset = function () { return offset; }; } else { this.offset = offset; } }; /** * Retrieves the current scroll position. * @returns The position in screen coordinates. */ BrowserViewportScroller.prototype.getScrollPosition = function () { if (this.supportsScrolling()) { return [this.window.pageXOffset, this.window.pageYOffset]; } else { return [0, 0]; } }; /** * Sets the scroll position. * @param position The new position in screen coordinates. */ BrowserViewportScroller.prototype.scrollToPosition = function (position) { if (this.supportsScrolling()) { this.window.scrollTo(position[0], position[1]); } }; /** * Scrolls to an element and attempts to focus the element. * * Note that the function name here is misleading in that the target string may be an ID for a * non-anchor element. * * @param target The ID of an element or name of the anchor. * * @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document * @see https://html.spec.whatwg.org/#scroll-to-fragid */ BrowserViewportScroller.prototype.scrollToAnchor = function (target) { if (!this.supportsScrolling()) { return; } // TODO(atscott): The correct behavior for `getElementsByName` would be to also verify that the // element is an anchor. However, this could be considered a breaking change and should be // done in a major version. var elSelected = findAnchorFromDocument(this.document, target); if (elSelected) { this.scrollToElement(elSelected); // After scrolling to the element, the spec dictates that we follow the focus steps for the // target. Rather than following the robust steps, simply attempt focus. this.attemptFocus(elSelected); } }; /** * Disables automatic scroll restoration provided by the browser. */ BrowserViewportScroller.prototype.setHistoryScrollRestoration = function (scrollRestoration) { if (this.supportScrollRestoration()) { var history = this.window.history; if (history && history.scrollRestoration) { history.scrollRestoration = scrollRestoration; } } }; /** * Scrolls to an element using the native offset and the specified offset set on this scroller. * * The offset can be used when we know that there is a floating header and scrolling naively to an * element (ex: `scrollIntoView`) leaves the element hidden behind the floating header. */ BrowserViewportScroller.prototype.scrollToElement = function (el) { var rect = el.getBoundingClientRect(); var left = rect.left + this.window.pageXOffset; var top = rect.top + this.window.pageYOffset; var offset = this.offset(); this.window.scrollTo(left - offset[0], top - offset[1]); }; /** * Calls `focus` on the `focusTarget` and returns `true` if the element was focused successfully. * * If `false`, further steps may be necessary to determine a valid substitute to be focused * instead. * * @see https://html.spec.whatwg.org/#get-the-focusable-area * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus * @see https://html.spec.whatwg.org/#focusable-area */ BrowserViewportScroller.prototype.attemptFocus = function (focusTarget) { focusTarget.focus(); return this.document.activeElement === focusTarget; }; /** * We only support scroll restoration when we can get a hold of window. * This means that we do not support this behavior when running in a web worker. * * Lifting this restriction right now would require more changes in the dom adapter. * Since webworkers aren't widely used, we will lift it once RouterScroller is * battle-tested. */ BrowserViewportScroller.prototype.supportScrollRestoration = function () { try { if (!this.supportsScrolling()) { return false; } // The `scrollRestoration` property could be on the `history` instance or its prototype. var scrollRestorationDescriptor = getScrollRestorationProperty(this.window.history) || getScrollRestorationProperty(Object.getPrototypeOf(this.window.history)); // We can write to the `scrollRestoration` property if it is a writable data field or it has a // setter function. return !!scrollRestorationDescriptor && !!(scrollRestorationDescriptor.writable || scrollRestorationDescriptor.set); } catch (_a) { return false; } }; BrowserViewportScroller.prototype.supportsScrolling = function () { try { return !!this.window && !!this.window.scrollTo && 'pageXOffset' in this.window; } catch (_a) { return false; } }; return BrowserViewportScroller; }()); function getScrollRestorationProperty(obj) { return Object.getOwnPropertyDescriptor(obj, 'scrollRestoration'); } function findAnchorFromDocument(document, target) { var documentResult = document.getElementById(target) || document.getElementsByName(target)[0]; if (documentResult) { return documentResult; } // `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we // have to traverse the DOM manually and do the lookup through the shadow roots. if (typeof document.createTreeWalker === 'function' && document.body && (document.body.createShadowRoot || document.body.attachShadow)) { var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT); var currentNode = treeWalker.currentNode; while (currentNode) { var shadowRoot = currentNode.shadowRoot; if (shadowRoot) { // Note that `ShadowRoot` doesn't support `getElementsByName` // so we have to fall back to `querySelector`. var result = shadowRoot.getElementById(target) || shadowRoot.querySelector("[name=\"" + target + "\"]"); if (result) { return result; } } currentNode = treeWalker.nextNode(); } } return null; } /** * Provides an empty implementation of the viewport scroller. */ var NullViewportScroller = /** @class */ (function () { function NullViewportScroller() { } /** * Empty implementation */ NullViewportScroller.prototype.setOffset = function (offset) { }; /** * Empty implementation */ NullViewportScroller.prototype.getScrollPosition = function () { return [0, 0]; }; /** * Empty implementation */ NullViewportScroller.prototype.scrollToPosition = function (position) { }; /** * Empty implementation */ NullViewportScroller.prototype.scrollToAnchor = function (anchor) { }; /** * Empty implementation */ NullViewportScroller.prototype.setHistoryScrollRestoration = function (scrollRestoration) { }; return NullViewportScroller; }()); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A wrapper around the `XMLHttpRequest` constructor. * * @publicApi */ var XhrFactory = /** @class */ (function () { function XhrFactory() { } return XhrFactory; }()); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // This file only reexports content of the `src` folder. Keep it that way. /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Generated bundle index. Do not edit. */ exports.APP_BASE_HREF = APP_BASE_HREF; exports.AsyncPipe = AsyncPipe; exports.CommonModule = CommonModule; exports.CurrencyPipe = CurrencyPipe; exports.DOCUMENT = DOCUMENT; exports.DatePipe = DatePipe; exports.DecimalPipe = DecimalPipe; exports.HashLocationStrategy = HashLocationStrategy; exports.I18nPluralPipe = I18nPluralPipe; exports.I18nSelectPipe = I18nSelectPipe; exports.JsonPipe = JsonPipe; exports.KeyValuePipe = KeyValuePipe; exports.LOCATION_INITIALIZED = LOCATION_INITIALIZED; exports.Location = Location; exports.LocationStrategy = LocationStrategy; exports.LowerCasePipe = LowerCasePipe; exports.NgClass = NgClass; exports.NgComponentOutlet = NgComponentOutlet; exports.NgForOf = NgForOf; exports.NgForOfContext = NgForOfContext; exports.NgIf = NgIf; exports.NgIfContext = NgIfContext; exports.NgLocaleLocalization = NgLocaleLocalization; exports.NgLocalization = NgLocalization; exports.NgPlural = NgPlural; exports.NgPluralCase = NgPluralCase; exports.NgStyle = NgStyle; exports.NgSwitch = NgSwitch; exports.NgSwitchCase = NgSwitchCase; exports.NgSwitchDefault = NgSwitchDefault; exports.NgTemplateOutlet = NgTemplateOutlet; exports.PathLocationStrategy = PathLocationStrategy; exports.PercentPipe = PercentPipe; exports.PlatformLocation = PlatformLocation; exports.SlicePipe = SlicePipe; exports.TitleCasePipe = TitleCasePipe; exports.UpperCasePipe = UpperCasePipe; exports.VERSION = VERSION; exports.ViewportScroller = ViewportScroller; exports.XhrFactory = XhrFactory; exports.formatCurrency = formatCurrency; exports.formatDate = formatDate; exports.formatNumber = formatNumber; exports.formatPercent = formatPercent; exports.getCurrencySymbol = getCurrencySymbol; exports.getLocaleCurrencyCode = getLocaleCurrencyCode; exports.getLocaleCurrencyName = getLocaleCurrencyName; exports.getLocaleCurrencySymbol = getLocaleCurrencySymbol; exports.getLocaleDateFormat = getLocaleDateFormat; exports.getLocaleDateTimeFormat = getLocaleDateTimeFormat; exports.getLocaleDayNames = getLocaleDayNames; exports.getLocaleDayPeriods = getLocaleDayPeriods; exports.getLocaleDirection = getLocaleDirection; exports.getLocaleEraNames = getLocaleEraNames; exports.getLocaleExtraDayPeriodRules = getLocaleExtraDayPeriodRules; exports.getLocaleExtraDayPeriods = getLocaleExtraDayPeriods; exports.getLocaleFirstDayOfWeek = getLocaleFirstDayOfWeek; exports.getLocaleId = getLocaleId; exports.getLocaleMonthNames = getLocaleMonthNames; exports.getLocaleNumberFormat = getLocaleNumberFormat; exports.getLocaleNumberSymbol = getLocaleNumberSymbol; exports.getLocalePluralCase = getLocalePluralCase; exports.getLocaleTimeFormat = getLocaleTimeFormat; exports.getLocaleWeekEndRange = getLocaleWeekEndRange; exports.getNumberOfCurrencyDigits = getNumberOfCurrencyDigits; exports.isPlatformBrowser = isPlatformBrowser; exports.isPlatformServer = isPlatformServer; exports.isPlatformWorkerApp = isPlatformWorkerApp; exports.isPlatformWorkerUi = isPlatformWorkerUi; exports.registerLocaleData = registerLocaleData; exports.ɵBrowserPlatformLocation = BrowserPlatformLocation; exports.ɵDomAdapter = DomAdapter; exports.ɵNullViewportScroller = NullViewportScroller; exports.ɵPLATFORM_BROWSER_ID = PLATFORM_BROWSER_ID; exports.ɵPLATFORM_SERVER_ID = PLATFORM_SERVER_ID; exports.ɵPLATFORM_WORKER_APP_ID = PLATFORM_WORKER_APP_ID; exports.ɵPLATFORM_WORKER_UI_ID = PLATFORM_WORKER_UI_ID; exports.ɵangular_packages_common_common_a = useBrowserPlatformLocation; exports.ɵangular_packages_common_common_b = createBrowserPlatformLocation; exports.ɵangular_packages_common_common_c = createLocation; exports.ɵangular_packages_common_common_d = provideLocationStrategy; exports.ɵangular_packages_common_common_e = COMMON_DIRECTIVES; exports.ɵangular_packages_common_common_f = COMMON_PIPES; exports.ɵgetDOM = getDOM; exports.ɵparseCookieValue = parseCookieValue; exports.ɵsetRootDomAdapter = setRootDomAdapter; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=common.umd.js.map ================================================ FILE: test/lib/angular-12/angular-12-compiler.js ================================================ /** * @license Angular v12.2.1 * (c) 2010-2021 Google LLC. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define('@angular/compiler', ['exports'], factory) : (global = global || self, factory((global.ng = global.ng || {}, global.ng.compiler = {}))); }(this, (function (exports) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || from); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ (function (TagContentType) { TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT"; TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT"; TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA"; })(exports.TagContentType || (exports.TagContentType = {})); function splitNsName(elementName) { if (elementName[0] != ':') { return [null, elementName]; } var colonIndex = elementName.indexOf(':', 1); if (colonIndex == -1) { throw new Error("Unsupported format \"" + elementName + "\" expecting \":namespace:name\""); } return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)]; } // `` tags work the same regardless the namespace function isNgContainer(tagName) { return splitNsName(tagName)[1] === 'ng-container'; } // `` tags work the same regardless the namespace function isNgContent(tagName) { return splitNsName(tagName)[1] === 'ng-content'; } // `` tags work the same regardless the namespace function isNgTemplate(tagName) { return splitNsName(tagName)[1] === 'ng-template'; } function getNsPrefix(fullName) { return fullName === null ? null : splitNsName(fullName)[0]; } function mergeNsAndName(prefix, localName) { return prefix ? ":" + prefix + ":" + localName : localName; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var HtmlTagDefinition = /** @class */ (function () { function HtmlTagDefinition(_c) { var _this = this; var _d = _c === void 0 ? {} : _c, closedByChildren = _d.closedByChildren, implicitNamespacePrefix = _d.implicitNamespacePrefix, _e = _d.contentType, contentType = _e === void 0 ? exports.TagContentType.PARSABLE_DATA : _e, _f = _d.closedByParent, closedByParent = _f === void 0 ? false : _f, _g = _d.isVoid, isVoid = _g === void 0 ? false : _g, _h = _d.ignoreFirstLf, ignoreFirstLf = _h === void 0 ? false : _h, _j = _d.preventNamespaceInheritance, preventNamespaceInheritance = _j === void 0 ? false : _j; this.closedByChildren = {}; this.closedByParent = false; this.canSelfClose = false; if (closedByChildren && closedByChildren.length > 0) { closedByChildren.forEach(function (tagName) { return _this.closedByChildren[tagName] = true; }); } this.isVoid = isVoid; this.closedByParent = closedByParent || isVoid; this.implicitNamespacePrefix = implicitNamespacePrefix || null; this.contentType = contentType; this.ignoreFirstLf = ignoreFirstLf; this.preventNamespaceInheritance = preventNamespaceInheritance; } HtmlTagDefinition.prototype.isClosedByChild = function (name) { return this.isVoid || name.toLowerCase() in this.closedByChildren; }; HtmlTagDefinition.prototype.getContentType = function (prefix) { if (typeof this.contentType === 'object') { var overrideType = prefix == null ? undefined : this.contentType[prefix]; return overrideType !== null && overrideType !== void 0 ? overrideType : this.contentType.default; } return this.contentType; }; return HtmlTagDefinition; }()); var _DEFAULT_TAG_DEFINITION; // see https://www.w3.org/TR/html51/syntax.html#optional-tags // This implementation does not fully conform to the HTML5 spec. var TAG_DEFINITIONS; function getHtmlTagDefinition(tagName) { var _a, _b; if (!TAG_DEFINITIONS) { _DEFAULT_TAG_DEFINITION = new HtmlTagDefinition(); TAG_DEFINITIONS = { 'base': new HtmlTagDefinition({ isVoid: true }), 'meta': new HtmlTagDefinition({ isVoid: true }), 'area': new HtmlTagDefinition({ isVoid: true }), 'embed': new HtmlTagDefinition({ isVoid: true }), 'link': new HtmlTagDefinition({ isVoid: true }), 'img': new HtmlTagDefinition({ isVoid: true }), 'input': new HtmlTagDefinition({ isVoid: true }), 'param': new HtmlTagDefinition({ isVoid: true }), 'hr': new HtmlTagDefinition({ isVoid: true }), 'br': new HtmlTagDefinition({ isVoid: true }), 'source': new HtmlTagDefinition({ isVoid: true }), 'track': new HtmlTagDefinition({ isVoid: true }), 'wbr': new HtmlTagDefinition({ isVoid: true }), 'p': new HtmlTagDefinition({ closedByChildren: [ 'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul' ], closedByParent: true }), 'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }), 'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }), 'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }), 'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }), 'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), 'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }), 'col': new HtmlTagDefinition({ isVoid: true }), 'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }), 'foreignObject': new HtmlTagDefinition({ // Usually the implicit namespace here would be redundant since it will be inherited from // the parent `svg`, but we have to do it for `foreignObject`, because the way the parser // works is that the parent node of an end tag is its own start tag which means that // the `preventNamespaceInheritance` on `foreignObject` would have it default to the // implicit namespace which is `html`, unless specified otherwise. implicitNamespacePrefix: 'svg', // We want to prevent children of foreignObject from inheriting its namespace, because // the point of the element is to allow nodes from other namespaces to be inserted. preventNamespaceInheritance: true, }), 'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }), 'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }), 'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }), 'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }), 'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), 'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), 'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }), 'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }), 'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }), 'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }), 'pre': new HtmlTagDefinition({ ignoreFirstLf: true }), 'listing': new HtmlTagDefinition({ ignoreFirstLf: true }), 'style': new HtmlTagDefinition({ contentType: exports.TagContentType.RAW_TEXT }), 'script': new HtmlTagDefinition({ contentType: exports.TagContentType.RAW_TEXT }), 'title': new HtmlTagDefinition({ // The browser supports two separate `title` tags which have to use // a different content type: `HTMLTitleElement` and `SVGTitleElement` contentType: { default: exports.TagContentType.ESCAPABLE_RAW_TEXT, svg: exports.TagContentType.PARSABLE_DATA } }), 'textarea': new HtmlTagDefinition({ contentType: exports.TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }), }; } // We have to make both a case-sensitive and a case-insesitive lookup, because // HTML tag names are case insensitive, whereas some SVG tags are case sensitive. return (_b = (_a = TAG_DEFINITIONS[tagName]) !== null && _a !== void 0 ? _a : TAG_DEFINITIONS[tagName.toLowerCase()]) !== null && _b !== void 0 ? _b : _DEFAULT_TAG_DEFINITION; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + // 1: ":not(" '(([\\.\\#]?)[-\\w]+)|' + // 2: "tag"; 3: "."/"#"; // "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range // 4: attribute; 5: attribute_string; 6: attribute_value '(?:\\[([-.\\w*\\\\$]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]", // "[name="value"]", // "[name='value']" '(\\))|' + // 7: ")" '(\\s*,\\s*)', // 8: "," 'g'); /** * A css selector contains an element name, * css classes and attribute/value pairs with the purpose * of selecting subsets out of them. */ var CssSelector = /** @class */ (function () { function CssSelector() { this.element = null; this.classNames = []; /** * The selectors are encoded in pairs where: * - even locations are attribute names * - odd locations are attribute values. * * Example: * Selector: `[key1=value1][key2]` would parse to: * ``` * ['key1', 'value1', 'key2', ''] * ``` */ this.attrs = []; this.notSelectors = []; } CssSelector.parse = function (selector) { var results = []; var _addResult = function (res, cssSel) { if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 && cssSel.attrs.length == 0) { cssSel.element = '*'; } res.push(cssSel); }; var cssSelector = new CssSelector(); var match; var current = cssSelector; var inNot = false; _SELECTOR_REGEXP.lastIndex = 0; while (match = _SELECTOR_REGEXP.exec(selector)) { if (match[1 /* NOT */]) { if (inNot) { throw new Error('Nesting :not in a selector is not allowed'); } inNot = true; current = new CssSelector(); cssSelector.notSelectors.push(current); } var tag = match[2 /* TAG */]; if (tag) { var prefix = match[3 /* PREFIX */]; if (prefix === '#') { // #hash current.addAttribute('id', tag.substr(1)); } else if (prefix === '.') { // Class current.addClassName(tag.substr(1)); } else { // Element current.setElement(tag); } } var attribute = match[4 /* ATTRIBUTE */]; if (attribute) { current.addAttribute(current.unescapeAttribute(attribute), match[6 /* ATTRIBUTE_VALUE */]); } if (match[7 /* NOT_END */]) { inNot = false; current = cssSelector; } if (match[8 /* SEPARATOR */]) { if (inNot) { throw new Error('Multiple selectors in :not are not supported'); } _addResult(results, cssSelector); cssSelector = current = new CssSelector(); } } _addResult(results, cssSelector); return results; }; /** * Unescape `\$` sequences from the CSS attribute selector. * * This is needed because `$` can have a special meaning in CSS selectors, * but we might want to match an attribute that contains `$`. * [MDN web link for more * info](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors). * @param attr the attribute to unescape. * @returns the unescaped string. */ CssSelector.prototype.unescapeAttribute = function (attr) { var result = ''; var escaping = false; for (var i = 0; i < attr.length; i++) { var char = attr.charAt(i); if (char === '\\') { escaping = true; continue; } if (char === '$' && !escaping) { throw new Error("Error in attribute selector \"" + attr + "\". " + "Unescaped \"$\" is not supported. Please escape with \"\\$\"."); } escaping = false; result += char; } return result; }; /** * Escape `$` sequences from the CSS attribute selector. * * This is needed because `$` can have a special meaning in CSS selectors, * with this method we are escaping `$` with `\$'. * [MDN web link for more * info](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors). * @param attr the attribute to escape. * @returns the escaped string. */ CssSelector.prototype.escapeAttribute = function (attr) { return attr.replace(/\\/g, '\\\\').replace(/\$/g, '\\$'); }; CssSelector.prototype.isElementSelector = function () { return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 && this.notSelectors.length === 0; }; CssSelector.prototype.hasElementSelector = function () { return !!this.element; }; CssSelector.prototype.setElement = function (element) { if (element === void 0) { element = null; } this.element = element; }; /** Gets a template string for an element that matches the selector. */ CssSelector.prototype.getMatchingElementTemplate = function () { var tagName = this.element || 'div'; var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : ''; var attrs = ''; for (var i = 0; i < this.attrs.length; i += 2) { var attrName = this.attrs[i]; var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : ''; attrs += " " + attrName + attrValue; } return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" : "<" + tagName + classAttr + attrs + ">"; }; CssSelector.prototype.getAttrs = function () { var result = []; if (this.classNames.length > 0) { result.push('class', this.classNames.join(' ')); } return result.concat(this.attrs); }; CssSelector.prototype.addAttribute = function (name, value) { if (value === void 0) { value = ''; } this.attrs.push(name, value && value.toLowerCase() || ''); }; CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); }; CssSelector.prototype.toString = function () { var res = this.element || ''; if (this.classNames) { this.classNames.forEach(function (klass) { return res += "." + klass; }); } if (this.attrs) { for (var i = 0; i < this.attrs.length; i += 2) { var name = this.escapeAttribute(this.attrs[i]); var value = this.attrs[i + 1]; res += "[" + name + (value ? '=' + value : '') + "]"; } } this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; }); return res; }; return CssSelector; }()); /** * Reads a list of CssSelectors and allows to calculate which ones * are contained in a given CssSelector. */ var SelectorMatcher = /** @class */ (function () { function SelectorMatcher() { this._elementMap = new Map(); this._elementPartialMap = new Map(); this._classMap = new Map(); this._classPartialMap = new Map(); this._attrValueMap = new Map(); this._attrValuePartialMap = new Map(); this._listContexts = []; } SelectorMatcher.createNotMatcher = function (notSelectors) { var notMatcher = new SelectorMatcher(); notMatcher.addSelectables(notSelectors, null); return notMatcher; }; SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) { var listContext = null; if (cssSelectors.length > 1) { listContext = new SelectorListContext(cssSelectors); this._listContexts.push(listContext); } for (var i = 0; i < cssSelectors.length; i++) { this._addSelectable(cssSelectors[i], callbackCtxt, listContext); } }; /** * Add an object that can be found later on by calling `match`. * @param cssSelector A css selector * @param callbackCtxt An opaque object that will be given to the callback of the `match` function */ SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) { var matcher = this; var element = cssSelector.element; var classNames = cssSelector.classNames; var attrs = cssSelector.attrs; var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext); if (element) { var isTerminal = attrs.length === 0 && classNames.length === 0; if (isTerminal) { this._addTerminal(matcher._elementMap, element, selectable); } else { matcher = this._addPartial(matcher._elementPartialMap, element); } } if (classNames) { for (var i = 0; i < classNames.length; i++) { var isTerminal = attrs.length === 0 && i === classNames.length - 1; var className = classNames[i]; if (isTerminal) { this._addTerminal(matcher._classMap, className, selectable); } else { matcher = this._addPartial(matcher._classPartialMap, className); } } } if (attrs) { for (var i = 0; i < attrs.length; i += 2) { var isTerminal = i === attrs.length - 2; var name = attrs[i]; var value = attrs[i + 1]; if (isTerminal) { var terminalMap = matcher._attrValueMap; var terminalValuesMap = terminalMap.get(name); if (!terminalValuesMap) { terminalValuesMap = new Map(); terminalMap.set(name, terminalValuesMap); } this._addTerminal(terminalValuesMap, value, selectable); } else { var partialMap = matcher._attrValuePartialMap; var partialValuesMap = partialMap.get(name); if (!partialValuesMap) { partialValuesMap = new Map(); partialMap.set(name, partialValuesMap); } matcher = this._addPartial(partialValuesMap, value); } } } }; SelectorMatcher.prototype._addTerminal = function (map, name, selectable) { var terminalList = map.get(name); if (!terminalList) { terminalList = []; map.set(name, terminalList); } terminalList.push(selectable); }; SelectorMatcher.prototype._addPartial = function (map, name) { var matcher = map.get(name); if (!matcher) { matcher = new SelectorMatcher(); map.set(name, matcher); } return matcher; }; /** * Find the objects that have been added via `addSelectable` * whose css selector is contained in the given css selector. * @param cssSelector A css selector * @param matchedCallback This callback will be called with the object handed into `addSelectable` * @return boolean true if a match was found */ SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) { var result = false; var element = cssSelector.element; var classNames = cssSelector.classNames; var attrs = cssSelector.attrs; for (var i = 0; i < this._listContexts.length; i++) { this._listContexts[i].alreadyMatched = false; } result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result; result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) || result; if (classNames) { for (var i = 0; i < classNames.length; i++) { var className = classNames[i]; result = this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result; result = this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) || result; } } if (attrs) { for (var i = 0; i < attrs.length; i += 2) { var name = attrs[i]; var value = attrs[i + 1]; var terminalValuesMap = this._attrValueMap.get(name); if (value) { result = this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result; } result = this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result; var partialValuesMap = this._attrValuePartialMap.get(name); if (value) { result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result; } result = this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result; } } return result; }; /** @internal */ SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) { if (!map || typeof name !== 'string') { return false; } var selectables = map.get(name) || []; var starSelectables = map.get('*'); if (starSelectables) { selectables = selectables.concat(starSelectables); } if (selectables.length === 0) { return false; } var selectable; var result = false; for (var i = 0; i < selectables.length; i++) { selectable = selectables[i]; result = selectable.finalize(cssSelector, matchedCallback) || result; } return result; }; /** @internal */ SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) { if (!map || typeof name !== 'string') { return false; } var nestedSelector = map.get(name); if (!nestedSelector) { return false; } // TODO(perf): get rid of recursion and measure again // TODO(perf): don't pass the whole selector into the recursion, // but only the not processed parts return nestedSelector.match(cssSelector, matchedCallback); }; return SelectorMatcher; }()); var SelectorListContext = /** @class */ (function () { function SelectorListContext(selectors) { this.selectors = selectors; this.alreadyMatched = false; } return SelectorListContext; }()); // Store context to pass back selector and context when a selector is matched var SelectorContext = /** @class */ (function () { function SelectorContext(selector, cbContext, listContext) { this.selector = selector; this.cbContext = cbContext; this.listContext = listContext; this.notSelectors = selector.notSelectors; } SelectorContext.prototype.finalize = function (cssSelector, callback) { var result = true; if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) { var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors); result = !notMatcher.match(cssSelector, null); } if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) { if (this.listContext) { this.listContext.alreadyMatched = true; } callback(this.selector, this.cbContext); } return result; }; return SelectorContext; }()); var createInject = makeMetadataFactory('Inject', function (token) { return ({ token: token }); }); var createInjectionToken = makeMetadataFactory('InjectionToken', function (desc) { return ({ _desc: desc, ɵprov: undefined }); }); var createAttribute = makeMetadataFactory('Attribute', function (attributeName) { return ({ attributeName: attributeName }); }); // Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not // explicitly set. var emitDistinctChangesOnlyDefaultValue = true; var createContentChildren = makeMetadataFactory('ContentChildren', function (selector, data) { if (data === void 0) { data = {}; } return (Object.assign({ selector: selector, first: false, isViewQuery: false, descendants: false, emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue }, data)); }); var createContentChild = makeMetadataFactory('ContentChild', function (selector, data) { if (data === void 0) { data = {}; } return (Object.assign({ selector: selector, first: true, isViewQuery: false, descendants: true }, data)); }); var createViewChildren = makeMetadataFactory('ViewChildren', function (selector, data) { if (data === void 0) { data = {}; } return (Object.assign({ selector: selector, first: false, isViewQuery: true, descendants: true, emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue }, data)); }); var createViewChild = makeMetadataFactory('ViewChild', function (selector, data) { return (Object.assign({ selector: selector, first: true, isViewQuery: true, descendants: true }, data)); }); var createDirective = makeMetadataFactory('Directive', function (dir) { if (dir === void 0) { dir = {}; } return dir; }); var ViewEncapsulation; (function (ViewEncapsulation) { ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated"; // Historically the 1 value was for `Native` encapsulation which has been removed as of v11. ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None"; ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom"; })(ViewEncapsulation || (ViewEncapsulation = {})); var ChangeDetectionStrategy; (function (ChangeDetectionStrategy) { ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush"; ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default"; })(ChangeDetectionStrategy || (ChangeDetectionStrategy = {})); var createComponent = makeMetadataFactory('Component', function (c) { if (c === void 0) { c = {}; } return (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c)); }); var createPipe = makeMetadataFactory('Pipe', function (p) { return (Object.assign({ pure: true }, p)); }); var createInput = makeMetadataFactory('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); }); var createOutput = makeMetadataFactory('Output', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); }); var createHostBinding = makeMetadataFactory('HostBinding', function (hostPropertyName) { return ({ hostPropertyName: hostPropertyName }); }); var createHostListener = makeMetadataFactory('HostListener', function (eventName, args) { return ({ eventName: eventName, args: args }); }); var createNgModule = makeMetadataFactory('NgModule', function (ngModule) { return ngModule; }); var createInjectable = makeMetadataFactory('Injectable', function (injectable) { if (injectable === void 0) { injectable = {}; } return injectable; }); var CUSTOM_ELEMENTS_SCHEMA = { name: 'custom-elements' }; var NO_ERRORS_SCHEMA = { name: 'no-errors-schema' }; var createOptional = makeMetadataFactory('Optional'); var createSelf = makeMetadataFactory('Self'); var createSkipSelf = makeMetadataFactory('SkipSelf'); var createHost = makeMetadataFactory('Host'); var Type = Function; var SecurityContext; (function (SecurityContext) { SecurityContext[SecurityContext["NONE"] = 0] = "NONE"; SecurityContext[SecurityContext["HTML"] = 1] = "HTML"; SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE"; SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT"; SecurityContext[SecurityContext["URL"] = 4] = "URL"; SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL"; })(SecurityContext || (SecurityContext = {})); var MissingTranslationStrategy; (function (MissingTranslationStrategy) { MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error"; MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning"; MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore"; })(MissingTranslationStrategy || (MissingTranslationStrategy = {})); function makeMetadataFactory(name, props) { // This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code // that works with the static_reflector.ts in the ViewEngine compiler. // In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be // new'ed. function factory() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var values = props ? props.apply(void 0, __spreadArray([], __read(args))) : {}; return Object.assign({ ngMetadataName: name }, values); } factory.isTypeOf = function (obj) { return obj && obj.ngMetadataName === name; }; factory.ngMetadataName = name; return factory; } function parserSelectorToSimpleSelector(selector) { var classes = selector.classNames && selector.classNames.length ? __spreadArray([8 /* CLASS */], __read(selector.classNames)) : []; var elementName = selector.element && selector.element !== '*' ? selector.element : ''; return __spreadArray(__spreadArray([elementName], __read(selector.attrs)), __read(classes)); } function parserSelectorToNegativeSelector(selector) { var classes = selector.classNames && selector.classNames.length ? __spreadArray([8 /* CLASS */], __read(selector.classNames)) : []; if (selector.element) { return __spreadArray(__spreadArray([ 1 /* NOT */ | 4 /* ELEMENT */, selector.element ], __read(selector.attrs)), __read(classes)); } else if (selector.attrs.length) { return __spreadArray(__spreadArray([1 /* NOT */ | 2 /* ATTRIBUTE */], __read(selector.attrs)), __read(classes)); } else { return selector.classNames && selector.classNames.length ? __spreadArray([1 /* NOT */ | 8 /* CLASS */], __read(selector.classNames)) : []; } } function parserSelectorToR3Selector(selector) { var positive = parserSelectorToSimpleSelector(selector); var negative = selector.notSelectors && selector.notSelectors.length ? selector.notSelectors.map(function (notSelector) { return parserSelectorToNegativeSelector(notSelector); }) : []; return positive.concat.apply(positive, __spreadArray([], __read(negative))); } function parseSelectorToR3Selector(selector) { return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : []; } var core = /*#__PURE__*/Object.freeze({ __proto__: null, createInject: createInject, createInjectionToken: createInjectionToken, createAttribute: createAttribute, emitDistinctChangesOnlyDefaultValue: emitDistinctChangesOnlyDefaultValue, createContentChildren: createContentChildren, createContentChild: createContentChild, createViewChildren: createViewChildren, createViewChild: createViewChild, createDirective: createDirective, get ViewEncapsulation () { return ViewEncapsulation; }, get ChangeDetectionStrategy () { return ChangeDetectionStrategy; }, createComponent: createComponent, createPipe: createPipe, createInput: createInput, createOutput: createOutput, createHostBinding: createHostBinding, createHostListener: createHostListener, createNgModule: createNgModule, createInjectable: createInjectable, CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA, createOptional: createOptional, createSelf: createSelf, createSkipSelf: createSkipSelf, createHost: createHost, Type: Type, get SecurityContext () { return SecurityContext; }, get MissingTranslationStrategy () { return MissingTranslationStrategy; }, parseSelectorToR3Selector: parseSelectorToR3Selector }); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ //// Types var TypeModifier; (function (TypeModifier) { TypeModifier[TypeModifier["Const"] = 0] = "Const"; })(TypeModifier || (TypeModifier = {})); var Type$1 = /** @class */ (function () { function Type(modifiers) { if (modifiers === void 0) { modifiers = []; } this.modifiers = modifiers; } Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; }; return Type; }()); (function (BuiltinTypeName) { BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic"; BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool"; BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String"; BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int"; BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number"; BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function"; BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred"; BuiltinTypeName[BuiltinTypeName["None"] = 7] = "None"; })(exports.BuiltinTypeName || (exports.BuiltinTypeName = {})); var BuiltinType = /** @class */ (function (_super) { __extends(BuiltinType, _super); function BuiltinType(name, modifiers) { var _this = _super.call(this, modifiers) || this; _this.name = name; return _this; } BuiltinType.prototype.visitType = function (visitor, context) { return visitor.visitBuiltinType(this, context); }; return BuiltinType; }(Type$1)); var ExpressionType = /** @class */ (function (_super) { __extends(ExpressionType, _super); function ExpressionType(value, modifiers, typeParams) { if (typeParams === void 0) { typeParams = null; } var _this = _super.call(this, modifiers) || this; _this.value = value; _this.typeParams = typeParams; return _this; } ExpressionType.prototype.visitType = function (visitor, context) { return visitor.visitExpressionType(this, context); }; return ExpressionType; }(Type$1)); var ArrayType = /** @class */ (function (_super) { __extends(ArrayType, _super); function ArrayType(of, modifiers) { var _this = _super.call(this, modifiers) || this; _this.of = of; return _this; } ArrayType.prototype.visitType = function (visitor, context) { return visitor.visitArrayType(this, context); }; return ArrayType; }(Type$1)); var MapType = /** @class */ (function (_super) { __extends(MapType, _super); function MapType(valueType, modifiers) { var _this = _super.call(this, modifiers) || this; _this.valueType = valueType || null; return _this; } MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); }; return MapType; }(Type$1)); var DYNAMIC_TYPE = new BuiltinType(exports.BuiltinTypeName.Dynamic); var INFERRED_TYPE = new BuiltinType(exports.BuiltinTypeName.Inferred); var BOOL_TYPE = new BuiltinType(exports.BuiltinTypeName.Bool); var INT_TYPE = new BuiltinType(exports.BuiltinTypeName.Int); var NUMBER_TYPE = new BuiltinType(exports.BuiltinTypeName.Number); var STRING_TYPE = new BuiltinType(exports.BuiltinTypeName.String); var FUNCTION_TYPE = new BuiltinType(exports.BuiltinTypeName.Function); var NONE_TYPE = new BuiltinType(exports.BuiltinTypeName.None); (function (UnaryOperator) { UnaryOperator[UnaryOperator["Minus"] = 0] = "Minus"; UnaryOperator[UnaryOperator["Plus"] = 1] = "Plus"; })(exports.UnaryOperator || (exports.UnaryOperator = {})); (function (BinaryOperator) { BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals"; BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals"; BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical"; BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical"; BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus"; BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus"; BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide"; BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply"; BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo"; BinaryOperator[BinaryOperator["And"] = 9] = "And"; BinaryOperator[BinaryOperator["Or"] = 10] = "Or"; BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd"; BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower"; BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals"; BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger"; BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals"; BinaryOperator[BinaryOperator["NullishCoalesce"] = 16] = "NullishCoalesce"; })(exports.BinaryOperator || (exports.BinaryOperator = {})); function nullSafeIsEquivalent(base, other) { if (base == null || other == null) { return base == other; } return base.isEquivalent(other); } function areAllEquivalentPredicate(base, other, equivalentPredicate) { var len = base.length; if (len !== other.length) { return false; } for (var i = 0; i < len; i++) { if (!equivalentPredicate(base[i], other[i])) { return false; } } return true; } function areAllEquivalent(base, other) { return areAllEquivalentPredicate(base, other, function (baseElement, otherElement) { return baseElement.isEquivalent(otherElement); }); } var Expression = /** @class */ (function () { function Expression(type, sourceSpan) { this.type = type || null; this.sourceSpan = sourceSpan || null; } Expression.prototype.prop = function (name, sourceSpan) { return new ReadPropExpr(this, name, null, sourceSpan); }; Expression.prototype.key = function (index, type, sourceSpan) { return new ReadKeyExpr(this, index, type, sourceSpan); }; Expression.prototype.callMethod = function (name, params, sourceSpan) { return new InvokeMethodExpr(this, name, params, null, sourceSpan); }; Expression.prototype.callFn = function (params, sourceSpan, pure) { return new InvokeFunctionExpr(this, params, null, sourceSpan, pure); }; Expression.prototype.instantiate = function (params, type, sourceSpan) { return new InstantiateExpr(this, params, type, sourceSpan); }; Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) { if (falseCase === void 0) { falseCase = null; } return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan); }; Expression.prototype.equals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Equals, this, rhs, null, sourceSpan); }; Expression.prototype.notEquals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.NotEquals, this, rhs, null, sourceSpan); }; Expression.prototype.identical = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Identical, this, rhs, null, sourceSpan); }; Expression.prototype.notIdentical = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.NotIdentical, this, rhs, null, sourceSpan); }; Expression.prototype.minus = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Minus, this, rhs, null, sourceSpan); }; Expression.prototype.plus = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Plus, this, rhs, null, sourceSpan); }; Expression.prototype.divide = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Divide, this, rhs, null, sourceSpan); }; Expression.prototype.multiply = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Multiply, this, rhs, null, sourceSpan); }; Expression.prototype.modulo = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Modulo, this, rhs, null, sourceSpan); }; Expression.prototype.and = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.And, this, rhs, null, sourceSpan); }; Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) { if (parens === void 0) { parens = true; } return new BinaryOperatorExpr(exports.BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens); }; Expression.prototype.or = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Or, this, rhs, null, sourceSpan); }; Expression.prototype.lower = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Lower, this, rhs, null, sourceSpan); }; Expression.prototype.lowerEquals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.LowerEquals, this, rhs, null, sourceSpan); }; Expression.prototype.bigger = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.Bigger, this, rhs, null, sourceSpan); }; Expression.prototype.biggerEquals = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan); }; Expression.prototype.isBlank = function (sourceSpan) { // Note: We use equals by purpose here to compare to null and undefined in JS. // We use the typed null to allow strictNullChecks to narrow types. return this.equals(TYPED_NULL_EXPR, sourceSpan); }; Expression.prototype.cast = function (type, sourceSpan) { return new CastExpr(this, type, sourceSpan); }; Expression.prototype.nullishCoalesce = function (rhs, sourceSpan) { return new BinaryOperatorExpr(exports.BinaryOperator.NullishCoalesce, this, rhs, null, sourceSpan); }; Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); }; return Expression; }()); (function (BuiltinVar) { BuiltinVar[BuiltinVar["This"] = 0] = "This"; BuiltinVar[BuiltinVar["Super"] = 1] = "Super"; BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError"; BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack"; })(exports.BuiltinVar || (exports.BuiltinVar = {})); var ReadVarExpr = /** @class */ (function (_super) { __extends(ReadVarExpr, _super); function ReadVarExpr(name, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; if (typeof name === 'string') { _this.name = name; _this.builtin = null; } else { _this.name = null; _this.builtin = name; } return _this; } ReadVarExpr.prototype.isEquivalent = function (e) { return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin; }; ReadVarExpr.prototype.isConstant = function () { return false; }; ReadVarExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitReadVarExpr(this, context); }; ReadVarExpr.prototype.set = function (value) { if (!this.name) { throw new Error("Built in variable " + this.builtin + " can not be assigned to."); } return new WriteVarExpr(this.name, value, null, this.sourceSpan); }; return ReadVarExpr; }(Expression)); var TypeofExpr = /** @class */ (function (_super) { __extends(TypeofExpr, _super); function TypeofExpr(expr, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.expr = expr; return _this; } TypeofExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitTypeofExpr(this, context); }; TypeofExpr.prototype.isEquivalent = function (e) { return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr); }; TypeofExpr.prototype.isConstant = function () { return this.expr.isConstant(); }; return TypeofExpr; }(Expression)); var WrappedNodeExpr = /** @class */ (function (_super) { __extends(WrappedNodeExpr, _super); function WrappedNodeExpr(node, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.node = node; return _this; } WrappedNodeExpr.prototype.isEquivalent = function (e) { return e instanceof WrappedNodeExpr && this.node === e.node; }; WrappedNodeExpr.prototype.isConstant = function () { return false; }; WrappedNodeExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWrappedNodeExpr(this, context); }; return WrappedNodeExpr; }(Expression)); var WriteVarExpr = /** @class */ (function (_super) { __extends(WriteVarExpr, _super); function WriteVarExpr(name, value, type, sourceSpan) { var _this = _super.call(this, type || value.type, sourceSpan) || this; _this.name = name; _this.value = value; return _this; } WriteVarExpr.prototype.isEquivalent = function (e) { return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value); }; WriteVarExpr.prototype.isConstant = function () { return false; }; WriteVarExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWriteVarExpr(this, context); }; WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) { return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan); }; WriteVarExpr.prototype.toConstDecl = function () { return this.toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final]); }; return WriteVarExpr; }(Expression)); var WriteKeyExpr = /** @class */ (function (_super) { __extends(WriteKeyExpr, _super); function WriteKeyExpr(receiver, index, value, type, sourceSpan) { var _this = _super.call(this, type || value.type, sourceSpan) || this; _this.receiver = receiver; _this.index = index; _this.value = value; return _this; } WriteKeyExpr.prototype.isEquivalent = function (e) { return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value); }; WriteKeyExpr.prototype.isConstant = function () { return false; }; WriteKeyExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWriteKeyExpr(this, context); }; return WriteKeyExpr; }(Expression)); var WritePropExpr = /** @class */ (function (_super) { __extends(WritePropExpr, _super); function WritePropExpr(receiver, name, value, type, sourceSpan) { var _this = _super.call(this, type || value.type, sourceSpan) || this; _this.receiver = receiver; _this.name = name; _this.value = value; return _this; } WritePropExpr.prototype.isEquivalent = function (e) { return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name && this.value.isEquivalent(e.value); }; WritePropExpr.prototype.isConstant = function () { return false; }; WritePropExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitWritePropExpr(this, context); }; return WritePropExpr; }(Expression)); (function (BuiltinMethod) { BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray"; BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable"; BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind"; })(exports.BuiltinMethod || (exports.BuiltinMethod = {})); var InvokeMethodExpr = /** @class */ (function (_super) { __extends(InvokeMethodExpr, _super); function InvokeMethodExpr(receiver, method, args, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.receiver = receiver; _this.args = args; if (typeof method === 'string') { _this.name = method; _this.builtin = null; } else { _this.name = null; _this.builtin = method; } return _this; } InvokeMethodExpr.prototype.isEquivalent = function (e) { return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args); }; InvokeMethodExpr.prototype.isConstant = function () { return false; }; InvokeMethodExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitInvokeMethodExpr(this, context); }; return InvokeMethodExpr; }(Expression)); var InvokeFunctionExpr = /** @class */ (function (_super) { __extends(InvokeFunctionExpr, _super); function InvokeFunctionExpr(fn, args, type, sourceSpan, pure) { if (pure === void 0) { pure = false; } var _this = _super.call(this, type, sourceSpan) || this; _this.fn = fn; _this.args = args; _this.pure = pure; return _this; } InvokeFunctionExpr.prototype.isEquivalent = function (e) { return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) && areAllEquivalent(this.args, e.args) && this.pure === e.pure; }; InvokeFunctionExpr.prototype.isConstant = function () { return false; }; InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitInvokeFunctionExpr(this, context); }; return InvokeFunctionExpr; }(Expression)); var TaggedTemplateExpr = /** @class */ (function (_super) { __extends(TaggedTemplateExpr, _super); function TaggedTemplateExpr(tag, template, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.tag = tag; _this.template = template; return _this; } TaggedTemplateExpr.prototype.isEquivalent = function (e) { return e instanceof TaggedTemplateExpr && this.tag.isEquivalent(e.tag) && areAllEquivalentPredicate(this.template.elements, e.template.elements, function (a, b) { return a.text === b.text; }) && areAllEquivalent(this.template.expressions, e.template.expressions); }; TaggedTemplateExpr.prototype.isConstant = function () { return false; }; TaggedTemplateExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitTaggedTemplateExpr(this, context); }; return TaggedTemplateExpr; }(Expression)); var InstantiateExpr = /** @class */ (function (_super) { __extends(InstantiateExpr, _super); function InstantiateExpr(classExpr, args, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.classExpr = classExpr; _this.args = args; return _this; } InstantiateExpr.prototype.isEquivalent = function (e) { return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) && areAllEquivalent(this.args, e.args); }; InstantiateExpr.prototype.isConstant = function () { return false; }; InstantiateExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitInstantiateExpr(this, context); }; return InstantiateExpr; }(Expression)); var LiteralExpr = /** @class */ (function (_super) { __extends(LiteralExpr, _super); function LiteralExpr(value, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.value = value; return _this; } LiteralExpr.prototype.isEquivalent = function (e) { return e instanceof LiteralExpr && this.value === e.value; }; LiteralExpr.prototype.isConstant = function () { return true; }; LiteralExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitLiteralExpr(this, context); }; return LiteralExpr; }(Expression)); var TemplateLiteral = /** @class */ (function () { function TemplateLiteral(elements, expressions) { this.elements = elements; this.expressions = expressions; } return TemplateLiteral; }()); var TemplateLiteralElement = /** @class */ (function () { function TemplateLiteralElement(text, sourceSpan, rawText) { var _a; this.text = text; this.sourceSpan = sourceSpan; // If `rawText` is not provided, try to extract the raw string from its // associated `sourceSpan`. If that is also not available, "fake" the raw // string instead by escaping the following control sequences: // - "\" would otherwise indicate that the next character is a control character. // - "`" and "${" are template string control sequences that would otherwise prematurely // indicate the end of the template literal element. this.rawText = (_a = rawText !== null && rawText !== void 0 ? rawText : sourceSpan === null || sourceSpan === void 0 ? void 0 : sourceSpan.toString()) !== null && _a !== void 0 ? _a : escapeForTemplateLiteral(escapeSlashes(text)); } return TemplateLiteralElement; }()); var MessagePiece = /** @class */ (function () { function MessagePiece(text, sourceSpan) { this.text = text; this.sourceSpan = sourceSpan; } return MessagePiece; }()); var LiteralPiece = /** @class */ (function (_super) { __extends(LiteralPiece, _super); function LiteralPiece() { return _super !== null && _super.apply(this, arguments) || this; } return LiteralPiece; }(MessagePiece)); var PlaceholderPiece = /** @class */ (function (_super) { __extends(PlaceholderPiece, _super); function PlaceholderPiece() { return _super !== null && _super.apply(this, arguments) || this; } return PlaceholderPiece; }(MessagePiece)); var LocalizedString = /** @class */ (function (_super) { __extends(LocalizedString, _super); function LocalizedString(metaBlock, messageParts, placeHolderNames, expressions, sourceSpan) { var _this = _super.call(this, STRING_TYPE, sourceSpan) || this; _this.metaBlock = metaBlock; _this.messageParts = messageParts; _this.placeHolderNames = placeHolderNames; _this.expressions = expressions; return _this; } LocalizedString.prototype.isEquivalent = function (e) { // return e instanceof LocalizedString && this.message === e.message; return false; }; LocalizedString.prototype.isConstant = function () { return false; }; LocalizedString.prototype.visitExpression = function (visitor, context) { return visitor.visitLocalizedString(this, context); }; /** * Serialize the given `meta` and `messagePart` into "cooked" and "raw" strings that can be used * in a `$localize` tagged string. The format of the metadata is the same as that parsed by * `parseI18nMeta()`. * * @param meta The metadata to serialize * @param messagePart The first part of the tagged string */ LocalizedString.prototype.serializeI18nHead = function () { var MEANING_SEPARATOR = '|'; var ID_SEPARATOR = '@@'; var LEGACY_ID_INDICATOR = '␟'; var metaBlock = this.metaBlock.description || ''; if (this.metaBlock.meaning) { metaBlock = "" + this.metaBlock.meaning + MEANING_SEPARATOR + metaBlock; } if (this.metaBlock.customId) { metaBlock = "" + metaBlock + ID_SEPARATOR + this.metaBlock.customId; } if (this.metaBlock.legacyIds) { this.metaBlock.legacyIds.forEach(function (legacyId) { metaBlock = "" + metaBlock + LEGACY_ID_INDICATOR + legacyId; }); } return createCookedRawString(metaBlock, this.messageParts[0].text, this.getMessagePartSourceSpan(0)); }; LocalizedString.prototype.getMessagePartSourceSpan = function (i) { var _a, _b; return (_b = (_a = this.messageParts[i]) === null || _a === void 0 ? void 0 : _a.sourceSpan) !== null && _b !== void 0 ? _b : this.sourceSpan; }; LocalizedString.prototype.getPlaceholderSourceSpan = function (i) { var _a, _b, _c, _d; return (_d = (_b = (_a = this.placeHolderNames[i]) === null || _a === void 0 ? void 0 : _a.sourceSpan) !== null && _b !== void 0 ? _b : (_c = this.expressions[i]) === null || _c === void 0 ? void 0 : _c.sourceSpan) !== null && _d !== void 0 ? _d : this.sourceSpan; }; /** * Serialize the given `placeholderName` and `messagePart` into "cooked" and "raw" strings that * can be used in a `$localize` tagged string. * * @param placeholderName The placeholder name to serialize * @param messagePart The following message string after this placeholder */ LocalizedString.prototype.serializeI18nTemplatePart = function (partIndex) { var placeholderName = this.placeHolderNames[partIndex - 1].text; var messagePart = this.messageParts[partIndex]; return createCookedRawString(placeholderName, messagePart.text, this.getMessagePartSourceSpan(partIndex)); }; return LocalizedString; }(Expression)); var escapeSlashes = function (str) { return str.replace(/\\/g, '\\\\'); }; var escapeStartingColon = function (str) { return str.replace(/^:/, '\\:'); }; var escapeColons = function (str) { return str.replace(/:/g, '\\:'); }; var escapeForTemplateLiteral = function (str) { return str.replace(/`/g, '\\`').replace(/\${/g, '$\\{'); }; /** * Creates a `{cooked, raw}` object from the `metaBlock` and `messagePart`. * * The `raw` text must have various character sequences escaped: * * "\" would otherwise indicate that the next character is a control character. * * "`" and "${" are template string control sequences that would otherwise prematurely indicate * the end of a message part. * * ":" inside a metablock would prematurely indicate the end of the metablock. * * ":" at the start of a messagePart with no metablock would erroneously indicate the start of a * metablock. * * @param metaBlock Any metadata that should be prepended to the string * @param messagePart The message part of the string */ function createCookedRawString(metaBlock, messagePart, range) { if (metaBlock === '') { return { cooked: messagePart, raw: escapeForTemplateLiteral(escapeStartingColon(escapeSlashes(messagePart))), range: range, }; } else { return { cooked: ":" + metaBlock + ":" + messagePart, raw: escapeForTemplateLiteral(":" + escapeColons(escapeSlashes(metaBlock)) + ":" + escapeSlashes(messagePart)), range: range, }; } } var ExternalExpr = /** @class */ (function (_super) { __extends(ExternalExpr, _super); function ExternalExpr(value, type, typeParams, sourceSpan) { if (typeParams === void 0) { typeParams = null; } var _this = _super.call(this, type, sourceSpan) || this; _this.value = value; _this.typeParams = typeParams; return _this; } ExternalExpr.prototype.isEquivalent = function (e) { return e instanceof ExternalExpr && this.value.name === e.value.name && this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime; }; ExternalExpr.prototype.isConstant = function () { return false; }; ExternalExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitExternalExpr(this, context); }; return ExternalExpr; }(Expression)); var ExternalReference = /** @class */ (function () { function ExternalReference(moduleName, name, runtime) { this.moduleName = moduleName; this.name = name; this.runtime = runtime; } return ExternalReference; }()); var ConditionalExpr = /** @class */ (function (_super) { __extends(ConditionalExpr, _super); function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) { if (falseCase === void 0) { falseCase = null; } var _this = _super.call(this, type || trueCase.type, sourceSpan) || this; _this.condition = condition; _this.falseCase = falseCase; _this.trueCase = trueCase; return _this; } ConditionalExpr.prototype.isEquivalent = function (e) { return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) && this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase); }; ConditionalExpr.prototype.isConstant = function () { return false; }; ConditionalExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitConditionalExpr(this, context); }; return ConditionalExpr; }(Expression)); var NotExpr = /** @class */ (function (_super) { __extends(NotExpr, _super); function NotExpr(condition, sourceSpan) { var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this; _this.condition = condition; return _this; } NotExpr.prototype.isEquivalent = function (e) { return e instanceof NotExpr && this.condition.isEquivalent(e.condition); }; NotExpr.prototype.isConstant = function () { return false; }; NotExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitNotExpr(this, context); }; return NotExpr; }(Expression)); var AssertNotNull = /** @class */ (function (_super) { __extends(AssertNotNull, _super); function AssertNotNull(condition, sourceSpan) { var _this = _super.call(this, condition.type, sourceSpan) || this; _this.condition = condition; return _this; } AssertNotNull.prototype.isEquivalent = function (e) { return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition); }; AssertNotNull.prototype.isConstant = function () { return false; }; AssertNotNull.prototype.visitExpression = function (visitor, context) { return visitor.visitAssertNotNullExpr(this, context); }; return AssertNotNull; }(Expression)); var CastExpr = /** @class */ (function (_super) { __extends(CastExpr, _super); function CastExpr(value, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.value = value; return _this; } CastExpr.prototype.isEquivalent = function (e) { return e instanceof CastExpr && this.value.isEquivalent(e.value); }; CastExpr.prototype.isConstant = function () { return false; }; CastExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitCastExpr(this, context); }; return CastExpr; }(Expression)); var FnParam = /** @class */ (function () { function FnParam(name, type) { if (type === void 0) { type = null; } this.name = name; this.type = type; } FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; }; return FnParam; }()); var FunctionExpr = /** @class */ (function (_super) { __extends(FunctionExpr, _super); function FunctionExpr(params, statements, type, sourceSpan, name) { var _this = _super.call(this, type, sourceSpan) || this; _this.params = params; _this.statements = statements; _this.name = name; return _this; } FunctionExpr.prototype.isEquivalent = function (e) { return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) && areAllEquivalent(this.statements, e.statements); }; FunctionExpr.prototype.isConstant = function () { return false; }; FunctionExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitFunctionExpr(this, context); }; FunctionExpr.prototype.toDeclStmt = function (name, modifiers) { return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan); }; return FunctionExpr; }(Expression)); var UnaryOperatorExpr = /** @class */ (function (_super) { __extends(UnaryOperatorExpr, _super); function UnaryOperatorExpr(operator, expr, type, sourceSpan, parens) { if (parens === void 0) { parens = true; } var _this = _super.call(this, type || NUMBER_TYPE, sourceSpan) || this; _this.operator = operator; _this.expr = expr; _this.parens = parens; return _this; } UnaryOperatorExpr.prototype.isEquivalent = function (e) { return e instanceof UnaryOperatorExpr && this.operator === e.operator && this.expr.isEquivalent(e.expr); }; UnaryOperatorExpr.prototype.isConstant = function () { return false; }; UnaryOperatorExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitUnaryOperatorExpr(this, context); }; return UnaryOperatorExpr; }(Expression)); var BinaryOperatorExpr = /** @class */ (function (_super) { __extends(BinaryOperatorExpr, _super); function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) { if (parens === void 0) { parens = true; } var _this = _super.call(this, type || lhs.type, sourceSpan) || this; _this.operator = operator; _this.rhs = rhs; _this.parens = parens; _this.lhs = lhs; return _this; } BinaryOperatorExpr.prototype.isEquivalent = function (e) { return e instanceof BinaryOperatorExpr && this.operator === e.operator && this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs); }; BinaryOperatorExpr.prototype.isConstant = function () { return false; }; BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitBinaryOperatorExpr(this, context); }; return BinaryOperatorExpr; }(Expression)); var ReadPropExpr = /** @class */ (function (_super) { __extends(ReadPropExpr, _super); function ReadPropExpr(receiver, name, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.receiver = receiver; _this.name = name; return _this; } ReadPropExpr.prototype.isEquivalent = function (e) { return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) && this.name === e.name; }; ReadPropExpr.prototype.isConstant = function () { return false; }; ReadPropExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitReadPropExpr(this, context); }; ReadPropExpr.prototype.set = function (value) { return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan); }; return ReadPropExpr; }(Expression)); var ReadKeyExpr = /** @class */ (function (_super) { __extends(ReadKeyExpr, _super); function ReadKeyExpr(receiver, index, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.receiver = receiver; _this.index = index; return _this; } ReadKeyExpr.prototype.isEquivalent = function (e) { return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) && this.index.isEquivalent(e.index); }; ReadKeyExpr.prototype.isConstant = function () { return false; }; ReadKeyExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitReadKeyExpr(this, context); }; ReadKeyExpr.prototype.set = function (value) { return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan); }; return ReadKeyExpr; }(Expression)); var LiteralArrayExpr = /** @class */ (function (_super) { __extends(LiteralArrayExpr, _super); function LiteralArrayExpr(entries, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.entries = entries; return _this; } LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); }; LiteralArrayExpr.prototype.isEquivalent = function (e) { return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries); }; LiteralArrayExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitLiteralArrayExpr(this, context); }; return LiteralArrayExpr; }(Expression)); var LiteralMapEntry = /** @class */ (function () { function LiteralMapEntry(key, value, quoted) { this.key = key; this.value = value; this.quoted = quoted; } LiteralMapEntry.prototype.isEquivalent = function (e) { return this.key === e.key && this.value.isEquivalent(e.value); }; return LiteralMapEntry; }()); var LiteralMapExpr = /** @class */ (function (_super) { __extends(LiteralMapExpr, _super); function LiteralMapExpr(entries, type, sourceSpan) { var _this = _super.call(this, type, sourceSpan) || this; _this.entries = entries; _this.valueType = null; if (type) { _this.valueType = type.valueType; } return _this; } LiteralMapExpr.prototype.isEquivalent = function (e) { return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries); }; LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); }; LiteralMapExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitLiteralMapExpr(this, context); }; return LiteralMapExpr; }(Expression)); var CommaExpr = /** @class */ (function (_super) { __extends(CommaExpr, _super); function CommaExpr(parts, sourceSpan) { var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this; _this.parts = parts; return _this; } CommaExpr.prototype.isEquivalent = function (e) { return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts); }; CommaExpr.prototype.isConstant = function () { return false; }; CommaExpr.prototype.visitExpression = function (visitor, context) { return visitor.visitCommaExpr(this, context); }; return CommaExpr; }(Expression)); var THIS_EXPR = new ReadVarExpr(exports.BuiltinVar.This, null, null); var SUPER_EXPR = new ReadVarExpr(exports.BuiltinVar.Super, null, null); var CATCH_ERROR_VAR = new ReadVarExpr(exports.BuiltinVar.CatchError, null, null); var CATCH_STACK_VAR = new ReadVarExpr(exports.BuiltinVar.CatchStack, null, null); var NULL_EXPR = new LiteralExpr(null, null, null); var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null); (function (StmtModifier) { StmtModifier[StmtModifier["Final"] = 0] = "Final"; StmtModifier[StmtModifier["Private"] = 1] = "Private"; StmtModifier[StmtModifier["Exported"] = 2] = "Exported"; StmtModifier[StmtModifier["Static"] = 3] = "Static"; })(exports.StmtModifier || (exports.StmtModifier = {})); var LeadingComment = /** @class */ (function () { function LeadingComment(text, multiline, trailingNewline) { this.text = text; this.multiline = multiline; this.trailingNewline = trailingNewline; } LeadingComment.prototype.toString = function () { return this.multiline ? " " + this.text + " " : this.text; }; return LeadingComment; }()); var JSDocComment = /** @class */ (function (_super) { __extends(JSDocComment, _super); function JSDocComment(tags) { var _this = _super.call(this, '', /* multiline */ true, /* trailingNewline */ true) || this; _this.tags = tags; return _this; } JSDocComment.prototype.toString = function () { return serializeTags(this.tags); }; return JSDocComment; }(LeadingComment)); var Statement = /** @class */ (function () { function Statement(modifiers, sourceSpan, leadingComments) { if (modifiers === void 0) { modifiers = []; } if (sourceSpan === void 0) { sourceSpan = null; } this.modifiers = modifiers; this.sourceSpan = sourceSpan; this.leadingComments = leadingComments; } Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; }; Statement.prototype.addLeadingComment = function (leadingComment) { var _a; this.leadingComments = (_a = this.leadingComments) !== null && _a !== void 0 ? _a : []; this.leadingComments.push(leadingComment); }; return Statement; }()); var DeclareVarStmt = /** @class */ (function (_super) { __extends(DeclareVarStmt, _super); function DeclareVarStmt(name, value, type, modifiers, sourceSpan, leadingComments) { var _this = _super.call(this, modifiers, sourceSpan, leadingComments) || this; _this.name = name; _this.value = value; _this.type = type || (value && value.type) || null; return _this; } DeclareVarStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof DeclareVarStmt && this.name === stmt.name && (this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value); }; DeclareVarStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitDeclareVarStmt(this, context); }; return DeclareVarStmt; }(Statement)); var DeclareFunctionStmt = /** @class */ (function (_super) { __extends(DeclareFunctionStmt, _super); function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan, leadingComments) { var _this = _super.call(this, modifiers, sourceSpan, leadingComments) || this; _this.name = name; _this.params = params; _this.statements = statements; _this.type = type || null; return _this; } DeclareFunctionStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) && areAllEquivalent(this.statements, stmt.statements); }; DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitDeclareFunctionStmt(this, context); }; return DeclareFunctionStmt; }(Statement)); var ExpressionStatement = /** @class */ (function (_super) { __extends(ExpressionStatement, _super); function ExpressionStatement(expr, sourceSpan, leadingComments) { var _this = _super.call(this, [], sourceSpan, leadingComments) || this; _this.expr = expr; return _this; } ExpressionStatement.prototype.isEquivalent = function (stmt) { return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr); }; ExpressionStatement.prototype.visitStatement = function (visitor, context) { return visitor.visitExpressionStmt(this, context); }; return ExpressionStatement; }(Statement)); var ReturnStatement = /** @class */ (function (_super) { __extends(ReturnStatement, _super); function ReturnStatement(value, sourceSpan, leadingComments) { if (sourceSpan === void 0) { sourceSpan = null; } var _this = _super.call(this, [], sourceSpan, leadingComments) || this; _this.value = value; return _this; } ReturnStatement.prototype.isEquivalent = function (stmt) { return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value); }; ReturnStatement.prototype.visitStatement = function (visitor, context) { return visitor.visitReturnStmt(this, context); }; return ReturnStatement; }(Statement)); var AbstractClassPart = /** @class */ (function () { function AbstractClassPart(type, modifiers) { if (type === void 0) { type = null; } if (modifiers === void 0) { modifiers = []; } this.type = type; this.modifiers = modifiers; } AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; }; return AbstractClassPart; }()); var ClassField = /** @class */ (function (_super) { __extends(ClassField, _super); function ClassField(name, type, modifiers, initializer) { var _this = _super.call(this, type, modifiers) || this; _this.name = name; _this.initializer = initializer; return _this; } ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; }; return ClassField; }(AbstractClassPart)); var ClassMethod = /** @class */ (function (_super) { __extends(ClassMethod, _super); function ClassMethod(name, params, body, type, modifiers) { var _this = _super.call(this, type, modifiers) || this; _this.name = name; _this.params = params; _this.body = body; return _this; } ClassMethod.prototype.isEquivalent = function (m) { return this.name === m.name && areAllEquivalent(this.body, m.body); }; return ClassMethod; }(AbstractClassPart)); var ClassGetter = /** @class */ (function (_super) { __extends(ClassGetter, _super); function ClassGetter(name, body, type, modifiers) { var _this = _super.call(this, type, modifiers) || this; _this.name = name; _this.body = body; return _this; } ClassGetter.prototype.isEquivalent = function (m) { return this.name === m.name && areAllEquivalent(this.body, m.body); }; return ClassGetter; }(AbstractClassPart)); var ClassStmt = /** @class */ (function (_super) { __extends(ClassStmt, _super); function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan, leadingComments) { var _this = _super.call(this, modifiers, sourceSpan, leadingComments) || this; _this.name = name; _this.parent = parent; _this.fields = fields; _this.getters = getters; _this.constructorMethod = constructorMethod; _this.methods = methods; return _this; } ClassStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof ClassStmt && this.name === stmt.name && nullSafeIsEquivalent(this.parent, stmt.parent) && areAllEquivalent(this.fields, stmt.fields) && areAllEquivalent(this.getters, stmt.getters) && this.constructorMethod.isEquivalent(stmt.constructorMethod) && areAllEquivalent(this.methods, stmt.methods); }; ClassStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitDeclareClassStmt(this, context); }; return ClassStmt; }(Statement)); var IfStmt = /** @class */ (function (_super) { __extends(IfStmt, _super); function IfStmt(condition, trueCase, falseCase, sourceSpan, leadingComments) { if (falseCase === void 0) { falseCase = []; } var _this = _super.call(this, [], sourceSpan, leadingComments) || this; _this.condition = condition; _this.trueCase = trueCase; _this.falseCase = falseCase; return _this; } IfStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) && areAllEquivalent(this.trueCase, stmt.trueCase) && areAllEquivalent(this.falseCase, stmt.falseCase); }; IfStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitIfStmt(this, context); }; return IfStmt; }(Statement)); var TryCatchStmt = /** @class */ (function (_super) { __extends(TryCatchStmt, _super); function TryCatchStmt(bodyStmts, catchStmts, sourceSpan, leadingComments) { if (sourceSpan === void 0) { sourceSpan = null; } var _this = _super.call(this, [], sourceSpan, leadingComments) || this; _this.bodyStmts = bodyStmts; _this.catchStmts = catchStmts; return _this; } TryCatchStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) && areAllEquivalent(this.catchStmts, stmt.catchStmts); }; TryCatchStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitTryCatchStmt(this, context); }; return TryCatchStmt; }(Statement)); var ThrowStmt = /** @class */ (function (_super) { __extends(ThrowStmt, _super); function ThrowStmt(error, sourceSpan, leadingComments) { if (sourceSpan === void 0) { sourceSpan = null; } var _this = _super.call(this, [], sourceSpan, leadingComments) || this; _this.error = error; return _this; } ThrowStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error); }; ThrowStmt.prototype.visitStatement = function (visitor, context) { return visitor.visitThrowStmt(this, context); }; return ThrowStmt; }(Statement)); var AstTransformer = /** @class */ (function () { function AstTransformer() { } AstTransformer.prototype.transformExpr = function (expr, context) { return expr; }; AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; }; AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitWrappedNodeExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitTypeofExpr = function (expr, context) { return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitWriteVarExpr = function (expr, context) { return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) { return this.transformExpr(new WriteKeyExpr(expr.receiver.visitExpression(this, context), expr.index.visitExpression(this, context), expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitWritePropExpr = function (expr, context) { return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context); }; AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) { var method = ast.builtin || ast.name; return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) { return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitTaggedTemplateExpr = function (ast, context) { var _this = this; return this.transformExpr(new TaggedTemplateExpr(ast.tag.visitExpression(this, context), new TemplateLiteral(ast.template.elements, ast.template.expressions.map(function (e) { return e.visitExpression(_this, context); })), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitInstantiateExpr = function (ast, context) { return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitLocalizedString = function (ast, context) { return this.transformExpr(new LocalizedString(ast.metaBlock, ast.messageParts, ast.placeHolderNames, this.visitAllExpressions(ast.expressions, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitExternalExpr = function (ast, context) { return this.transformExpr(ast, context); }; AstTransformer.prototype.visitConditionalExpr = function (ast, context) { return this.transformExpr(new ConditionalExpr(ast.condition.visitExpression(this, context), ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitNotExpr = function (ast, context) { return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) { return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitCastExpr = function (ast, context) { return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitFunctionExpr = function (ast, context) { return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitUnaryOperatorExpr = function (ast, context) { return this.transformExpr(new UnaryOperatorExpr(ast.operator, ast.expr.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) { return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitReadPropExpr = function (ast, context) { return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitReadKeyExpr = function (ast, context) { return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) { return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context); }; AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) { var _this = this; var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); }); var mapType = new MapType(ast.valueType); return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context); }; AstTransformer.prototype.visitCommaExpr = function (ast, context) { return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context); }; AstTransformer.prototype.visitAllExpressions = function (exprs, context) { var _this = this; return exprs.map(function (expr) { return expr.visitExpression(_this, context); }); }; AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) { var value = stmt.value && stmt.value.visitExpression(this, context); return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) { return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitExpressionStmt = function (stmt, context) { return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitReturnStmt = function (stmt, context) { return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) { var _this = this; var parent = stmt.parent.visitExpression(this, context); var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); }); var ctorMethod = stmt.constructorMethod && new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers); var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); }); return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context); }; AstTransformer.prototype.visitIfStmt = function (stmt, context) { return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) { return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitThrowStmt = function (stmt, context) { return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context); }; AstTransformer.prototype.visitAllStatements = function (stmts, context) { var _this = this; return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); }); }; return AstTransformer; }()); var RecursiveAstVisitor = /** @class */ (function () { function RecursiveAstVisitor() { } RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; }; RecursiveAstVisitor.prototype.visitExpression = function (ast, context) { if (ast.type) { ast.type.visitType(this, context); } return ast; }; RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) { var _this = this; type.value.visitExpression(this, context); if (type.typeParams !== null) { type.typeParams.forEach(function (param) { return _this.visitType(param, context); }); } return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); }; RecursiveAstVisitor.prototype.visitWrappedNodeExpr = function (ast, context) { return ast; }; RecursiveAstVisitor.prototype.visitTypeofExpr = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) { ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) { ast.receiver.visitExpression(this, context); ast.index.visitExpression(this, context); ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) { ast.receiver.visitExpression(this, context); ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) { ast.receiver.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) { ast.fn.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitTaggedTemplateExpr = function (ast, context) { ast.tag.visitExpression(this, context); this.visitAllExpressions(ast.template.expressions, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) { ast.classExpr.visitExpression(this, context); this.visitAllExpressions(ast.args, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLocalizedString = function (ast, context) { return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) { var _this = this; if (ast.typeParams) { ast.typeParams.forEach(function (type) { return type.visitType(_this, context); }); } return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) { ast.condition.visitExpression(this, context); ast.trueCase.visitExpression(this, context); ast.falseCase.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) { ast.condition.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) { ast.condition.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) { ast.value.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) { this.visitAllStatements(ast.statements, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitUnaryOperatorExpr = function (ast, context) { ast.expr.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) { ast.lhs.visitExpression(this, context); ast.rhs.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) { ast.receiver.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) { ast.receiver.visitExpression(this, context); ast.index.visitExpression(this, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) { this.visitAllExpressions(ast.entries, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) { var _this = this; ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); }); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) { this.visitAllExpressions(ast.parts, context); return this.visitExpression(ast, context); }; RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) { var _this = this; exprs.forEach(function (expr) { return expr.visitExpression(_this, context); }); }; RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) { if (stmt.value) { stmt.value.visitExpression(this, context); } if (stmt.type) { stmt.type.visitType(this, context); } return stmt; }; RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) { this.visitAllStatements(stmt.statements, context); if (stmt.type) { stmt.type.visitType(this, context); } return stmt; }; RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) { stmt.expr.visitExpression(this, context); return stmt; }; RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) { stmt.value.visitExpression(this, context); return stmt; }; RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) { var _this = this; stmt.parent.visitExpression(this, context); stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); }); if (stmt.constructorMethod) { this.visitAllStatements(stmt.constructorMethod.body, context); } stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); }); return stmt; }; RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) { stmt.condition.visitExpression(this, context); this.visitAllStatements(stmt.trueCase, context); this.visitAllStatements(stmt.falseCase, context); return stmt; }; RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) { this.visitAllStatements(stmt.bodyStmts, context); this.visitAllStatements(stmt.catchStmts, context); return stmt; }; RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) { stmt.error.visitExpression(this, context); return stmt; }; RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) { var _this = this; stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); }); }; return RecursiveAstVisitor; }()); function findReadVarNames(stmts) { var visitor = new _ReadVarVisitor(); visitor.visitAllStatements(stmts, null); return visitor.varNames; } var _ReadVarVisitor = /** @class */ (function (_super) { __extends(_ReadVarVisitor, _super); function _ReadVarVisitor() { var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this; _this.varNames = new Set(); return _this; } _ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) { // Don't descend into nested functions return stmt; }; _ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) { // Don't descend into nested classes return stmt; }; _ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) { if (ast.name) { this.varNames.add(ast.name); } return null; }; return _ReadVarVisitor; }(RecursiveAstVisitor)); function collectExternalReferences(stmts) { var visitor = new _FindExternalReferencesVisitor(); visitor.visitAllStatements(stmts, null); return visitor.externalReferences; } var _FindExternalReferencesVisitor = /** @class */ (function (_super) { __extends(_FindExternalReferencesVisitor, _super); function _FindExternalReferencesVisitor() { var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this; _this.externalReferences = []; return _this; } _FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) { this.externalReferences.push(e.value); return _super.prototype.visitExternalExpr.call(this, e, context); }; return _FindExternalReferencesVisitor; }(RecursiveAstVisitor)); function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) { if (!sourceSpan) { return stmt; } var transformer = new _ApplySourceSpanTransformer(sourceSpan); return stmt.visitStatement(transformer, null); } function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) { if (!sourceSpan) { return expr; } var transformer = new _ApplySourceSpanTransformer(sourceSpan); return expr.visitExpression(transformer, null); } var _ApplySourceSpanTransformer = /** @class */ (function (_super) { __extends(_ApplySourceSpanTransformer, _super); function _ApplySourceSpanTransformer(sourceSpan) { var _this = _super.call(this) || this; _this.sourceSpan = sourceSpan; return _this; } _ApplySourceSpanTransformer.prototype._clone = function (obj) { var e_1, _e; var clone = Object.create(obj.constructor.prototype); try { for (var _f = __values(Object.keys(obj)), _g = _f.next(); !_g.done; _g = _f.next()) { var prop = _g.value; clone[prop] = obj[prop]; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_g && !_g.done && (_e = _f.return)) _e.call(_f); } finally { if (e_1) throw e_1.error; } } return clone; }; _ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) { if (!expr.sourceSpan) { expr = this._clone(expr); expr.sourceSpan = this.sourceSpan; } return expr; }; _ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) { if (!stmt.sourceSpan) { stmt = this._clone(stmt); stmt.sourceSpan = this.sourceSpan; } return stmt; }; return _ApplySourceSpanTransformer; }(AstTransformer)); function leadingComment(text, multiline, trailingNewline) { if (multiline === void 0) { multiline = false; } if (trailingNewline === void 0) { trailingNewline = true; } return new LeadingComment(text, multiline, trailingNewline); } function jsDocComment(tags) { if (tags === void 0) { tags = []; } return new JSDocComment(tags); } function variable(name, type, sourceSpan) { return new ReadVarExpr(name, type, sourceSpan); } function importExpr(id, typeParams, sourceSpan) { if (typeParams === void 0) { typeParams = null; } return new ExternalExpr(id, null, typeParams, sourceSpan); } function importType(id, typeParams, typeModifiers) { return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null; } function expressionType(expr, typeModifiers, typeParams) { return new ExpressionType(expr, typeModifiers, typeParams); } function typeofExpr(expr) { return new TypeofExpr(expr); } function literalArr(values, type, sourceSpan) { return new LiteralArrayExpr(values, type, sourceSpan); } function literalMap(values, type) { if (type === void 0) { type = null; } return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null); } function unary(operator, expr, type, sourceSpan) { return new UnaryOperatorExpr(operator, expr, type, sourceSpan); } function not(expr, sourceSpan) { return new NotExpr(expr, sourceSpan); } function assertNotNull(expr, sourceSpan) { return new AssertNotNull(expr, sourceSpan); } function fn(params, body, type, sourceSpan, name) { return new FunctionExpr(params, body, type, sourceSpan, name); } function ifStmt(condition, thenClause, elseClause, sourceSpan, leadingComments) { return new IfStmt(condition, thenClause, elseClause, sourceSpan, leadingComments); } function taggedTemplate(tag, template, type, sourceSpan) { return new TaggedTemplateExpr(tag, template, type, sourceSpan); } function literal(value, type, sourceSpan) { return new LiteralExpr(value, type, sourceSpan); } function localizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan) { return new LocalizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan); } function isNull(exp) { return exp instanceof LiteralExpr && exp.value === null; } /* * Serializes a `Tag` into a string. * Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`). */ function tagToString(tag) { var out = ''; if (tag.tagName) { out += " @" + tag.tagName; } if (tag.text) { if (tag.text.match(/\/\*|\*\//)) { throw new Error('JSDoc text cannot contain "/*" and "*/"'); } out += ' ' + tag.text.replace(/@/g, '\\@'); } return out; } function serializeTags(tags) { var e_2, _e; if (tags.length === 0) return ''; if (tags.length === 1 && tags[0].tagName && !tags[0].text) { // The JSDOC comment is a single simple tag: e.g `/** @tagname */`. return "*" + tagToString(tags[0]) + " "; } var out = '*\n'; try { for (var tags_1 = __values(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) { var tag = tags_1_1.value; out += ' *'; // If the tagToString is multi-line, insert " * " prefixes on lines. out += tagToString(tag).replace(/\n/g, '\n * '); out += '\n'; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (tags_1_1 && !tags_1_1.done && (_e = tags_1.return)) _e.call(tags_1); } finally { if (e_2) throw e_2.error; } } out += ' '; return out; } var CONSTANT_PREFIX = '_c'; /** * `ConstantPool` tries to reuse literal factories when two or more literals are identical. * We determine whether literals are identical by creating a key out of their AST using the * `KeyVisitor`. This constant is used to replace dynamic expressions which can't be safely * converted into a key. E.g. given an expression `{foo: bar()}`, since we don't know what * the result of `bar` will be, we create a key that looks like `{foo: }`. Note * that we use a variable, rather than something like `null` in order to avoid collisions. */ var UNKNOWN_VALUE_KEY = variable(''); /** * Context to use when producing a key. * * This ensures we see the constant not the reference variable when producing * a key. */ var KEY_CONTEXT = {}; /** * Generally all primitive values are excluded from the `ConstantPool`, but there is an exclusion * for strings that reach a certain length threshold. This constant defines the length threshold for * strings. */ var POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS = 50; /** * A node that is a place-holder that allows the node to be replaced when the actual * node is known. * * This allows the constant pool to change an expression from a direct reference to * a constant to a shared constant. It returns a fix-up node that is later allowed to * change the referenced expression. */ var FixupExpression = /** @class */ (function (_super) { __extends(FixupExpression, _super); function FixupExpression(resolved) { var _this = _super.call(this, resolved.type) || this; _this.resolved = resolved; _this.original = resolved; return _this; } FixupExpression.prototype.visitExpression = function (visitor, context) { if (context === KEY_CONTEXT) { // When producing a key we want to traverse the constant not the // variable used to refer to it. return this.original.visitExpression(visitor, context); } else { return this.resolved.visitExpression(visitor, context); } }; FixupExpression.prototype.isEquivalent = function (e) { return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved); }; FixupExpression.prototype.isConstant = function () { return true; }; FixupExpression.prototype.fixup = function (expression) { this.resolved = expression; this.shared = true; }; return FixupExpression; }(Expression)); /** * A constant pool allows a code emitter to share constant in an output context. * * The constant pool also supports sharing access to ivy definitions references. */ var ConstantPool = /** @class */ (function () { function ConstantPool(isClosureCompilerEnabled) { if (isClosureCompilerEnabled === void 0) { isClosureCompilerEnabled = false; } this.isClosureCompilerEnabled = isClosureCompilerEnabled; this.statements = []; this.literals = new Map(); this.literalFactories = new Map(); this.injectorDefinitions = new Map(); this.directiveDefinitions = new Map(); this.componentDefinitions = new Map(); this.pipeDefinitions = new Map(); this.nextNameIndex = 0; } ConstantPool.prototype.getConstLiteral = function (literal, forceShared) { if ((literal instanceof LiteralExpr && !isLongStringLiteral(literal)) || literal instanceof FixupExpression) { // Do no put simple literals into the constant pool or try to produce a constant for a // reference to a constant. return literal; } var key = this.keyOf(literal); var fixup = this.literals.get(key); var newValue = false; if (!fixup) { fixup = new FixupExpression(literal); this.literals.set(key, fixup); newValue = true; } if ((!newValue && !fixup.shared) || (newValue && forceShared)) { // Replace the expression with a variable var name = this.freshName(); var definition = void 0; var usage = void 0; if (this.isClosureCompilerEnabled && isLongStringLiteral(literal)) { // For string literals, Closure will **always** inline the string at // **all** usages, duplicating it each time. For large strings, this // unnecessarily bloats bundle size. To work around this restriction, we // wrap the string in a function, and call that function for each usage. // This tricks Closure into using inline logic for functions instead of // string literals. Function calls are only inlined if the body is small // enough to be worth it. By doing this, very large strings will be // shared across multiple usages, rather than duplicating the string at // each usage site. // // const myStr = function() { return "very very very long string"; }; // const usage1 = myStr(); // const usage2 = myStr(); definition = variable(name).set(new FunctionExpr([], // Params. [ // Statements. new ReturnStatement(literal), ])); usage = variable(name).callFn([]); } else { // Just declare and use the variable directly, without a function call // indirection. This saves a few bytes and avoids an unncessary call. definition = variable(name).set(literal); usage = variable(name); } this.statements.push(definition.toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final])); fixup.fixup(usage); } return fixup; }; ConstantPool.prototype.getDefinition = function (type, kind, ctx, forceShared) { if (forceShared === void 0) { forceShared = false; } var definitions = this.definitionsOf(kind); var fixup = definitions.get(type); var newValue = false; if (!fixup) { var property = this.propertyNameOf(kind); fixup = new FixupExpression(ctx.importExpr(type).prop(property)); definitions.set(type, fixup); newValue = true; } if ((!newValue && !fixup.shared) || (newValue && forceShared)) { var name = this.freshName(); this.statements.push(variable(name).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [exports.StmtModifier.Final])); fixup.fixup(variable(name)); } return fixup; }; ConstantPool.prototype.getLiteralFactory = function (literal) { // Create a pure function that builds an array of a mix of constant and variable expressions if (literal instanceof LiteralArrayExpr) { var argumentsForKey = literal.entries.map(function (e) { return e.isConstant() ? e : UNKNOWN_VALUE_KEY; }); var key = this.keyOf(literalArr(argumentsForKey)); return this._getLiteralFactory(key, literal.entries, function (entries) { return literalArr(entries); }); } else { var expressionForKey = literalMap(literal.entries.map(function (e) { return ({ key: e.key, value: e.value.isConstant() ? e.value : UNKNOWN_VALUE_KEY, quoted: e.quoted }); })); var key = this.keyOf(expressionForKey); return this._getLiteralFactory(key, literal.entries.map(function (e) { return e.value; }), function (entries) { return literalMap(entries.map(function (value, index) { return ({ key: literal.entries[index].key, value: value, quoted: literal.entries[index].quoted }); })); }); } }; ConstantPool.prototype._getLiteralFactory = function (key, values, resultMap) { var _this = this; var literalFactory = this.literalFactories.get(key); var literalFactoryArguments = values.filter((function (e) { return !e.isConstant(); })); if (!literalFactory) { var resultExpressions = values.map(function (e, index) { return e.isConstant() ? _this.getConstLiteral(e, true) : variable("a" + index); }); var parameters = resultExpressions.filter(isVariable).map(function (e) { return new FnParam(e.name, DYNAMIC_TYPE); }); var pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE); var name = this.freshName(); this.statements.push(variable(name).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [ exports.StmtModifier.Final ])); literalFactory = variable(name); this.literalFactories.set(key, literalFactory); } return { literalFactory: literalFactory, literalFactoryArguments: literalFactoryArguments }; }; /** * Produce a unique name. * * The name might be unique among different prefixes if any of the prefixes end in * a digit so the prefix should be a constant string (not based on user input) and * must not end in a digit. */ ConstantPool.prototype.uniqueName = function (prefix) { return "" + prefix + this.nextNameIndex++; }; ConstantPool.prototype.definitionsOf = function (kind) { switch (kind) { case 2 /* Component */: return this.componentDefinitions; case 1 /* Directive */: return this.directiveDefinitions; case 0 /* Injector */: return this.injectorDefinitions; case 3 /* Pipe */: return this.pipeDefinitions; } }; ConstantPool.prototype.propertyNameOf = function (kind) { switch (kind) { case 2 /* Component */: return 'ɵcmp'; case 1 /* Directive */: return 'ɵdir'; case 0 /* Injector */: return 'ɵinj'; case 3 /* Pipe */: return 'ɵpipe'; } }; ConstantPool.prototype.freshName = function () { return this.uniqueName(CONSTANT_PREFIX); }; ConstantPool.prototype.keyOf = function (expression) { return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT); }; return ConstantPool; }()); /** * Visitor used to determine if 2 expressions are equivalent and can be shared in the * `ConstantPool`. * * When the id (string) generated by the visitor is equal, expressions are considered equivalent. */ var KeyVisitor = /** @class */ (function () { function KeyVisitor() { this.visitWrappedNodeExpr = invalid; this.visitWriteVarExpr = invalid; this.visitWriteKeyExpr = invalid; this.visitWritePropExpr = invalid; this.visitInvokeMethodExpr = invalid; this.visitInvokeFunctionExpr = invalid; this.visitTaggedTemplateExpr = invalid; this.visitInstantiateExpr = invalid; this.visitConditionalExpr = invalid; this.visitNotExpr = invalid; this.visitAssertNotNullExpr = invalid; this.visitCastExpr = invalid; this.visitFunctionExpr = invalid; this.visitUnaryOperatorExpr = invalid; this.visitBinaryOperatorExpr = invalid; this.visitReadPropExpr = invalid; this.visitReadKeyExpr = invalid; this.visitCommaExpr = invalid; this.visitLocalizedString = invalid; } KeyVisitor.prototype.visitLiteralExpr = function (ast) { return "" + (typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value); }; KeyVisitor.prototype.visitLiteralArrayExpr = function (ast, context) { var _this = this; return "[" + ast.entries.map(function (entry) { return entry.visitExpression(_this, context); }).join(',') + "]"; }; KeyVisitor.prototype.visitLiteralMapExpr = function (ast, context) { var _this = this; var mapKey = function (entry) { var quote = entry.quoted ? '"' : ''; return "" + quote + entry.key + quote; }; var mapEntry = function (entry) { return mapKey(entry) + ":" + entry.value.visitExpression(_this, context); }; return "{" + ast.entries.map(mapEntry).join(','); }; KeyVisitor.prototype.visitExternalExpr = function (ast) { return ast.value.moduleName ? "EX:" + ast.value.moduleName + ":" + ast.value.name : "EX:" + ast.value.runtime.name; }; KeyVisitor.prototype.visitReadVarExpr = function (node) { return "VAR:" + node.name; }; KeyVisitor.prototype.visitTypeofExpr = function (node, context) { return "TYPEOF:" + node.expr.visitExpression(this, context); }; return KeyVisitor; }()); function invalid(arg) { throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name); } function isVariable(e) { return e instanceof ReadVarExpr; } function isLongStringLiteral(expr) { return expr instanceof LiteralExpr && typeof expr.value === 'string' && expr.value.length >= POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var CORE = '@angular/core'; var Identifiers = /** @class */ (function () { function Identifiers() { } return Identifiers; }()); /* Methods */ Identifiers.NEW_METHOD = 'factory'; Identifiers.TRANSFORM_METHOD = 'transform'; Identifiers.PATCH_DEPS = 'patchedDeps'; Identifiers.core = { name: null, moduleName: CORE }; /* Instructions */ Identifiers.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE }; Identifiers.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE }; Identifiers.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE }; Identifiers.element = { name: 'ɵɵelement', moduleName: CORE }; Identifiers.elementStart = { name: 'ɵɵelementStart', moduleName: CORE }; Identifiers.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE }; Identifiers.advance = { name: 'ɵɵadvance', moduleName: CORE }; Identifiers.syntheticHostProperty = { name: 'ɵɵsyntheticHostProperty', moduleName: CORE }; Identifiers.syntheticHostListener = { name: 'ɵɵsyntheticHostListener', moduleName: CORE }; Identifiers.attribute = { name: 'ɵɵattribute', moduleName: CORE }; Identifiers.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE }; Identifiers.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE }; Identifiers.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE }; Identifiers.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE }; Identifiers.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE }; Identifiers.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE }; Identifiers.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE }; Identifiers.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE }; Identifiers.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE }; Identifiers.classProp = { name: 'ɵɵclassProp', moduleName: CORE }; Identifiers.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE }; Identifiers.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE }; Identifiers.elementContainer = { name: 'ɵɵelementContainer', moduleName: CORE }; Identifiers.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE }; Identifiers.styleMapInterpolate1 = { name: 'ɵɵstyleMapInterpolate1', moduleName: CORE }; Identifiers.styleMapInterpolate2 = { name: 'ɵɵstyleMapInterpolate2', moduleName: CORE }; Identifiers.styleMapInterpolate3 = { name: 'ɵɵstyleMapInterpolate3', moduleName: CORE }; Identifiers.styleMapInterpolate4 = { name: 'ɵɵstyleMapInterpolate4', moduleName: CORE }; Identifiers.styleMapInterpolate5 = { name: 'ɵɵstyleMapInterpolate5', moduleName: CORE }; Identifiers.styleMapInterpolate6 = { name: 'ɵɵstyleMapInterpolate6', moduleName: CORE }; Identifiers.styleMapInterpolate7 = { name: 'ɵɵstyleMapInterpolate7', moduleName: CORE }; Identifiers.styleMapInterpolate8 = { name: 'ɵɵstyleMapInterpolate8', moduleName: CORE }; Identifiers.styleMapInterpolateV = { name: 'ɵɵstyleMapInterpolateV', moduleName: CORE }; Identifiers.classMap = { name: 'ɵɵclassMap', moduleName: CORE }; Identifiers.classMapInterpolate1 = { name: 'ɵɵclassMapInterpolate1', moduleName: CORE }; Identifiers.classMapInterpolate2 = { name: 'ɵɵclassMapInterpolate2', moduleName: CORE }; Identifiers.classMapInterpolate3 = { name: 'ɵɵclassMapInterpolate3', moduleName: CORE }; Identifiers.classMapInterpolate4 = { name: 'ɵɵclassMapInterpolate4', moduleName: CORE }; Identifiers.classMapInterpolate5 = { name: 'ɵɵclassMapInterpolate5', moduleName: CORE }; Identifiers.classMapInterpolate6 = { name: 'ɵɵclassMapInterpolate6', moduleName: CORE }; Identifiers.classMapInterpolate7 = { name: 'ɵɵclassMapInterpolate7', moduleName: CORE }; Identifiers.classMapInterpolate8 = { name: 'ɵɵclassMapInterpolate8', moduleName: CORE }; Identifiers.classMapInterpolateV = { name: 'ɵɵclassMapInterpolateV', moduleName: CORE }; Identifiers.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE }; Identifiers.stylePropInterpolate1 = { name: 'ɵɵstylePropInterpolate1', moduleName: CORE }; Identifiers.stylePropInterpolate2 = { name: 'ɵɵstylePropInterpolate2', moduleName: CORE }; Identifiers.stylePropInterpolate3 = { name: 'ɵɵstylePropInterpolate3', moduleName: CORE }; Identifiers.stylePropInterpolate4 = { name: 'ɵɵstylePropInterpolate4', moduleName: CORE }; Identifiers.stylePropInterpolate5 = { name: 'ɵɵstylePropInterpolate5', moduleName: CORE }; Identifiers.stylePropInterpolate6 = { name: 'ɵɵstylePropInterpolate6', moduleName: CORE }; Identifiers.stylePropInterpolate7 = { name: 'ɵɵstylePropInterpolate7', moduleName: CORE }; Identifiers.stylePropInterpolate8 = { name: 'ɵɵstylePropInterpolate8', moduleName: CORE }; Identifiers.stylePropInterpolateV = { name: 'ɵɵstylePropInterpolateV', moduleName: CORE }; Identifiers.nextContext = { name: 'ɵɵnextContext', moduleName: CORE }; Identifiers.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE }; Identifiers.text = { name: 'ɵɵtext', moduleName: CORE }; Identifiers.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE }; Identifiers.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE }; Identifiers.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE }; Identifiers.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE }; Identifiers.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE }; Identifiers.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE }; Identifiers.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE }; Identifiers.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE }; Identifiers.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE }; Identifiers.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE }; Identifiers.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE }; Identifiers.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE }; Identifiers.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE }; Identifiers.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE }; Identifiers.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE }; Identifiers.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE }; Identifiers.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE }; Identifiers.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE }; Identifiers.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE }; Identifiers.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE }; Identifiers.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE }; Identifiers.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE }; Identifiers.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE }; Identifiers.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE }; Identifiers.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE }; Identifiers.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE }; Identifiers.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE }; Identifiers.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE }; Identifiers.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE }; Identifiers.hostProperty = { name: 'ɵɵhostProperty', moduleName: CORE }; Identifiers.property = { name: 'ɵɵproperty', moduleName: CORE }; Identifiers.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE }; Identifiers.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE }; Identifiers.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE }; Identifiers.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE }; Identifiers.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE }; Identifiers.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE }; Identifiers.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE }; Identifiers.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE }; Identifiers.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE }; Identifiers.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE }; Identifiers.i18n = { name: 'ɵɵi18n', moduleName: CORE }; Identifiers.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE }; Identifiers.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE }; Identifiers.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE }; Identifiers.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE }; Identifiers.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE }; Identifiers.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE }; Identifiers.pipe = { name: 'ɵɵpipe', moduleName: CORE }; Identifiers.projection = { name: 'ɵɵprojection', moduleName: CORE }; Identifiers.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE }; Identifiers.reference = { name: 'ɵɵreference', moduleName: CORE }; Identifiers.inject = { name: 'ɵɵinject', moduleName: CORE }; Identifiers.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE }; Identifiers.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE }; Identifiers.invalidFactory = { name: 'ɵɵinvalidFactory', moduleName: CORE }; Identifiers.invalidFactoryDep = { name: 'ɵɵinvalidFactoryDep', moduleName: CORE }; Identifiers.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE }; Identifiers.forwardRef = { name: 'forwardRef', moduleName: CORE }; Identifiers.resolveForwardRef = { name: 'resolveForwardRef', moduleName: CORE }; Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE }; Identifiers.declareInjectable = { name: 'ɵɵngDeclareInjectable', moduleName: CORE }; Identifiers.InjectableDeclaration = { name: 'ɵɵInjectableDeclaration', moduleName: CORE }; Identifiers.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE }; Identifiers.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE }; Identifiers.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE }; Identifiers.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE }; Identifiers.declareComponent = { name: 'ɵɵngDeclareComponent', moduleName: CORE }; Identifiers.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE }; Identifiers.ChangeDetectionStrategy = { name: 'ChangeDetectionStrategy', moduleName: CORE, }; Identifiers.ViewEncapsulation = { name: 'ViewEncapsulation', moduleName: CORE, }; Identifiers.ComponentDeclaration = { name: 'ɵɵComponentDeclaration', moduleName: CORE, }; Identifiers.FactoryDeclaration = { name: 'ɵɵFactoryDeclaration', moduleName: CORE, }; Identifiers.declareFactory = { name: 'ɵɵngDeclareFactory', moduleName: CORE }; Identifiers.FactoryTarget = { name: 'ɵɵFactoryTarget', moduleName: CORE }; Identifiers.defineDirective = { name: 'ɵɵdefineDirective', moduleName: CORE }; Identifiers.declareDirective = { name: 'ɵɵngDeclareDirective', moduleName: CORE }; Identifiers.DirectiveDeclaration = { name: 'ɵɵDirectiveDeclaration', moduleName: CORE, }; Identifiers.InjectorDef = { name: 'ɵɵInjectorDef', moduleName: CORE }; Identifiers.InjectorDeclaration = { name: 'ɵɵInjectorDeclaration', moduleName: CORE }; Identifiers.defineInjector = { name: 'ɵɵdefineInjector', moduleName: CORE }; Identifiers.declareInjector = { name: 'ɵɵngDeclareInjector', moduleName: CORE }; Identifiers.NgModuleDeclaration = { name: 'ɵɵNgModuleDeclaration', moduleName: CORE, }; Identifiers.ModuleWithProviders = { name: 'ModuleWithProviders', moduleName: CORE, }; Identifiers.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE }; Identifiers.declareNgModule = { name: 'ɵɵngDeclareNgModule', moduleName: CORE }; Identifiers.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE }; Identifiers.PipeDeclaration = { name: 'ɵɵPipeDeclaration', moduleName: CORE }; Identifiers.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE }; Identifiers.declarePipe = { name: 'ɵɵngDeclarePipe', moduleName: CORE }; Identifiers.declareClassMetadata = { name: 'ɵɵngDeclareClassMetadata', moduleName: CORE }; Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE }; Identifiers.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE }; Identifiers.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE }; Identifiers.loadQuery = { name: 'ɵɵloadQuery', moduleName: CORE }; Identifiers.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE }; Identifiers.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE }; Identifiers.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE }; Identifiers.CopyDefinitionFeature = { name: 'ɵɵCopyDefinitionFeature', moduleName: CORE }; Identifiers.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE }; Identifiers.listener = { name: 'ɵɵlistener', moduleName: CORE }; Identifiers.getInheritedFactory = { name: 'ɵɵgetInheritedFactory', moduleName: CORE, }; // sanitization-related functions Identifiers.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE }; Identifiers.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE }; Identifiers.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE }; Identifiers.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE }; Identifiers.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE }; Identifiers.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE }; Identifiers.trustConstantHtml = { name: 'ɵɵtrustConstantHtml', moduleName: CORE }; Identifiers.trustConstantResourceUrl = { name: 'ɵɵtrustConstantResourceUrl', moduleName: CORE }; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var DASH_CASE_REGEXP = /-+([a-z0-9])/g; function dashCaseToCamelCase(input) { return input.replace(DASH_CASE_REGEXP, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } return m[1].toUpperCase(); }); } function splitAtColon(input, defaultValues) { return _splitAt(input, ':', defaultValues); } function splitAtPeriod(input, defaultValues) { return _splitAt(input, '.', defaultValues); } function _splitAt(input, character, defaultValues) { var characterIndex = input.indexOf(character); if (characterIndex == -1) return defaultValues; return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()]; } function visitValue(value, visitor, context) { if (Array.isArray(value)) { return visitor.visitArray(value, context); } if (isStrictStringMap(value)) { return visitor.visitStringMap(value, context); } if (value == null || typeof value == 'string' || typeof value == 'number' || typeof value == 'boolean') { return visitor.visitPrimitive(value, context); } return visitor.visitOther(value, context); } function isDefined(val) { return val !== null && val !== undefined; } function noUndefined(val) { return val === undefined ? null : val; } var ValueTransformer = /** @class */ (function () { function ValueTransformer() { } ValueTransformer.prototype.visitArray = function (arr, context) { var _this = this; return arr.map(function (value) { return visitValue(value, _this, context); }); }; ValueTransformer.prototype.visitStringMap = function (map, context) { var _this = this; var result = {}; Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); }); return result; }; ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; }; ValueTransformer.prototype.visitOther = function (value, context) { return value; }; return ValueTransformer; }()); var SyncAsync = { assertSync: function (value) { if (isPromise(value)) { throw new Error("Illegal state: value cannot be a promise"); } return value; }, then: function (value, cb) { return isPromise(value) ? value.then(cb) : cb(value); }, all: function (syncAsyncValues) { return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues; } }; function error(msg) { throw new Error("Internal Error: " + msg); } function syntaxError(msg, parseErrors) { var error = Error(msg); error[ERROR_SYNTAX_ERROR] = true; if (parseErrors) error[ERROR_PARSE_ERRORS] = parseErrors; return error; } var ERROR_SYNTAX_ERROR = 'ngSyntaxError'; var ERROR_PARSE_ERRORS = 'ngParseErrors'; function isSyntaxError(error) { return error[ERROR_SYNTAX_ERROR]; } function getParseErrors(error) { return error[ERROR_PARSE_ERRORS] || []; } // Escape characters that have a special meaning in Regular Expressions function escapeRegExp(s) { return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); } var STRING_MAP_PROTO = Object.getPrototypeOf({}); function isStrictStringMap(obj) { return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO; } function utf8Encode(str) { var encoded = []; for (var index = 0; index < str.length; index++) { var codePoint = str.charCodeAt(index); // decode surrogate // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) { var low = str.charCodeAt(index + 1); if (low >= 0xdc00 && low <= 0xdfff) { index++; codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000; } } if (codePoint <= 0x7f) { encoded.push(codePoint); } else if (codePoint <= 0x7ff) { encoded.push(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80); } else if (codePoint <= 0xffff) { encoded.push((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); } else if (codePoint <= 0x1fffff) { encoded.push(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); } } return encoded; } function stringify(token) { if (typeof token === 'string') { return token; } if (Array.isArray(token)) { return '[' + token.map(stringify).join(', ') + ']'; } if (token == null) { return '' + token; } if (token.overriddenName) { return "" + token.overriddenName; } if (token.name) { return "" + token.name; } if (!token.toString) { return 'object'; } // WARNING: do not try to `JSON.stringify(token)` here // see https://github.com/angular/angular/issues/23440 var res = token.toString(); if (res == null) { return '' + res; } var newLineIndex = res.indexOf('\n'); return newLineIndex === -1 ? res : res.substring(0, newLineIndex); } /** * Lazily retrieves the reference value from a forwardRef. */ function resolveForwardRef(type) { if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) { return type(); } else { return type; } } /** * Determine if the argument is shaped like a Promise */ function isPromise(obj) { // allow any Promise/A+ compliant thenable. // It's up to the caller to ensure that obj.then conforms to the spec return !!obj && typeof obj.then === 'function'; } var Version = /** @class */ (function () { function Version(full) { this.full = full; var splits = full.split('.'); this.major = splits[0]; this.minor = splits[1]; this.patch = splits.slice(2).join('.'); } return Version; }()); var __window = typeof window !== 'undefined' && window; var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && self; var __global = typeof global !== 'undefined' && global; // Check __global first, because in Node tests both __global and __window may be defined and _global // should be __global in that case. var _global = __global || __window || __self; function newArray(size, value) { var list = []; for (var i = 0; i < size; i++) { list.push(value); } return list; } /** * Partitions a given array into 2 arrays, based on a boolean value returned by the condition * function. * * @param arr Input array that should be partitioned * @param conditionFn Condition function that is called for each item in a given array and returns a * boolean value. */ function partitionArray(arr, conditionFn) { var e_1, _a; var truthy = []; var falsy = []; try { for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) { var item = arr_1_1.value; (conditionFn(item) ? truthy : falsy).push(item); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1); } finally { if (e_1) throw e_1.error; } } return [truthy, falsy]; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * This is an R3 `Node`-like wrapper for a raw `html.Comment` node. We do not currently * require the implementation of a visitor for Comments as they are only collected at * the top-level of the R3 AST, and only if `Render3ParseOptions['collectCommentNodes']` * is true. */ var Comment = /** @class */ (function () { function Comment(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Comment.prototype.visit = function (_visitor) { throw new Error('visit() not implemented for Comment'); }; return Comment; }()); var Text = /** @class */ (function () { function Text(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Text.prototype.visit = function (visitor) { return visitor.visitText(this); }; return Text; }()); var BoundText = /** @class */ (function () { function BoundText(value, sourceSpan, i18n) { this.value = value; this.sourceSpan = sourceSpan; this.i18n = i18n; } BoundText.prototype.visit = function (visitor) { return visitor.visitBoundText(this); }; return BoundText; }()); /** * Represents a text attribute in the template. * * `valueSpan` may not be present in cases where there is no value `
    `. * `keySpan` may also not be present for synthetic attributes from ICU expansions. */ var TextAttribute = /** @class */ (function () { function TextAttribute(name, value, sourceSpan, keySpan, valueSpan, i18n) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; this.i18n = i18n; } TextAttribute.prototype.visit = function (visitor) { return visitor.visitTextAttribute(this); }; return TextAttribute; }()); var BoundAttribute = /** @class */ (function () { function BoundAttribute(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan, i18n) { this.name = name; this.type = type; this.securityContext = securityContext; this.value = value; this.unit = unit; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; this.i18n = i18n; } BoundAttribute.fromBoundElementProperty = function (prop, i18n) { if (prop.keySpan === undefined) { throw new Error("Unexpected state: keySpan must be defined for bound attributes but was not for " + prop.name + ": " + prop.sourceSpan); } return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n); }; BoundAttribute.prototype.visit = function (visitor) { return visitor.visitBoundAttribute(this); }; return BoundAttribute; }()); var BoundEvent = /** @class */ (function () { function BoundEvent(name, type, handler, target, phase, sourceSpan, handlerSpan, keySpan) { this.name = name; this.type = type; this.handler = handler; this.target = target; this.phase = phase; this.sourceSpan = sourceSpan; this.handlerSpan = handlerSpan; this.keySpan = keySpan; } BoundEvent.fromParsedEvent = function (event) { var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null; var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null; if (event.keySpan === undefined) { throw new Error("Unexpected state: keySpan must be defined for bound event but was not for " + event.name + ": " + event.sourceSpan); } return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan, event.keySpan); }; BoundEvent.prototype.visit = function (visitor) { return visitor.visitBoundEvent(this); }; return BoundEvent; }()); var Element = /** @class */ (function () { function Element(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) { this.name = name; this.attributes = attributes; this.inputs = inputs; this.outputs = outputs; this.children = children; this.references = references; this.sourceSpan = sourceSpan; this.startSourceSpan = startSourceSpan; this.endSourceSpan = endSourceSpan; this.i18n = i18n; } Element.prototype.visit = function (visitor) { return visitor.visitElement(this); }; return Element; }()); var Template = /** @class */ (function () { function Template(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) { this.tagName = tagName; this.attributes = attributes; this.inputs = inputs; this.outputs = outputs; this.templateAttrs = templateAttrs; this.children = children; this.references = references; this.variables = variables; this.sourceSpan = sourceSpan; this.startSourceSpan = startSourceSpan; this.endSourceSpan = endSourceSpan; this.i18n = i18n; } Template.prototype.visit = function (visitor) { return visitor.visitTemplate(this); }; return Template; }()); var Content = /** @class */ (function () { function Content(selector, attributes, sourceSpan, i18n) { this.selector = selector; this.attributes = attributes; this.sourceSpan = sourceSpan; this.i18n = i18n; this.name = 'ng-content'; } Content.prototype.visit = function (visitor) { return visitor.visitContent(this); }; return Content; }()); var Variable = /** @class */ (function () { function Variable(name, value, sourceSpan, keySpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; } Variable.prototype.visit = function (visitor) { return visitor.visitVariable(this); }; return Variable; }()); var Reference = /** @class */ (function () { function Reference(name, value, sourceSpan, keySpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; } Reference.prototype.visit = function (visitor) { return visitor.visitReference(this); }; return Reference; }()); var Icu = /** @class */ (function () { function Icu(vars, placeholders, sourceSpan, i18n) { this.vars = vars; this.placeholders = placeholders; this.sourceSpan = sourceSpan; this.i18n = i18n; } Icu.prototype.visit = function (visitor) { return visitor.visitIcu(this); }; return Icu; }()); var NullVisitor = /** @class */ (function () { function NullVisitor() { } NullVisitor.prototype.visitElement = function (element) { }; NullVisitor.prototype.visitTemplate = function (template) { }; NullVisitor.prototype.visitContent = function (content) { }; NullVisitor.prototype.visitVariable = function (variable) { }; NullVisitor.prototype.visitReference = function (reference) { }; NullVisitor.prototype.visitTextAttribute = function (attribute) { }; NullVisitor.prototype.visitBoundAttribute = function (attribute) { }; NullVisitor.prototype.visitBoundEvent = function (attribute) { }; NullVisitor.prototype.visitText = function (text) { }; NullVisitor.prototype.visitBoundText = function (text) { }; NullVisitor.prototype.visitIcu = function (icu) { }; return NullVisitor; }()); var RecursiveVisitor = /** @class */ (function () { function RecursiveVisitor() { } RecursiveVisitor.prototype.visitElement = function (element) { visitAll(this, element.attributes); visitAll(this, element.inputs); visitAll(this, element.outputs); visitAll(this, element.children); visitAll(this, element.references); }; RecursiveVisitor.prototype.visitTemplate = function (template) { visitAll(this, template.attributes); visitAll(this, template.inputs); visitAll(this, template.outputs); visitAll(this, template.children); visitAll(this, template.references); visitAll(this, template.variables); }; RecursiveVisitor.prototype.visitContent = function (content) { }; RecursiveVisitor.prototype.visitVariable = function (variable) { }; RecursiveVisitor.prototype.visitReference = function (reference) { }; RecursiveVisitor.prototype.visitTextAttribute = function (attribute) { }; RecursiveVisitor.prototype.visitBoundAttribute = function (attribute) { }; RecursiveVisitor.prototype.visitBoundEvent = function (attribute) { }; RecursiveVisitor.prototype.visitText = function (text) { }; RecursiveVisitor.prototype.visitBoundText = function (text) { }; RecursiveVisitor.prototype.visitIcu = function (icu) { }; return RecursiveVisitor; }()); var TransformVisitor = /** @class */ (function () { function TransformVisitor() { } TransformVisitor.prototype.visitElement = function (element) { var newAttributes = transformAll(this, element.attributes); var newInputs = transformAll(this, element.inputs); var newOutputs = transformAll(this, element.outputs); var newChildren = transformAll(this, element.children); var newReferences = transformAll(this, element.references); if (newAttributes != element.attributes || newInputs != element.inputs || newOutputs != element.outputs || newChildren != element.children || newReferences != element.references) { return new Element(element.name, newAttributes, newInputs, newOutputs, newChildren, newReferences, element.sourceSpan, element.startSourceSpan, element.endSourceSpan); } return element; }; TransformVisitor.prototype.visitTemplate = function (template) { var newAttributes = transformAll(this, template.attributes); var newInputs = transformAll(this, template.inputs); var newOutputs = transformAll(this, template.outputs); var newTemplateAttrs = transformAll(this, template.templateAttrs); var newChildren = transformAll(this, template.children); var newReferences = transformAll(this, template.references); var newVariables = transformAll(this, template.variables); if (newAttributes != template.attributes || newInputs != template.inputs || newOutputs != template.outputs || newTemplateAttrs != template.templateAttrs || newChildren != template.children || newReferences != template.references || newVariables != template.variables) { return new Template(template.tagName, newAttributes, newInputs, newOutputs, newTemplateAttrs, newChildren, newReferences, newVariables, template.sourceSpan, template.startSourceSpan, template.endSourceSpan); } return template; }; TransformVisitor.prototype.visitContent = function (content) { return content; }; TransformVisitor.prototype.visitVariable = function (variable) { return variable; }; TransformVisitor.prototype.visitReference = function (reference) { return reference; }; TransformVisitor.prototype.visitTextAttribute = function (attribute) { return attribute; }; TransformVisitor.prototype.visitBoundAttribute = function (attribute) { return attribute; }; TransformVisitor.prototype.visitBoundEvent = function (attribute) { return attribute; }; TransformVisitor.prototype.visitText = function (text) { return text; }; TransformVisitor.prototype.visitBoundText = function (text) { return text; }; TransformVisitor.prototype.visitIcu = function (icu) { return icu; }; return TransformVisitor; }()); function visitAll(visitor, nodes) { var e_1, _a, e_2, _b; var result = []; if (visitor.visit) { try { for (var nodes_1 = __values(nodes), nodes_1_1 = nodes_1.next(); !nodes_1_1.done; nodes_1_1 = nodes_1.next()) { var node = nodes_1_1.value; var newNode = visitor.visit(node) || node.visit(visitor); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (nodes_1_1 && !nodes_1_1.done && (_a = nodes_1.return)) _a.call(nodes_1); } finally { if (e_1) throw e_1.error; } } } else { try { for (var nodes_2 = __values(nodes), nodes_2_1 = nodes_2.next(); !nodes_2_1.done; nodes_2_1 = nodes_2.next()) { var node = nodes_2_1.value; var newNode = node.visit(visitor); if (newNode) { result.push(newNode); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (nodes_2_1 && !nodes_2_1.done && (_b = nodes_2.return)) _b.call(nodes_2); } finally { if (e_2) throw e_2.error; } } } return result; } function transformAll(visitor, nodes) { var e_3, _a; var result = []; var changed = false; try { for (var nodes_3 = __values(nodes), nodes_3_1 = nodes_3.next(); !nodes_3_1.done; nodes_3_1 = nodes_3.next()) { var node = nodes_3_1.value; var newNode = node.visit(visitor); if (newNode) { result.push(newNode); } changed = changed || newNode != node; } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (nodes_3_1 && !nodes_3_1.done && (_a = nodes_3.return)) _a.call(nodes_3); } finally { if (e_3) throw e_3.error; } } return changed ? result : nodes; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var Message = /** @class */ (function () { /** * @param nodes message AST * @param placeholders maps placeholder names to static content and their source spans * @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages) * @param meaning * @param description * @param customId */ function Message(nodes, placeholders, placeholderToMessage, meaning, description, customId) { this.nodes = nodes; this.placeholders = placeholders; this.placeholderToMessage = placeholderToMessage; this.meaning = meaning; this.description = description; this.customId = customId; this.id = this.customId; /** The ids to use if there are no custom id and if `i18nLegacyMessageIdFormat` is not empty */ this.legacyIds = []; if (nodes.length) { this.sources = [{ filePath: nodes[0].sourceSpan.start.file.url, startLine: nodes[0].sourceSpan.start.line + 1, startCol: nodes[0].sourceSpan.start.col + 1, endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1, endCol: nodes[0].sourceSpan.start.col + 1 }]; } else { this.sources = []; } } return Message; }()); var Text$1 = /** @class */ (function () { function Text(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return Text; }()); // TODO(vicb): do we really need this node (vs an array) ? var Container = /** @class */ (function () { function Container(children, sourceSpan) { this.children = children; this.sourceSpan = sourceSpan; } Container.prototype.visit = function (visitor, context) { return visitor.visitContainer(this, context); }; return Container; }()); var Icu$1 = /** @class */ (function () { function Icu(expression, type, cases, sourceSpan) { this.expression = expression; this.type = type; this.cases = cases; this.sourceSpan = sourceSpan; } Icu.prototype.visit = function (visitor, context) { return visitor.visitIcu(this, context); }; return Icu; }()); var TagPlaceholder = /** @class */ (function () { function TagPlaceholder(tag, attrs, startName, closeName, children, isVoid, // TODO sourceSpan should cover all (we need a startSourceSpan and endSourceSpan) sourceSpan, startSourceSpan, endSourceSpan) { this.tag = tag; this.attrs = attrs; this.startName = startName; this.closeName = closeName; this.children = children; this.isVoid = isVoid; this.sourceSpan = sourceSpan; this.startSourceSpan = startSourceSpan; this.endSourceSpan = endSourceSpan; } TagPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitTagPlaceholder(this, context); }; return TagPlaceholder; }()); var Placeholder = /** @class */ (function () { function Placeholder(value, name, sourceSpan) { this.value = value; this.name = name; this.sourceSpan = sourceSpan; } Placeholder.prototype.visit = function (visitor, context) { return visitor.visitPlaceholder(this, context); }; return Placeholder; }()); var IcuPlaceholder = /** @class */ (function () { function IcuPlaceholder(value, name, sourceSpan) { this.value = value; this.name = name; this.sourceSpan = sourceSpan; } IcuPlaceholder.prototype.visit = function (visitor, context) { return visitor.visitIcuPlaceholder(this, context); }; return IcuPlaceholder; }()); // Clone the AST var CloneVisitor = /** @class */ (function () { function CloneVisitor() { } CloneVisitor.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); }; CloneVisitor.prototype.visitContainer = function (container, context) { var _this = this; var children = container.children.map(function (n) { return n.visit(_this, context); }); return new Container(children, container.sourceSpan); }; CloneVisitor.prototype.visitIcu = function (icu, context) { var _this = this; var cases = {}; Object.keys(icu.cases).forEach(function (key) { return cases[key] = icu.cases[key].visit(_this, context); }); var msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan); msg.expressionPlaceholder = icu.expressionPlaceholder; return msg; }; CloneVisitor.prototype.visitTagPlaceholder = function (ph, context) { var _this = this; var children = ph.children.map(function (n) { return n.visit(_this, context); }); return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan); }; CloneVisitor.prototype.visitPlaceholder = function (ph, context) { return new Placeholder(ph.value, ph.name, ph.sourceSpan); }; CloneVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan); }; return CloneVisitor; }()); // Visit all the nodes recursively var RecurseVisitor = /** @class */ (function () { function RecurseVisitor() { } RecurseVisitor.prototype.visitText = function (text, context) { }; RecurseVisitor.prototype.visitContainer = function (container, context) { var _this = this; container.children.forEach(function (child) { return child.visit(_this); }); }; RecurseVisitor.prototype.visitIcu = function (icu, context) { var _this = this; Object.keys(icu.cases).forEach(function (k) { icu.cases[k].visit(_this); }); }; RecurseVisitor.prototype.visitTagPlaceholder = function (ph, context) { var _this = this; ph.children.forEach(function (child) { return child.visit(_this); }); }; RecurseVisitor.prototype.visitPlaceholder = function (ph, context) { }; RecurseVisitor.prototype.visitIcuPlaceholder = function (ph, context) { }; return RecurseVisitor; }()); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Represents a big integer using a buffer of its individual digits, with the least significant * digit stored at the beginning of the array (little endian). * * For performance reasons, each instance is mutable. The addition operation can be done in-place * to reduce memory pressure of allocation for the digits array. */ var BigInteger = /** @class */ (function () { /** * Creates a big integer using its individual digits in little endian storage. */ function BigInteger(digits) { this.digits = digits; } BigInteger.zero = function () { return new BigInteger([0]); }; BigInteger.one = function () { return new BigInteger([1]); }; /** * Creates a clone of this instance. */ BigInteger.prototype.clone = function () { return new BigInteger(this.digits.slice()); }; /** * Returns a new big integer with the sum of `this` and `other` as its value. This does not mutate * `this` but instead returns a new instance, unlike `addToSelf`. */ BigInteger.prototype.add = function (other) { var result = this.clone(); result.addToSelf(other); return result; }; /** * Adds `other` to the instance itself, thereby mutating its value. */ BigInteger.prototype.addToSelf = function (other) { var maxNrOfDigits = Math.max(this.digits.length, other.digits.length); var carry = 0; for (var i = 0; i < maxNrOfDigits; i++) { var digitSum = carry; if (i < this.digits.length) { digitSum += this.digits[i]; } if (i < other.digits.length) { digitSum += other.digits[i]; } if (digitSum >= 10) { this.digits[i] = digitSum - 10; carry = 1; } else { this.digits[i] = digitSum; carry = 0; } } // Apply a remaining carry if needed. if (carry > 0) { this.digits[maxNrOfDigits] = 1; } }; /** * Builds the decimal string representation of the big integer. As this is stored in * little endian, the digits are concatenated in reverse order. */ BigInteger.prototype.toString = function () { var res = ''; for (var i = this.digits.length - 1; i >= 0; i--) { res += this.digits[i]; } return res; }; return BigInteger; }()); /** * Represents a big integer which is optimized for multiplication operations, as its power-of-twos * are memoized. See `multiplyBy()` for details on the multiplication algorithm. */ var BigIntForMultiplication = /** @class */ (function () { function BigIntForMultiplication(value) { this.powerOfTwos = [value]; } /** * Returns the big integer itself. */ BigIntForMultiplication.prototype.getValue = function () { return this.powerOfTwos[0]; }; /** * Computes the value for `num * b`, where `num` is a JS number and `b` is a big integer. The * value for `b` is represented by a storage model that is optimized for this computation. * * This operation is implemented in N(log2(num)) by continuous halving of the number, where the * least-significant bit (LSB) is tested in each iteration. If the bit is set, the bit's index is * used as exponent into the power-of-two multiplication of `b`. * * As an example, consider the multiplication num=42, b=1337. In binary 42 is 0b00101010 and the * algorithm unrolls into the following iterations: * * Iteration | num | LSB | b * 2^iter | Add? | product * -----------|------------|------|------------|------|-------- * 0 | 0b00101010 | 0 | 1337 | No | 0 * 1 | 0b00010101 | 1 | 2674 | Yes | 2674 * 2 | 0b00001010 | 0 | 5348 | No | 2674 * 3 | 0b00000101 | 1 | 10696 | Yes | 13370 * 4 | 0b00000010 | 0 | 21392 | No | 13370 * 5 | 0b00000001 | 1 | 42784 | Yes | 56154 * 6 | 0b00000000 | 0 | 85568 | No | 56154 * * The computed product of 56154 is indeed the correct result. * * The `BigIntForMultiplication` representation for a big integer provides memoized access to the * power-of-two values to reduce the workload in computing those values. */ BigIntForMultiplication.prototype.multiplyBy = function (num) { var product = BigInteger.zero(); this.multiplyByAndAddTo(num, product); return product; }; /** * See `multiplyBy()` for details. This function allows for the computed product to be added * directly to the provided result big integer. */ BigIntForMultiplication.prototype.multiplyByAndAddTo = function (num, result) { for (var exponent = 0; num !== 0; num = num >>> 1, exponent++) { if (num & 1) { var value = this.getMultipliedByPowerOfTwo(exponent); result.addToSelf(value); } } }; /** * Computes and memoizes the big integer value for `this.number * 2^exponent`. */ BigIntForMultiplication.prototype.getMultipliedByPowerOfTwo = function (exponent) { // Compute the powers up until the requested exponent, where each value is computed from its // predecessor. This is simple as `this.number * 2^(exponent - 1)` only has to be doubled (i.e. // added to itself) to reach `this.number * 2^exponent`. for (var i = this.powerOfTwos.length; i <= exponent; i++) { var previousPower = this.powerOfTwos[i - 1]; this.powerOfTwos[i] = previousPower.add(previousPower); } return this.powerOfTwos[exponent]; }; return BigIntForMultiplication; }()); /** * Represents an exponentiation operation for the provided base, of which exponents are computed and * memoized. The results are represented by a `BigIntForMultiplication` which is tailored for * multiplication operations by memoizing the power-of-twos. This effectively results in a matrix * representation that is lazily computed upon request. */ var BigIntExponentiation = /** @class */ (function () { function BigIntExponentiation(base) { this.base = base; this.exponents = [new BigIntForMultiplication(BigInteger.one())]; } /** * Compute the value for `this.base^exponent`, resulting in a big integer that is optimized for * further multiplication operations. */ BigIntExponentiation.prototype.toThePowerOf = function (exponent) { // Compute the results up until the requested exponent, where every value is computed from its // predecessor. This is because `this.base^(exponent - 1)` only has to be multiplied by `base` // to reach `this.base^exponent`. for (var i = this.exponents.length; i <= exponent; i++) { var value = this.exponents[i - 1].multiplyBy(this.base); this.exponents[i] = new BigIntForMultiplication(value); } return this.exponents[exponent]; }; return BigIntExponentiation; }()); /** * Return the message id or compute it using the XLIFF1 digest. */ function digest(message) { return message.id || computeDigest(message); } /** * Compute the message id using the XLIFF1 digest. */ function computeDigest(message) { return sha1(serializeNodes(message.nodes).join('') + ("[" + message.meaning + "]")); } /** * Return the message id or compute it using the XLIFF2/XMB/$localize digest. */ function decimalDigest(message) { return message.id || computeDecimalDigest(message); } /** * Compute the message id using the XLIFF2/XMB/$localize digest. */ function computeDecimalDigest(message) { var visitor = new _SerializerIgnoreIcuExpVisitor(); var parts = message.nodes.map(function (a) { return a.visit(visitor, null); }); return computeMsgId(parts.join(''), message.meaning); } /** * Serialize the i18n ast to something xml-like in order to generate an UID. * * The visitor is also used in the i18n parser tests * * @internal */ var _SerializerVisitor = /** @class */ (function () { function _SerializerVisitor() { } _SerializerVisitor.prototype.visitText = function (text, context) { return text.value; }; _SerializerVisitor.prototype.visitContainer = function (container, context) { var _this = this; return "[" + container.children.map(function (child) { return child.visit(_this); }).join(', ') + "]"; }; _SerializerVisitor.prototype.visitIcu = function (icu, context) { var _this = this; var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; }); return "{" + icu.expression + ", " + icu.type + ", " + strCases.join(', ') + "}"; }; _SerializerVisitor.prototype.visitTagPlaceholder = function (ph, context) { var _this = this; return ph.isVoid ? "" : "" + ph.children.map(function (child) { return child.visit(_this); }).join(', ') + ""; }; _SerializerVisitor.prototype.visitPlaceholder = function (ph, context) { return ph.value ? "" + ph.value + "" : ""; }; _SerializerVisitor.prototype.visitIcuPlaceholder = function (ph, context) { return "" + ph.value.visit(this) + ""; }; return _SerializerVisitor; }()); var serializerVisitor = new _SerializerVisitor(); function serializeNodes(nodes) { return nodes.map(function (a) { return a.visit(serializerVisitor, null); }); } /** * Serialize the i18n ast to something xml-like in order to generate an UID. * * Ignore the ICU expressions so that message IDs stays identical if only the expression changes. * * @internal */ var _SerializerIgnoreIcuExpVisitor = /** @class */ (function (_super) { __extends(_SerializerIgnoreIcuExpVisitor, _super); function _SerializerIgnoreIcuExpVisitor() { return _super !== null && _super.apply(this, arguments) || this; } _SerializerIgnoreIcuExpVisitor.prototype.visitIcu = function (icu, context) { var _this = this; var strCases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; }); // Do not take the expression into account return "{" + icu.type + ", " + strCases.join(', ') + "}"; }; return _SerializerIgnoreIcuExpVisitor; }(_SerializerVisitor)); /** * Compute the SHA1 of the given string * * see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf * * WARNING: this function has not been designed not tested with security in mind. * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT. */ function sha1(str) { var utf8 = utf8Encode(str); var words32 = bytesToWords32(utf8, Endian.Big); var len = utf8.length * 8; var w = newArray(80); var a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476, e = 0xc3d2e1f0; words32[len >> 5] |= 0x80 << (24 - len % 32); words32[((len + 64 >> 9) << 4) + 15] = len; for (var i = 0; i < words32.length; i += 16) { var h0 = a, h1 = b, h2 = c, h3 = d, h4 = e; for (var j = 0; j < 80; j++) { if (j < 16) { w[j] = words32[i + j]; } else { w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1); } var fkVal = fk(j, b, c, d); var f = fkVal[0]; var k = fkVal[1]; var temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32); e = d; d = c; c = rol32(b, 30); b = a; a = temp; } a = add32(a, h0); b = add32(b, h1); c = add32(c, h2); d = add32(d, h3); e = add32(e, h4); } return bytesToHexString(words32ToByteString([a, b, c, d, e])); } function fk(index, b, c, d) { if (index < 20) { return [(b & c) | (~b & d), 0x5a827999]; } if (index < 40) { return [b ^ c ^ d, 0x6ed9eba1]; } if (index < 60) { return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]; } return [b ^ c ^ d, 0xca62c1d6]; } /** * Compute the fingerprint of the given string * * The output is 64 bit number encoded as a decimal string * * based on: * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java */ function fingerprint(str) { var utf8 = utf8Encode(str); var hi = hash32(utf8, 0); var lo = hash32(utf8, 102072); if (hi == 0 && (lo == 0 || lo == 1)) { hi = hi ^ 0x130f9bef; lo = lo ^ -0x6b5f56d8; } return [hi, lo]; } function computeMsgId(msg, meaning) { if (meaning === void 0) { meaning = ''; } var msgFingerprint = fingerprint(msg); if (meaning) { var meaningFingerprint = fingerprint(meaning); msgFingerprint = add64(rol64(msgFingerprint, 1), meaningFingerprint); } var hi = msgFingerprint[0]; var lo = msgFingerprint[1]; return wordsToDecimalString(hi & 0x7fffffff, lo); } function hash32(bytes, c) { var a = 0x9e3779b9, b = 0x9e3779b9; var i; var len = bytes.length; for (i = 0; i + 12 <= len; i += 12) { a = add32(a, wordAt(bytes, i, Endian.Little)); b = add32(b, wordAt(bytes, i + 4, Endian.Little)); c = add32(c, wordAt(bytes, i + 8, Endian.Little)); var res = mix(a, b, c); a = res[0], b = res[1], c = res[2]; } a = add32(a, wordAt(bytes, i, Endian.Little)); b = add32(b, wordAt(bytes, i + 4, Endian.Little)); // the first byte of c is reserved for the length c = add32(c, len); c = add32(c, wordAt(bytes, i + 8, Endian.Little) << 8); return mix(a, b, c)[2]; } // clang-format off function mix(a, b, c) { a = sub32(a, b); a = sub32(a, c); a ^= c >>> 13; b = sub32(b, c); b = sub32(b, a); b ^= a << 8; c = sub32(c, a); c = sub32(c, b); c ^= b >>> 13; a = sub32(a, b); a = sub32(a, c); a ^= c >>> 12; b = sub32(b, c); b = sub32(b, a); b ^= a << 16; c = sub32(c, a); c = sub32(c, b); c ^= b >>> 5; a = sub32(a, b); a = sub32(a, c); a ^= c >>> 3; b = sub32(b, c); b = sub32(b, a); b ^= a << 10; c = sub32(c, a); c = sub32(c, b); c ^= b >>> 15; return [a, b, c]; } // clang-format on // Utils var Endian; (function (Endian) { Endian[Endian["Little"] = 0] = "Little"; Endian[Endian["Big"] = 1] = "Big"; })(Endian || (Endian = {})); function add32(a, b) { return add32to64(a, b)[1]; } function add32to64(a, b) { var low = (a & 0xffff) + (b & 0xffff); var high = (a >>> 16) + (b >>> 16) + (low >>> 16); return [high >>> 16, (high << 16) | (low & 0xffff)]; } function add64(a, b) { var ah = a[0], al = a[1]; var bh = b[0], bl = b[1]; var result = add32to64(al, bl); var carry = result[0]; var l = result[1]; var h = add32(add32(ah, bh), carry); return [h, l]; } function sub32(a, b) { var low = (a & 0xffff) - (b & 0xffff); var high = (a >> 16) - (b >> 16) + (low >> 16); return (high << 16) | (low & 0xffff); } // Rotate a 32b number left `count` position function rol32(a, count) { return (a << count) | (a >>> (32 - count)); } // Rotate a 64b number left `count` position function rol64(num, count) { var hi = num[0], lo = num[1]; var h = (hi << count) | (lo >>> (32 - count)); var l = (lo << count) | (hi >>> (32 - count)); return [h, l]; } function bytesToWords32(bytes, endian) { var size = (bytes.length + 3) >>> 2; var words32 = []; for (var i = 0; i < size; i++) { words32[i] = wordAt(bytes, i * 4, endian); } return words32; } function byteAt(bytes, index) { return index >= bytes.length ? 0 : bytes[index]; } function wordAt(bytes, index, endian) { var word = 0; if (endian === Endian.Big) { for (var i = 0; i < 4; i++) { word += byteAt(bytes, index + i) << (24 - 8 * i); } } else { for (var i = 0; i < 4; i++) { word += byteAt(bytes, index + i) << 8 * i; } } return word; } function words32ToByteString(words32) { return words32.reduce(function (bytes, word) { return bytes.concat(word32ToByteString(word)); }, []); } function word32ToByteString(word) { var bytes = []; for (var i = 0; i < 4; i++) { bytes.push((word >>> 8 * (3 - i)) & 0xff); } return bytes; } function bytesToHexString(bytes) { var hex = ''; for (var i = 0; i < bytes.length; i++) { var b = byteAt(bytes, i); hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16); } return hex.toLowerCase(); } /** * Create a shared exponentiation pool for base-256 computations. This shared pool provides memoized * power-of-256 results with memoized power-of-two computations for efficient multiplication. * * For our purposes, this can be safely stored as a global without memory concerns. The reason is * that we encode two words, so only need the 0th (for the low word) and 4th (for the high word) * exponent. */ var base256 = new BigIntExponentiation(256); /** * Represents two 32-bit words as a single decimal number. This requires a big integer storage * model as JS numbers are not accurate enough to represent the 64-bit number. * * Based on https://www.danvk.org/hex2dec.html */ function wordsToDecimalString(hi, lo) { // Encode the four bytes in lo in the lower digits of the decimal number. // Note: the multiplication results in lo itself but represented by a big integer using its // decimal digits. var decimal = base256.toThePowerOf(0).multiplyBy(lo); // Encode the four bytes in hi above the four lo bytes. lo is a maximum of (2^8)^4, which is why // this multiplication factor is applied. base256.toThePowerOf(4).multiplyByAndAddTo(hi, decimal); return decimal.toString(); } var Serializer = /** @class */ (function () { function Serializer() { } // Creates a name mapper, see `PlaceholderMapper` // Returning `null` means that no name mapping is used. Serializer.prototype.createNameMapper = function (message) { return null; }; return Serializer; }()); /** * A simple mapper that take a function to transform an internal name to a public name */ var SimplePlaceholderMapper = /** @class */ (function (_super) { __extends(SimplePlaceholderMapper, _super); // create a mapping from the message function SimplePlaceholderMapper(message, mapName) { var _this = _super.call(this) || this; _this.mapName = mapName; _this.internalToPublic = {}; _this.publicToNextId = {}; _this.publicToInternal = {}; message.nodes.forEach(function (node) { return node.visit(_this); }); return _this; } SimplePlaceholderMapper.prototype.toPublicName = function (internalName) { return this.internalToPublic.hasOwnProperty(internalName) ? this.internalToPublic[internalName] : null; }; SimplePlaceholderMapper.prototype.toInternalName = function (publicName) { return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] : null; }; SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; }; SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.startName); _super.prototype.visitTagPlaceholder.call(this, ph, context); this.visitPlaceholderName(ph.closeName); }; SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); }; SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); }; // XMB placeholders could only contains A-Z, 0-9 and _ SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) { if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) { return; } var publicName = this.mapName(internalName); if (this.publicToInternal.hasOwnProperty(publicName)) { // Create a new XMB when it has already been used var nextId = this.publicToNextId[publicName]; this.publicToNextId[publicName] = nextId + 1; publicName = publicName + "_" + nextId; } else { this.publicToNextId[publicName] = 1; } this.internalToPublic[internalName] = publicName; this.publicToInternal[publicName] = internalName; }; return SimplePlaceholderMapper; }(RecurseVisitor)); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _Visitor = /** @class */ (function () { function _Visitor() { } _Visitor.prototype.visitTag = function (tag) { var _this = this; var strAttrs = this._serializeAttributes(tag.attrs); if (tag.children.length == 0) { return "<" + tag.name + strAttrs + "/>"; } var strChildren = tag.children.map(function (node) { return node.visit(_this); }); return "<" + tag.name + strAttrs + ">" + strChildren.join('') + ""; }; _Visitor.prototype.visitText = function (text) { return text.value; }; _Visitor.prototype.visitDeclaration = function (decl) { return ""; }; _Visitor.prototype._serializeAttributes = function (attrs) { var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' '); return strAttrs.length > 0 ? ' ' + strAttrs : ''; }; _Visitor.prototype.visitDoctype = function (doctype) { return ""; }; return _Visitor; }()); var _visitor = new _Visitor(); function serialize(nodes) { return nodes.map(function (node) { return node.visit(_visitor); }).join(''); } var Declaration = /** @class */ (function () { function Declaration(unescapedAttrs) { var _this = this; this.attrs = {}; Object.keys(unescapedAttrs).forEach(function (k) { _this.attrs[k] = escapeXml(unescapedAttrs[k]); }); } Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); }; return Declaration; }()); var Doctype = /** @class */ (function () { function Doctype(rootTag, dtd) { this.rootTag = rootTag; this.dtd = dtd; } Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); }; return Doctype; }()); var Tag = /** @class */ (function () { function Tag(name, unescapedAttrs, children) { var _this = this; if (unescapedAttrs === void 0) { unescapedAttrs = {}; } if (children === void 0) { children = []; } this.name = name; this.children = children; this.attrs = {}; Object.keys(unescapedAttrs).forEach(function (k) { _this.attrs[k] = escapeXml(unescapedAttrs[k]); }); } Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); }; return Tag; }()); var Text$2 = /** @class */ (function () { function Text(unescapedValue) { this.value = escapeXml(unescapedValue); } Text.prototype.visit = function (visitor) { return visitor.visitText(this); }; return Text; }()); var CR = /** @class */ (function (_super) { __extends(CR, _super); function CR(ws) { if (ws === void 0) { ws = 0; } return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this; } return CR; }(Text$2)); var _ESCAPED_CHARS = [ [/&/g, '&'], [/"/g, '"'], [/'/g, '''], [//g, '>'], ]; // Escape `_ESCAPED_CHARS` characters in the given text with encoded entities function escapeXml(text) { return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text); } var _MESSAGES_TAG = 'messagebundle'; var _MESSAGE_TAG = 'msg'; var _PLACEHOLDER_TAG = 'ph'; var _EXAMPLE_TAG = 'ex'; var _SOURCE_TAG = 'source'; var _DOCTYPE = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; var Xmb = /** @class */ (function (_super) { __extends(Xmb, _super); function Xmb() { return _super !== null && _super.apply(this, arguments) || this; } Xmb.prototype.write = function (messages, locale) { var exampleVisitor = new ExampleVisitor(); var visitor = new _Visitor$1(); var rootNode = new Tag(_MESSAGES_TAG); messages.forEach(function (message) { var attrs = { id: message.id }; if (message.description) { attrs['desc'] = message.description; } if (message.meaning) { attrs['meaning'] = message.meaning; } var sourceTags = []; message.sources.forEach(function (source) { sourceTags.push(new Tag(_SOURCE_TAG, {}, [new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))])); }); rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, __spreadArray(__spreadArray([], __read(sourceTags)), __read(visitor.serialize(message.nodes))))); }); rootNode.children.push(new CR()); return serialize([ new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), new Doctype(_MESSAGES_TAG, _DOCTYPE), new CR(), exampleVisitor.addDefaultExamples(rootNode), new CR(), ]); }; Xmb.prototype.load = function (content, url) { throw new Error('Unsupported'); }; Xmb.prototype.digest = function (message) { return digest$1(message); }; Xmb.prototype.createNameMapper = function (message) { return new SimplePlaceholderMapper(message, toPublicName); }; return Xmb; }(Serializer)); var _Visitor$1 = /** @class */ (function () { function _Visitor() { } _Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; }; _Visitor.prototype.visitContainer = function (container, context) { var _this = this; var nodes = []; container.children.forEach(function (node) { return nodes.push.apply(nodes, __spreadArray([], __read(node.visit(_this)))); }); return nodes; }; _Visitor.prototype.visitIcu = function (icu, context) { var _this = this; var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")]; Object.keys(icu.cases).forEach(function (c) { nodes.push.apply(nodes, __spreadArray(__spreadArray([new Text$2(c + " {")], __read(icu.cases[c].visit(_this))), [new Text$2("} ")])); }); nodes.push(new Text$2("}")); return nodes; }; _Visitor.prototype.visitTagPlaceholder = function (ph, context) { var startTagAsText = new Text$2("<" + ph.tag + ">"); var startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]); // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. var startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]); if (ph.isVoid) { // void tags have no children nor closing tags return [startTagPh]; } var closeTagAsText = new Text$2(""); var closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]); // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. var closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]); return __spreadArray(__spreadArray([startTagPh], __read(this.serialize(ph.children))), [closeTagPh]); }; _Visitor.prototype.visitPlaceholder = function (ph, context) { var interpolationAsText = new Text$2("{{" + ph.value + "}}"); // Example tag needs to be not-empty for TC. var exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]); return [ // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText]) ]; }; _Visitor.prototype.visitIcuPlaceholder = function (ph, context) { var icuExpression = ph.value.expression; var icuType = ph.value.type; var icuCases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' '); var icuAsText = new Text$2("{" + icuExpression + ", " + icuType + ", " + icuCases + "}"); var exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]); return [ // TC requires PH to have a non empty EX, and uses the text node to show the "original" value. new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText]) ]; }; _Visitor.prototype.serialize = function (nodes) { var _this = this; return [].concat.apply([], __spreadArray([], __read(nodes.map(function (node) { return node.visit(_this); })))); }; return _Visitor; }()); function digest$1(message) { return decimalDigest(message); } // TC requires at least one non-empty example on placeholders var ExampleVisitor = /** @class */ (function () { function ExampleVisitor() { } ExampleVisitor.prototype.addDefaultExamples = function (node) { node.visit(this); return node; }; ExampleVisitor.prototype.visitTag = function (tag) { var _this = this; if (tag.name === _PLACEHOLDER_TAG) { if (!tag.children || tag.children.length == 0) { var exText = new Text$2(tag.attrs['name'] || '...'); tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])]; } } else if (tag.children) { tag.children.forEach(function (node) { return node.visit(_this); }); } }; ExampleVisitor.prototype.visitText = function (text) { }; ExampleVisitor.prototype.visitDeclaration = function (decl) { }; ExampleVisitor.prototype.visitDoctype = function (doctype) { }; return ExampleVisitor; }()); // XMB/XTB placeholders can only contain A-Z, 0-9 and _ function toPublicName(internalName) { return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_'); } /* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */ var CLOSURE_TRANSLATION_VAR_PREFIX = 'MSG_'; /** * Prefix for non-`goog.getMsg` i18n-related vars. * Note: the prefix uses lowercase characters intentionally due to a Closure behavior that * considers variables like `I18N_0` as constants and throws an error when their value changes. */ var TRANSLATION_VAR_PREFIX = 'i18n_'; /** Name of the i18n attributes **/ var I18N_ATTR = 'i18n'; var I18N_ATTR_PREFIX = 'i18n-'; /** Prefix of var expressions used in ICUs */ var I18N_ICU_VAR_PREFIX = 'VAR_'; /** Prefix of ICU expressions for post processing */ var I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_'; /** Placeholder wrapper for i18n expressions **/ var I18N_PLACEHOLDER_SYMBOL = '�'; function isI18nAttribute(name) { return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX); } function isI18nRootNode(meta) { return meta instanceof Message; } function isSingleI18nIcu(meta) { return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1; } function hasI18nMeta(node) { return !!node.i18n; } function hasI18nAttrs(element) { return element.attrs.some(function (attr) { return isI18nAttribute(attr.name); }); } function icuFromI18nMessage(message) { return message.nodes[0]; } function wrapI18nPlaceholder(content, contextId) { if (contextId === void 0) { contextId = 0; } var blockId = contextId > 0 ? ":" + contextId : ''; return "" + I18N_PLACEHOLDER_SYMBOL + content + blockId + I18N_PLACEHOLDER_SYMBOL; } function assembleI18nBoundString(strings, bindingStartIndex, contextId) { if (bindingStartIndex === void 0) { bindingStartIndex = 0; } if (contextId === void 0) { contextId = 0; } if (!strings.length) return ''; var acc = ''; var lastIdx = strings.length - 1; for (var i = 0; i < lastIdx; i++) { acc += "" + strings[i] + wrapI18nPlaceholder(bindingStartIndex + i, contextId); } acc += strings[lastIdx]; return acc; } function getSeqNumberGenerator(startsAt) { if (startsAt === void 0) { startsAt = 0; } var current = startsAt; return function () { return current++; }; } function placeholdersToParams(placeholders) { var params = {}; placeholders.forEach(function (values, key) { params[key] = literal(values.length > 1 ? "[" + values.join('|') + "]" : values[0]); }); return params; } function updatePlaceholderMap(map, name) { var values = []; for (var _i = 2; _i < arguments.length; _i++) { values[_i - 2] = arguments[_i]; } var current = map.get(name) || []; current.push.apply(current, __spreadArray([], __read(values))); map.set(name, current); } function assembleBoundTextPlaceholders(meta, bindingStartIndex, contextId) { if (bindingStartIndex === void 0) { bindingStartIndex = 0; } if (contextId === void 0) { contextId = 0; } var startIdx = bindingStartIndex; var placeholders = new Map(); var node = meta instanceof Message ? meta.nodes.find(function (node) { return node instanceof Container; }) : meta; if (node) { node .children .filter(function (child) { return child instanceof Placeholder; }) .forEach(function (child, idx) { var content = wrapI18nPlaceholder(startIdx + idx, contextId); updatePlaceholderMap(placeholders, child.name, content); }); } return placeholders; } /** * Format the placeholder names in a map of placeholders to expressions. * * The placeholder names are converted from "internal" format (e.g. `START_TAG_DIV_1`) to "external" * format (e.g. `startTagDiv_1`). * * @param params A map of placeholder names to expressions. * @param useCamelCase whether to camelCase the placeholder name when formatting. * @returns A new map of formatted placeholder names to expressions. */ function i18nFormatPlaceholderNames(params, useCamelCase) { if (params === void 0) { params = {}; } var _params = {}; if (params && Object.keys(params).length) { Object.keys(params).forEach(function (key) { return _params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]; }); } return _params; } /** * Converts internal placeholder names to public-facing format * (for example to use in goog.getMsg call). * Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`. * * @param name The placeholder name that should be formatted * @returns Formatted placeholder name */ function formatI18nPlaceholderName(name, useCamelCase) { if (useCamelCase === void 0) { useCamelCase = true; } var publicName = toPublicName(name); if (!useCamelCase) { return publicName; } var chunks = publicName.split('_'); if (chunks.length === 1) { // if no "_" found - just lowercase the value return name.toLowerCase(); } var postfix; // eject last element if it's a number if (/^\d+$/.test(chunks[chunks.length - 1])) { postfix = chunks.pop(); } var raw = chunks.shift().toLowerCase(); if (chunks.length) { raw += chunks.map(function (c) { return c.charAt(0).toUpperCase() + c.slice(1).toLowerCase(); }).join(''); } return postfix ? raw + "_" + postfix : raw; } /** * Generates a prefix for translation const name. * * @param extra Additional local prefix that should be injected into translation var name * @returns Complete translation const prefix */ function getTranslationConstPrefix(extra) { return ("" + CLOSURE_TRANSLATION_VAR_PREFIX + extra).toUpperCase(); } /** * Generate AST to declare a variable. E.g. `var I18N_1;`. * @param variable the name of the variable to declare. */ function declareI18nVariable(variable) { return new DeclareVarStmt(variable.name, undefined, INFERRED_TYPE, undefined, variable.sourceSpan); } /** * Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in * quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may * bot work in some cases when object keys are mangled by minifier. * * TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with * inputs that contain potentially unsafe chars. */ var UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/; /** Name of the temporary to use during data binding */ var TEMPORARY_NAME = '_t'; /** Name of the context parameter passed into a template function */ var CONTEXT_NAME = 'ctx'; /** Name of the RenderFlag passed into a template function */ var RENDER_FLAGS = 'rf'; /** The prefix reference variables */ var REFERENCE_PREFIX = '_r'; /** The name of the implicit context reference */ var IMPLICIT_REFERENCE = '$implicit'; /** Non bindable attribute name **/ var NON_BINDABLE_ATTR = 'ngNonBindable'; /** Name for the variable keeping track of the context returned by `ɵɵrestoreView`. */ var RESTORED_VIEW_CONTEXT_NAME = 'restoredCtx'; /** * Creates an allocator for a temporary variable. * * A variable declaration is added to the statements the first time the allocator is invoked. */ function temporaryAllocator(statements, name) { var temp = null; return function () { if (!temp) { statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE)); temp = variable(name); } return temp; }; } function unsupported(feature) { if (this) { throw new Error("Builder " + this.constructor.name + " doesn't support " + feature + " yet"); } throw new Error("Feature " + feature + " is not supported yet"); } function invalid$1(arg) { throw new Error("Invalid state: Visitor " + this.constructor.name + " doesn't handle " + arg.constructor.name); } function asLiteral(value) { if (Array.isArray(value)) { return literalArr(value.map(asLiteral)); } return literal(value, INFERRED_TYPE); } function conditionallyCreateMapObjectLiteral(keys, keepDeclared) { if (Object.getOwnPropertyNames(keys).length > 0) { return mapToExpression(keys, keepDeclared); } return null; } function mapToExpression(map, keepDeclared) { return literalMap(Object.getOwnPropertyNames(map).map(function (key) { var _a, _b; // canonical syntax: `dirProp: publicProp` // if there is no `:`, use dirProp = elProp var value = map[key]; var declaredName; var publicName; var minifiedName; var needsDeclaredName; if (Array.isArray(value)) { _a = __read(value, 2), publicName = _a[0], declaredName = _a[1]; minifiedName = key; needsDeclaredName = publicName !== declaredName; } else { _b = __read(splitAtColon(key, [key, value]), 2), declaredName = _b[0], publicName = _b[1]; minifiedName = declaredName; // Only include the declared name if extracted from the key, i.e. the key contains a colon. // Otherwise the declared name should be omitted even if it is different from the public name, // as it may have already been minified. needsDeclaredName = publicName !== declaredName && key.includes(':'); } return { key: minifiedName, // put quotes around keys that contain potentially unsafe characters quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName), value: (keepDeclared && needsDeclaredName) ? literalArr([asLiteral(publicName), asLiteral(declaredName)]) : asLiteral(publicName) }; })); } /** * Remove trailing null nodes as they are implied. */ function trimTrailingNulls(parameters) { while (isNull(parameters[parameters.length - 1])) { parameters.pop(); } return parameters; } function getQueryPredicate(query, constantPool) { if (Array.isArray(query.predicate)) { var predicate_1 = []; query.predicate.forEach(function (selector) { // Each item in predicates array may contain strings with comma-separated refs // (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them // as separate array entities var selectors = selector.split(',').map(function (token) { return literal(token.trim()); }); predicate_1.push.apply(predicate_1, __spreadArray([], __read(selectors))); }); return constantPool.getConstLiteral(literalArr(predicate_1), true); } else { return query.predicate; } } /** * A representation for an object literal used during codegen of definition objects. The generic * type `T` allows to reference a documented type of the generated structure, such that the * property names that are set can be resolved to their documented declaration. */ var DefinitionMap = /** @class */ (function () { function DefinitionMap() { this.values = []; } DefinitionMap.prototype.set = function (key, value) { if (value) { this.values.push({ key: key, value: value, quoted: false }); } }; DefinitionMap.prototype.toLiteralMap = function () { return literalMap(this.values); }; return DefinitionMap; }()); /** * Extract a map of properties to values for a given element or template node, which can be used * by the directive matching machinery. * * @param elOrTpl the element or template in question * @return an object set up for directive matching. For attributes on the element/template, this * object maps a property name to its (static) value. For any bindings, this map simply maps the * property name to an empty string. */ function getAttrsForDirectiveMatching(elOrTpl) { var attributesMap = {}; if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') { elOrTpl.templateAttrs.forEach(function (a) { return attributesMap[a.name] = ''; }); } else { elOrTpl.attributes.forEach(function (a) { if (!isI18nAttribute(a.name)) { attributesMap[a.name] = a.value; } }); elOrTpl.inputs.forEach(function (i) { attributesMap[i.name] = ''; }); elOrTpl.outputs.forEach(function (o) { attributesMap[o.name] = ''; }); } return attributesMap; } /** Returns a call expression to a chained instruction, e.g. `property(params[0])(params[1])`. */ function chainedInstruction(reference, calls, span) { var expression = importExpr(reference, null, span); if (calls.length > 0) { for (var i = 0; i < calls.length; i++) { expression = expression.callFn(calls[i], span); } } else { // Add a blank invocation, in case the `calls` array is empty. expression = expression.callFn([], span); } return expression; } /** * Gets the number of arguments expected to be passed to a generated instruction in the case of * interpolation instructions. * @param interpolation An interpolation ast */ function getInterpolationArgsLength(interpolation) { var expressions = interpolation.expressions, strings = interpolation.strings; if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') { // If the interpolation has one interpolated value, but the prefix and suffix are both empty // strings, we only pass one argument, to a special instruction like `propertyInterpolate` or // `textInterpolate`. return 1; } else { return expressions.length + strings.length; } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Creates an array literal expression from the given array, mapping all values to an expression * using the provided mapping function. If the array is empty or null, then null is returned. * * @param values The array to transfer into literal array expression. * @param mapper The logic to use for creating an expression for the array's values. * @returns An array literal expression representing `values`, or null if `values` is empty or * is itself null. */ function toOptionalLiteralArray(values, mapper) { if (values === null || values.length === 0) { return null; } return literalArr(values.map(function (value) { return mapper(value); })); } /** * Creates an object literal expression from the given object, mapping all values to an expression * using the provided mapping function. If the object has no keys, then null is returned. * * @param object The object to transfer into an object literal expression. * @param mapper The logic to use for creating an expression for the object's values. * @returns An object literal expression representing `object`, or null if `object` does not have * any keys. */ function toOptionalLiteralMap(object, mapper) { var entries = Object.keys(object).map(function (key) { var value = object[key]; return { key: key, value: mapper(value), quoted: true }; }); if (entries.length > 0) { return literalMap(entries); } else { return null; } } function compileDependencies(deps) { if (deps === 'invalid') { // The `deps` can be set to the string "invalid" by the `unwrapConstructorDependencies()` // function, which tries to convert `ConstructorDeps` into `R3DependencyMetadata[]`. return literal('invalid'); } else if (deps === null) { return literal(null); } else { return literalArr(deps.map(compileDependency)); } } function compileDependency(dep) { var depMeta = new DefinitionMap(); depMeta.set('token', dep.token); if (dep.attributeNameType !== null) { depMeta.set('attribute', literal(true)); } if (dep.host) { depMeta.set('host', literal(true)); } if (dep.optional) { depMeta.set('optional', literal(true)); } if (dep.self) { depMeta.set('self', literal(true)); } if (dep.skipSelf) { depMeta.set('skipSelf', literal(true)); } return depMeta.toLiteralMap(); } /** * Generate an expression that has the given `expr` wrapped in the following form: * * ``` * forwardRef(() => expr) * ``` */ function generateForwardRef(expr) { return importExpr(Identifiers.forwardRef).callFn([fn([], [new ReturnStatement(expr)])]); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit var VERSION = 3; var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,'; var SourceMapGenerator = /** @class */ (function () { function SourceMapGenerator(file) { if (file === void 0) { file = null; } this.file = file; this.sourcesContent = new Map(); this.lines = []; this.lastCol0 = 0; this.hasMappings = false; } // The content is `null` when the content is expected to be loaded using the URL SourceMapGenerator.prototype.addSource = function (url, content) { if (content === void 0) { content = null; } if (!this.sourcesContent.has(url)) { this.sourcesContent.set(url, content); } return this; }; SourceMapGenerator.prototype.addLine = function () { this.lines.push([]); this.lastCol0 = 0; return this; }; SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) { if (!this.currentLine) { throw new Error("A line must be added before mappings can be added"); } if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) { throw new Error("Unknown source file \"" + sourceUrl + "\""); } if (col0 == null) { throw new Error("The column in the generated code must be provided"); } if (col0 < this.lastCol0) { throw new Error("Mapping should be added in output order"); } if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) { throw new Error("The source location must be provided when a source url is provided"); } this.hasMappings = true; this.lastCol0 = col0; this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 }); return this; }; Object.defineProperty(SourceMapGenerator.prototype, "currentLine", { /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ get: function () { return this.lines.slice(-1)[0]; }, enumerable: false, configurable: true }); SourceMapGenerator.prototype.toJSON = function () { var _this = this; if (!this.hasMappings) { return null; } var sourcesIndex = new Map(); var sources = []; var sourcesContent = []; Array.from(this.sourcesContent.keys()).forEach(function (url, i) { sourcesIndex.set(url, i); sources.push(url); sourcesContent.push(_this.sourcesContent.get(url) || null); }); var mappings = ''; var lastCol0 = 0; var lastSourceIndex = 0; var lastSourceLine0 = 0; var lastSourceCol0 = 0; this.lines.forEach(function (segments) { lastCol0 = 0; mappings += segments .map(function (segment) { // zero-based starting column of the line in the generated code var segAsStr = toBase64VLQ(segment.col0 - lastCol0); lastCol0 = segment.col0; if (segment.sourceUrl != null) { // zero-based index into the “sources” list segAsStr += toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex); lastSourceIndex = sourcesIndex.get(segment.sourceUrl); // the zero-based starting line in the original source segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0); lastSourceLine0 = segment.sourceLine0; // the zero-based starting column in the original source segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0); lastSourceCol0 = segment.sourceCol0; } return segAsStr; }) .join(','); mappings += ';'; }); mappings = mappings.slice(0, -1); return { 'file': this.file || '', 'version': VERSION, 'sourceRoot': '', 'sources': sources, 'sourcesContent': sourcesContent, 'mappings': mappings, }; }; SourceMapGenerator.prototype.toJsComment = function () { return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) : ''; }; return SourceMapGenerator; }()); function toBase64String(value) { var b64 = ''; var encoded = utf8Encode(value); for (var i = 0; i < encoded.length;) { var i1 = encoded[i++]; var i2 = i < encoded.length ? encoded[i++] : null; var i3 = i < encoded.length ? encoded[i++] : null; b64 += toBase64Digit(i1 >> 2); b64 += toBase64Digit(((i1 & 3) << 4) | (i2 === null ? 0 : i2 >> 4)); b64 += i2 === null ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 === null ? 0 : i3 >> 6)); b64 += i2 === null || i3 === null ? '=' : toBase64Digit(i3 & 63); } return b64; } function toBase64VLQ(value) { value = value < 0 ? ((-value) << 1) + 1 : value << 1; var out = ''; do { var digit = value & 31; value = value >> 5; if (value > 0) { digit = digit | 32; } out += toBase64Digit(digit); } while (value > 0); return out; } var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function toBase64Digit(value) { if (value < 0 || value >= 64) { throw new Error("Can only encode value in the range [0, 63]"); } return B64_DIGITS[value]; } var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g; var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i; var _INDENT_WITH = ' '; var CATCH_ERROR_VAR$1 = variable('error', null, null); var CATCH_STACK_VAR$1 = variable('stack', null, null); var _EmittedLine = /** @class */ (function () { function _EmittedLine(indent) { this.indent = indent; this.partsLength = 0; this.parts = []; this.srcSpans = []; } return _EmittedLine; }()); var EmitterVisitorContext = /** @class */ (function () { function EmitterVisitorContext(_indent) { this._indent = _indent; this._classes = []; this._preambleLineCount = 0; this._lines = [new _EmittedLine(_indent)]; } EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); }; Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", { /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ get: function () { return this._lines[this._lines.length - 1]; }, enumerable: false, configurable: true }); EmitterVisitorContext.prototype.println = function (from, lastPart) { if (lastPart === void 0) { lastPart = ''; } this.print(from || null, lastPart, true); }; EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; }; EmitterVisitorContext.prototype.lineLength = function () { return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength; }; EmitterVisitorContext.prototype.print = function (from, part, newLine) { if (newLine === void 0) { newLine = false; } if (part.length > 0) { this._currentLine.parts.push(part); this._currentLine.partsLength += part.length; this._currentLine.srcSpans.push(from && from.sourceSpan || null); } if (newLine) { this._lines.push(new _EmittedLine(this._indent)); } }; EmitterVisitorContext.prototype.removeEmptyLastLine = function () { if (this.lineIsEmpty()) { this._lines.pop(); } }; EmitterVisitorContext.prototype.incIndent = function () { this._indent++; if (this.lineIsEmpty()) { this._currentLine.indent = this._indent; } }; EmitterVisitorContext.prototype.decIndent = function () { this._indent--; if (this.lineIsEmpty()) { this._currentLine.indent = this._indent; } }; EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); }; EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); }; Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", { get: function () { return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null; }, enumerable: false, configurable: true }); EmitterVisitorContext.prototype.toSource = function () { return this.sourceLines .map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; }) .join('\n'); }; EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) { if (startsAtLine === void 0) { startsAtLine = 0; } var map = new SourceMapGenerator(genFilePath); var firstOffsetMapped = false; var mapFirstOffsetIfNeeded = function () { if (!firstOffsetMapped) { // Add a single space so that tools won't try to load the file from disk. // Note: We are using virtual urls like `ng:///`, so we have to // provide a content here. map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0); firstOffsetMapped = true; } }; for (var i = 0; i < startsAtLine; i++) { map.addLine(); mapFirstOffsetIfNeeded(); } this.sourceLines.forEach(function (line, lineIdx) { map.addLine(); var spans = line.srcSpans; var parts = line.parts; var col0 = line.indent * _INDENT_WITH.length; var spanIdx = 0; // skip leading parts without source spans while (spanIdx < spans.length && !spans[spanIdx]) { col0 += parts[spanIdx].length; spanIdx++; } if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) { firstOffsetMapped = true; } else { mapFirstOffsetIfNeeded(); } while (spanIdx < spans.length) { var span = spans[spanIdx]; var source = span.start.file; var sourceLine = span.start.line; var sourceCol = span.start.col; map.addSource(source.url, source.content) .addMapping(col0, source.url, sourceLine, sourceCol); col0 += parts[spanIdx].length; spanIdx++; // assign parts without span or the same span to the previous segment while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) { col0 += parts[spanIdx].length; spanIdx++; } } }); return map; }; EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; }; EmitterVisitorContext.prototype.spanOf = function (line, column) { var emittedLine = this._lines[line - this._preambleLineCount]; if (emittedLine) { var columnsLeft = column - _createIndent(emittedLine.indent).length; for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) { var part = emittedLine.parts[partIndex]; if (part.length > columnsLeft) { return emittedLine.srcSpans[partIndex]; } columnsLeft -= part.length; } } return null; }; Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", { /** * @internal strip this from published d.ts files due to * https://github.com/microsoft/TypeScript/issues/36216 */ get: function () { if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) { return this._lines.slice(0, -1); } return this._lines; }, enumerable: false, configurable: true }); return EmitterVisitorContext; }()); var AbstractEmitterVisitor = /** @class */ (function () { function AbstractEmitterVisitor(_escapeDollarInStrings) { this._escapeDollarInStrings = _escapeDollarInStrings; } AbstractEmitterVisitor.prototype.printLeadingComments = function (stmt, ctx) { var e_1, _a; if (stmt.leadingComments === undefined) { return; } try { for (var _b = __values(stmt.leadingComments), _c = _b.next(); !_c.done; _c = _b.next()) { var comment = _c.value; if (comment instanceof JSDocComment) { ctx.print(stmt, "/*" + comment.toString() + "*/", comment.trailingNewline); } else { if (comment.multiline) { ctx.print(stmt, "/* " + comment.text + " */", comment.trailingNewline); } else { comment.text.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); }); } } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } }; AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) { this.printLeadingComments(stmt, ctx); stmt.expr.visitExpression(this, ctx); ctx.println(stmt, ';'); return null; }; AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) { this.printLeadingComments(stmt, ctx); ctx.print(stmt, "return "); stmt.value.visitExpression(this, ctx); ctx.println(stmt, ';'); return null; }; AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) { this.printLeadingComments(stmt, ctx); ctx.print(stmt, "if ("); stmt.condition.visitExpression(this, ctx); ctx.print(stmt, ") {"); var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0; if (stmt.trueCase.length <= 1 && !hasElseCase) { ctx.print(stmt, " "); this.visitAllStatements(stmt.trueCase, ctx); ctx.removeEmptyLastLine(); ctx.print(stmt, " "); } else { ctx.println(); ctx.incIndent(); this.visitAllStatements(stmt.trueCase, ctx); ctx.decIndent(); if (hasElseCase) { ctx.println(stmt, "} else {"); ctx.incIndent(); this.visitAllStatements(stmt.falseCase, ctx); ctx.decIndent(); } } ctx.println(stmt, "}"); return null; }; AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) { this.printLeadingComments(stmt, ctx); ctx.print(stmt, "throw "); stmt.error.visitExpression(this, ctx); ctx.println(stmt, ";"); return null; }; AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) { var lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } ctx.print(expr, expr.name + " = "); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; }; AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) { var lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } expr.receiver.visitExpression(this, ctx); ctx.print(expr, "["); expr.index.visitExpression(this, ctx); ctx.print(expr, "] = "); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; }; AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) { var lineWasEmpty = ctx.lineIsEmpty(); if (!lineWasEmpty) { ctx.print(expr, '('); } expr.receiver.visitExpression(this, ctx); ctx.print(expr, "." + expr.name + " = "); expr.value.visitExpression(this, ctx); if (!lineWasEmpty) { ctx.print(expr, ')'); } return null; }; AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) { expr.receiver.visitExpression(this, ctx); var name = expr.name; if (expr.builtin != null) { name = this.getBuiltinMethodName(expr.builtin); if (name == null) { // some builtins just mean to skip the call. return null; } } ctx.print(expr, "." + name + "("); this.visitAllExpressions(expr.args, ctx, ","); ctx.print(expr, ")"); return null; }; AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) { expr.fn.visitExpression(this, ctx); ctx.print(expr, "("); this.visitAllExpressions(expr.args, ctx, ','); ctx.print(expr, ")"); return null; }; AbstractEmitterVisitor.prototype.visitTaggedTemplateExpr = function (expr, ctx) { expr.tag.visitExpression(this, ctx); ctx.print(expr, '`' + expr.template.elements[0].rawText); for (var i = 1; i < expr.template.elements.length; i++) { ctx.print(expr, '${'); expr.template.expressions[i - 1].visitExpression(this, ctx); ctx.print(expr, "}" + expr.template.elements[i].rawText); } ctx.print(expr, '`'); return null; }; AbstractEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) { throw new Error('Abstract emitter cannot visit WrappedNodeExpr.'); }; AbstractEmitterVisitor.prototype.visitTypeofExpr = function (expr, ctx) { ctx.print(expr, 'typeof '); expr.expr.visitExpression(this, ctx); }; AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) { var varName = ast.name; if (ast.builtin != null) { switch (ast.builtin) { case exports.BuiltinVar.Super: varName = 'super'; break; case exports.BuiltinVar.This: varName = 'this'; break; case exports.BuiltinVar.CatchError: varName = CATCH_ERROR_VAR$1.name; break; case exports.BuiltinVar.CatchStack: varName = CATCH_STACK_VAR$1.name; break; default: throw new Error("Unknown builtin variable " + ast.builtin); } } ctx.print(ast, varName); return null; }; AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) { ctx.print(ast, "new "); ast.classExpr.visitExpression(this, ctx); ctx.print(ast, "("); this.visitAllExpressions(ast.args, ctx, ','); ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) { var value = ast.value; if (typeof value === 'string') { ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings)); } else { ctx.print(ast, "" + value); } return null; }; AbstractEmitterVisitor.prototype.visitLocalizedString = function (ast, ctx) { var head = ast.serializeI18nHead(); ctx.print(ast, '$localize `' + head.raw); for (var i = 1; i < ast.messageParts.length; i++) { ctx.print(ast, '${'); ast.expressions[i - 1].visitExpression(this, ctx); ctx.print(ast, "}" + ast.serializeI18nTemplatePart(i).raw); } ctx.print(ast, '`'); return null; }; AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) { ctx.print(ast, "("); ast.condition.visitExpression(this, ctx); ctx.print(ast, '? '); ast.trueCase.visitExpression(this, ctx); ctx.print(ast, ': '); ast.falseCase.visitExpression(this, ctx); ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) { ctx.print(ast, '!'); ast.condition.visitExpression(this, ctx); return null; }; AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) { ast.condition.visitExpression(this, ctx); return null; }; AbstractEmitterVisitor.prototype.visitUnaryOperatorExpr = function (ast, ctx) { var opStr; switch (ast.operator) { case exports.UnaryOperator.Plus: opStr = '+'; break; case exports.UnaryOperator.Minus: opStr = '-'; break; default: throw new Error("Unknown operator " + ast.operator); } if (ast.parens) ctx.print(ast, "("); ctx.print(ast, opStr); ast.expr.visitExpression(this, ctx); if (ast.parens) ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) { var opStr; switch (ast.operator) { case exports.BinaryOperator.Equals: opStr = '=='; break; case exports.BinaryOperator.Identical: opStr = '==='; break; case exports.BinaryOperator.NotEquals: opStr = '!='; break; case exports.BinaryOperator.NotIdentical: opStr = '!=='; break; case exports.BinaryOperator.And: opStr = '&&'; break; case exports.BinaryOperator.BitwiseAnd: opStr = '&'; break; case exports.BinaryOperator.Or: opStr = '||'; break; case exports.BinaryOperator.Plus: opStr = '+'; break; case exports.BinaryOperator.Minus: opStr = '-'; break; case exports.BinaryOperator.Divide: opStr = '/'; break; case exports.BinaryOperator.Multiply: opStr = '*'; break; case exports.BinaryOperator.Modulo: opStr = '%'; break; case exports.BinaryOperator.Lower: opStr = '<'; break; case exports.BinaryOperator.LowerEquals: opStr = '<='; break; case exports.BinaryOperator.Bigger: opStr = '>'; break; case exports.BinaryOperator.BiggerEquals: opStr = '>='; break; case exports.BinaryOperator.NullishCoalesce: opStr = '??'; break; default: throw new Error("Unknown operator " + ast.operator); } if (ast.parens) ctx.print(ast, "("); ast.lhs.visitExpression(this, ctx); ctx.print(ast, " " + opStr + " "); ast.rhs.visitExpression(this, ctx); if (ast.parens) ctx.print(ast, ")"); return null; }; AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) { ast.receiver.visitExpression(this, ctx); ctx.print(ast, "."); ctx.print(ast, ast.name); return null; }; AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) { ast.receiver.visitExpression(this, ctx); ctx.print(ast, "["); ast.index.visitExpression(this, ctx); ctx.print(ast, "]"); return null; }; AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) { ctx.print(ast, "["); this.visitAllExpressions(ast.entries, ctx, ','); ctx.print(ast, "]"); return null; }; AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) { var _this = this; ctx.print(ast, "{"); this.visitAllObjects(function (entry) { ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":"); entry.value.visitExpression(_this, ctx); }, ast.entries, ctx, ','); ctx.print(ast, "}"); return null; }; AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) { ctx.print(ast, '('); this.visitAllExpressions(ast.parts, ctx, ','); ctx.print(ast, ')'); return null; }; AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) { var _this = this; this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator); }; AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) { var incrementedIndent = false; for (var i = 0; i < expressions.length; i++) { if (i > 0) { if (ctx.lineLength() > 80) { ctx.print(null, separator, true); if (!incrementedIndent) { // continuation are marked with double indent. ctx.incIndent(); ctx.incIndent(); incrementedIndent = true; } } else { ctx.print(null, separator, false); } } handler(expressions[i]); } if (incrementedIndent) { // continuation are marked with double indent. ctx.decIndent(); ctx.decIndent(); } }; AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) { var _this = this; statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); }); }; return AbstractEmitterVisitor; }()); function escapeIdentifier(input, escapeDollar, alwaysQuote) { if (alwaysQuote === void 0) { alwaysQuote = true; } if (input == null) { return null; } var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () { var match = []; for (var _i = 0; _i < arguments.length; _i++) { match[_i] = arguments[_i]; } if (match[0] == '$') { return escapeDollar ? '\\$' : '$'; } else if (match[0] == '\n') { return '\\n'; } else if (match[0] == '\r') { return '\\r'; } else { return "\\" + match[0]; } }); var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body); return requiresQuotes ? "'" + body + "'" : body; } function _createIndent(count) { var res = ''; for (var i = 0; i < count; i++) { res += _INDENT_WITH; } return res; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function typeWithParameters(type, numParams) { if (numParams === 0) { return expressionType(type); } var params = []; for (var i = 0; i < numParams; i++) { params.push(DYNAMIC_TYPE); } return expressionType(type, undefined, params); } var ANIMATE_SYMBOL_PREFIX = '@'; function prepareSyntheticPropertyName(name) { return "" + ANIMATE_SYMBOL_PREFIX + name; } function prepareSyntheticListenerName(name, phase) { return "" + ANIMATE_SYMBOL_PREFIX + name + "." + phase; } function getSafePropertyAccessString(accessor, name) { var escapedName = escapeIdentifier(name, false, false); return escapedName !== name ? accessor + "[" + escapedName + "]" : accessor + "." + name; } function prepareSyntheticListenerFunctionName(name, phase) { return "animation_" + name + "_" + phase; } function jitOnlyGuardedExpression(expr) { return guardedExpression('ngJitMode', expr); } function devOnlyGuardedExpression(expr) { return guardedExpression('ngDevMode', expr); } function guardedExpression(guard, expr) { var guardExpr = new ExternalExpr({ name: guard, moduleName: null }); var guardNotDefined = new BinaryOperatorExpr(exports.BinaryOperator.Identical, new TypeofExpr(guardExpr), literal('undefined')); var guardUndefinedOrTrue = new BinaryOperatorExpr(exports.BinaryOperator.Or, guardNotDefined, guardExpr, /* type */ undefined, /* sourceSpan */ undefined, true); return new BinaryOperatorExpr(exports.BinaryOperator.And, guardUndefinedOrTrue, expr); } function wrapReference(value) { var wrapped = new WrappedNodeExpr(value); return { value: wrapped, type: wrapped }; } function refsToArray(refs, shouldForwardDeclare) { var values = literalArr(refs.map(function (ref) { return ref.value; })); return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var R3FactoryDelegateType; (function (R3FactoryDelegateType) { R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class"; R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function"; })(R3FactoryDelegateType || (R3FactoryDelegateType = {})); (function (FactoryTarget) { FactoryTarget[FactoryTarget["Directive"] = 0] = "Directive"; FactoryTarget[FactoryTarget["Component"] = 1] = "Component"; FactoryTarget[FactoryTarget["Injectable"] = 2] = "Injectable"; FactoryTarget[FactoryTarget["Pipe"] = 3] = "Pipe"; FactoryTarget[FactoryTarget["NgModule"] = 4] = "NgModule"; })(exports.FactoryTarget || (exports.FactoryTarget = {})); /** * Construct a factory function expression for the given `R3FactoryMetadata`. */ function compileFactoryFunction(meta) { var t = variable('t'); var baseFactoryVar = null; // The type to instantiate via constructor invocation. If there is no delegated factory, meaning // this type is always created by constructor invocation, then this is the type-to-create // parameter provided by the user (t) if specified, or the current type if not. If there is a // delegated factory (which is used to create the current type) then this is only the type-to- // create parameter (t). var typeForCtor = !isDelegatedFactoryMetadata(meta) ? new BinaryOperatorExpr(exports.BinaryOperator.Or, t, meta.internalType) : t; var ctorExpr = null; if (meta.deps !== null) { // There is a constructor (either explicitly or implicitly defined). if (meta.deps !== 'invalid') { ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.target)); } } else { // There is no constructor, use the base class' factory to construct typeForCtor. baseFactoryVar = variable("\u0275" + meta.name + "_BaseFactory"); ctorExpr = baseFactoryVar.callFn([typeForCtor]); } var body = []; var retExpr = null; function makeConditionalFactory(nonCtorExpr) { var r = variable('r'); body.push(r.set(NULL_EXPR).toDeclStmt()); var ctorStmt = ctorExpr !== null ? r.set(ctorExpr).toStmt() : importExpr(Identifiers.invalidFactory).callFn([]).toStmt(); body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()])); return r; } if (isDelegatedFactoryMetadata(meta)) { // This type is created with a delegated factory. If a type parameter is not specified, call // the factory instead. var delegateArgs = injectDependencies(meta.delegateDeps, meta.target); // Either call `new delegate(...)` or `delegate(...)` depending on meta.delegateType. var factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ? InstantiateExpr : InvokeFunctionExpr)(meta.delegate, delegateArgs); retExpr = makeConditionalFactory(factoryExpr); } else if (isExpressionFactoryMetadata(meta)) { // TODO(alxhub): decide whether to lower the value here or in the caller retExpr = makeConditionalFactory(meta.expression); } else { retExpr = ctorExpr; } if (retExpr === null) { // The expression cannot be formed so render an `ɵɵinvalidFactory()` call. body.push(importExpr(Identifiers.invalidFactory).callFn([]).toStmt()); } else if (baseFactoryVar !== null) { // This factory uses a base factory, so call `ɵɵgetInheritedFactory()` to compute it. var getInheritedFactoryCall = importExpr(Identifiers.getInheritedFactory).callFn([meta.internalType]); // Memoize the base factoryFn: `baseFactory || (baseFactory = ɵɵgetInheritedFactory(...))` var baseFactory = new BinaryOperatorExpr(exports.BinaryOperator.Or, baseFactoryVar, baseFactoryVar.set(getInheritedFactoryCall)); body.push(new ReturnStatement(baseFactory.callFn([typeForCtor]))); } else { // This is straightforward factory, just return it. body.push(new ReturnStatement(retExpr)); } var factoryFn = fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, meta.name + "_Factory"); if (baseFactoryVar !== null) { // There is a base factory variable so wrap its declaration along with the factory function into // an IIFE. factoryFn = fn([], [ new DeclareVarStmt(baseFactoryVar.name), new ReturnStatement(factoryFn) ]).callFn([], /* sourceSpan */ undefined, /* pure */ true); } return { expression: factoryFn, statements: [], type: createFactoryType(meta), }; } function createFactoryType(meta) { var ctorDepsType = meta.deps !== null && meta.deps !== 'invalid' ? createCtorDepsType(meta.deps) : NONE_TYPE; return expressionType(importExpr(Identifiers.FactoryDeclaration, [typeWithParameters(meta.type.type, meta.typeArgumentCount), ctorDepsType])); } function injectDependencies(deps, target) { return deps.map(function (dep, index) { return compileInjectDependency(dep, target, index); }); } function compileInjectDependency(dep, target, index) { // Interpret the dependency according to its resolved type. if (dep.token === null) { return importExpr(Identifiers.invalidFactoryDep).callFn([literal(index)]); } else if (dep.attributeNameType === null) { // Build up the injection flags according to the metadata. var flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) | (dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) | (dep.optional ? 8 /* Optional */ : 0) | (target === exports.FactoryTarget.Pipe ? 16 /* ForPipe */ : 0); // If this dependency is optional or otherwise has non-default flags, then additional // parameters describing how to inject the dependency must be passed to the inject function // that's being used. var flagsParam = (flags !== 0 /* Default */ || dep.optional) ? literal(flags) : null; // Build up the arguments to the injectFn call. var injectArgs = [dep.token]; if (flagsParam) { injectArgs.push(flagsParam); } var injectFn = getInjectFn(target); return importExpr(injectFn).callFn(injectArgs); } else { // The `dep.attributeTypeName` value is defined, which indicates that this is an `@Attribute()` // type dependency. For the generated JS we still want to use the `dep.token` value in case the // name given for the attribute is not a string literal. For example given `@Attribute(foo())`, // we want to generate `ɵɵinjectAttribute(foo())`. // // The `dep.attributeTypeName` is only actually used (in `createCtorDepType()`) to generate // typings. return importExpr(Identifiers.injectAttribute).callFn([dep.token]); } } function createCtorDepsType(deps) { var hasTypes = false; var attributeTypes = deps.map(function (dep) { var type = createCtorDepType(dep); if (type !== null) { hasTypes = true; return type; } else { return literal(null); } }); if (hasTypes) { return expressionType(literalArr(attributeTypes)); } else { return NONE_TYPE; } } function createCtorDepType(dep) { var entries = []; if (dep.attributeNameType !== null) { entries.push({ key: 'attribute', value: dep.attributeNameType, quoted: false }); } if (dep.optional) { entries.push({ key: 'optional', value: literal(true), quoted: false }); } if (dep.host) { entries.push({ key: 'host', value: literal(true), quoted: false }); } if (dep.self) { entries.push({ key: 'self', value: literal(true), quoted: false }); } if (dep.skipSelf) { entries.push({ key: 'skipSelf', value: literal(true), quoted: false }); } return entries.length > 0 ? literalMap(entries) : null; } function isDelegatedFactoryMetadata(meta) { return meta.delegateType !== undefined; } function isExpressionFactoryMetadata(meta) { return meta.expression !== undefined; } function getInjectFn(target) { switch (target) { case exports.FactoryTarget.Component: case exports.FactoryTarget.Directive: case exports.FactoryTarget.Pipe: return Identifiers.directiveInject; case exports.FactoryTarget.NgModule: case exports.FactoryTarget.Injectable: default: return Identifiers.inject; } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function createR3ProviderExpression(expression, isForwardRef) { return { expression: expression, isForwardRef: isForwardRef }; } function compileInjectable(meta, resolveForwardRefs) { var result = null; var factoryMeta = { name: meta.name, type: meta.type, internalType: meta.internalType, typeArgumentCount: meta.typeArgumentCount, deps: [], target: exports.FactoryTarget.Injectable, }; if (meta.useClass !== undefined) { // meta.useClass has two modes of operation. Either deps are specified, in which case `new` is // used to instantiate the class with dependencies injected, or deps are not specified and // the factory of the class is used to instantiate it. // // A special case exists for useClass: Type where Type is the injectable type itself and no // deps are specified, in which case 'useClass' is effectively ignored. var useClassOnSelf = meta.useClass.expression.isEquivalent(meta.internalType); var deps = undefined; if (meta.deps !== undefined) { deps = meta.deps; } if (deps !== undefined) { // factory: () => new meta.useClass(...deps) result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { delegate: meta.useClass.expression, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class })); } else if (useClassOnSelf) { result = compileFactoryFunction(factoryMeta); } else { result = { statements: [], expression: delegateToFactory(meta.type.value, meta.useClass.expression, resolveForwardRefs) }; } } else if (meta.useFactory !== undefined) { if (meta.deps !== undefined) { result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { delegate: meta.useFactory, delegateDeps: meta.deps || [], delegateType: R3FactoryDelegateType.Function })); } else { result = { statements: [], expression: fn([], [new ReturnStatement(meta.useFactory.callFn([]))]) }; } } else if (meta.useValue !== undefined) { // Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for // client code because meta.useValue is an Expression which will be defined even if the actual // value is undefined. result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { expression: meta.useValue.expression })); } else if (meta.useExisting !== undefined) { // useExisting is an `inject` call on the existing token. result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { expression: importExpr(Identifiers.inject).callFn([meta.useExisting.expression]) })); } else { result = { statements: [], expression: delegateToFactory(meta.type.value, meta.internalType, resolveForwardRefs) }; } var token = meta.internalType; var injectableProps = new DefinitionMap(); injectableProps.set('token', token); injectableProps.set('factory', result.expression); // Only generate providedIn property if it has a non-null value if (meta.providedIn.expression.value !== null) { injectableProps.set('providedIn', meta.providedIn.isForwardRef ? generateForwardRef(meta.providedIn.expression) : meta.providedIn.expression); } var expression = importExpr(Identifiers.ɵɵdefineInjectable) .callFn([injectableProps.toLiteralMap()], undefined, true); return { expression: expression, type: createInjectableType(meta), statements: result.statements, }; } function createInjectableType(meta) { return new ExpressionType(importExpr(Identifiers.InjectableDeclaration, [typeWithParameters(meta.type.type, meta.typeArgumentCount)])); } function delegateToFactory(type, internalType, unwrapForwardRefs) { if (type.node === internalType.node) { // The types are the same, so we can simply delegate directly to the type's factory. // ``` // factory: type.ɵfac // ``` return internalType.prop('ɵfac'); } if (!unwrapForwardRefs) { // The type is not wrapped in a `forwardRef()`, so we create a simple factory function that // accepts a sub-type as an argument. // ``` // factory: function(t) { return internalType.ɵfac(t); } // ``` return createFactoryFunction(internalType); } // The internalType is actually wrapped in a `forwardRef()` so we need to resolve that before // calling its factory. // ``` // factory: function(t) { return core.resolveForwardRef(type).ɵfac(t); } // ``` var unwrappedType = importExpr(Identifiers.resolveForwardRef).callFn([internalType]); return createFactoryFunction(unwrappedType); } function createFactoryFunction(type) { return fn([new FnParam('t', DYNAMIC_TYPE)], [new ReturnStatement(type.callMethod('ɵfac', [variable('t')]))]); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function assertArrayOfStrings(identifier, value) { if (value == null) { return; } if (!Array.isArray(value)) { throw new Error("Expected '" + identifier + "' to be an array of strings."); } for (var i = 0; i < value.length; i += 1) { if (typeof value[i] !== 'string') { throw new Error("Expected '" + identifier + "' to be an array of strings."); } } } var UNUSABLE_INTERPOLATION_REGEXPS = [ /^\s*$/, /[<>]/, /^[{}]$/, /&(#|[a-z])/i, /^\/\//, // comment ]; function assertInterpolationSymbols(identifier, value) { if (value != null && !(Array.isArray(value) && value.length == 2)) { throw new Error("Expected '" + identifier + "' to be an array, [start, end]."); } else if (value != null) { var start_1 = value[0]; var end_1 = value[1]; // Check for unusable interpolation symbols UNUSABLE_INTERPOLATION_REGEXPS.forEach(function (regexp) { if (regexp.test(start_1) || regexp.test(end_1)) { throw new Error("['" + start_1 + "', '" + end_1 + "'] contains unusable interpolation symbol."); } }); } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var InterpolationConfig = /** @class */ (function () { function InterpolationConfig(start, end) { this.start = start; this.end = end; } InterpolationConfig.fromArray = function (markers) { if (!markers) { return DEFAULT_INTERPOLATION_CONFIG; } assertInterpolationSymbols('interpolation', markers); return new InterpolationConfig(markers[0], markers[1]); }; return InterpolationConfig; }()); var DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}'); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A token representing the a reference to a static type. * * This token is unique for a filePath and name and can be used as a hash table key. */ var StaticSymbol = /** @class */ (function () { function StaticSymbol(filePath, name, members) { this.filePath = filePath; this.name = name; this.members = members; } StaticSymbol.prototype.assertNoMembers = function () { if (this.members.length) { throw new Error("Illegal state: symbol without members expected, but got " + JSON.stringify(this) + "."); } }; return StaticSymbol; }()); /** * A cache of static symbol used by the StaticReflector to return the same symbol for the * same symbol values. */ var StaticSymbolCache = /** @class */ (function () { function StaticSymbolCache() { this.cache = new Map(); } StaticSymbolCache.prototype.get = function (declarationFile, name, members) { members = members || []; var memberSuffix = members.length ? "." + members.join('.') : ''; var key = "\"" + declarationFile + "\"." + name + memberSuffix; var result = this.cache.get(key); if (!result) { result = new StaticSymbol(declarationFile, name, members); this.cache.set(key, result); } return result; }; return StaticSymbolCache; }()); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // group 0: "[prop] or (event) or @trigger" // group 1: "prop" from "[prop]" // group 2: "event" from "(event)" // group 3: "@trigger" from "@trigger" var HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/; function sanitizeIdentifier(name) { return name.replace(/\W/g, '_'); } var _anonymousTypeIndex = 0; function identifierName(compileIdentifier) { if (!compileIdentifier || !compileIdentifier.reference) { return null; } var ref = compileIdentifier.reference; if (ref instanceof StaticSymbol) { return ref.name; } if (ref['__anonymousType']) { return ref['__anonymousType']; } if (ref['__forward_ref__']) { // We do not want to try to stringify a `forwardRef()` function because that would cause the // inner function to be evaluated too early, defeating the whole point of the `forwardRef`. return '__forward_ref__'; } var identifier = stringify(ref); if (identifier.indexOf('(') >= 0) { // case: anonymous functions! identifier = "anonymous_" + _anonymousTypeIndex++; ref['__anonymousType'] = identifier; } else { identifier = sanitizeIdentifier(identifier); } return identifier; } function identifierModuleUrl(compileIdentifier) { var ref = compileIdentifier.reference; if (ref instanceof StaticSymbol) { return ref.filePath; } // Runtime type return "./" + stringify(ref); } function viewClassName(compType, embeddedTemplateIndex) { return "View_" + identifierName({ reference: compType }) + "_" + embeddedTemplateIndex; } function rendererTypeName(compType) { return "RenderType_" + identifierName({ reference: compType }); } function hostViewClassName(compType) { return "HostView_" + identifierName({ reference: compType }); } function componentFactoryName(compType) { return identifierName({ reference: compType }) + "NgFactory"; } (function (CompileSummaryKind) { CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe"; CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive"; CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule"; CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable"; })(exports.CompileSummaryKind || (exports.CompileSummaryKind = {})); function tokenName(token) { return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier); } function tokenReference(token) { if (token.identifier != null) { return token.identifier.reference; } else { return token.value; } } /** * Metadata about a stylesheet */ var CompileStylesheetMetadata = /** @class */ (function () { function CompileStylesheetMetadata(_a) { var _b = _a === void 0 ? {} : _a, moduleUrl = _b.moduleUrl, styles = _b.styles, styleUrls = _b.styleUrls; this.moduleUrl = moduleUrl || null; this.styles = _normalizeArray(styles); this.styleUrls = _normalizeArray(styleUrls); } return CompileStylesheetMetadata; }()); /** * Metadata regarding compilation of a template. */ var CompileTemplateMetadata = /** @class */ (function () { function CompileTemplateMetadata(_a) { var encapsulation = _a.encapsulation, template = _a.template, templateUrl = _a.templateUrl, htmlAst = _a.htmlAst, styles = _a.styles, styleUrls = _a.styleUrls, externalStylesheets = _a.externalStylesheets, animations = _a.animations, ngContentSelectors = _a.ngContentSelectors, interpolation = _a.interpolation, isInline = _a.isInline, preserveWhitespaces = _a.preserveWhitespaces; this.encapsulation = encapsulation; this.template = template; this.templateUrl = templateUrl; this.htmlAst = htmlAst; this.styles = _normalizeArray(styles); this.styleUrls = _normalizeArray(styleUrls); this.externalStylesheets = _normalizeArray(externalStylesheets); this.animations = animations ? flatten(animations) : []; this.ngContentSelectors = ngContentSelectors || []; if (interpolation && interpolation.length != 2) { throw new Error("'interpolation' should have a start and an end symbol."); } this.interpolation = interpolation; this.isInline = isInline; this.preserveWhitespaces = preserveWhitespaces; } CompileTemplateMetadata.prototype.toSummary = function () { return { ngContentSelectors: this.ngContentSelectors, encapsulation: this.encapsulation, styles: this.styles, animations: this.animations }; }; return CompileTemplateMetadata; }()); /** * Metadata regarding compilation of a directive. */ var CompileDirectiveMetadata = /** @class */ (function () { function CompileDirectiveMetadata(_a) { var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, hostListeners = _a.hostListeners, hostProperties = _a.hostProperties, hostAttributes = _a.hostAttributes, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory; this.isHost = !!isHost; this.type = type; this.isComponent = isComponent; this.selector = selector; this.exportAs = exportAs; this.changeDetection = changeDetection; this.inputs = inputs; this.outputs = outputs; this.hostListeners = hostListeners; this.hostProperties = hostProperties; this.hostAttributes = hostAttributes; this.providers = _normalizeArray(providers); this.viewProviders = _normalizeArray(viewProviders); this.queries = _normalizeArray(queries); this.guards = guards; this.viewQueries = _normalizeArray(viewQueries); this.entryComponents = _normalizeArray(entryComponents); this.template = template; this.componentViewType = componentViewType; this.rendererType = rendererType; this.componentFactory = componentFactory; } CompileDirectiveMetadata.create = function (_a) { var isHost = _a.isHost, type = _a.type, isComponent = _a.isComponent, selector = _a.selector, exportAs = _a.exportAs, changeDetection = _a.changeDetection, inputs = _a.inputs, outputs = _a.outputs, host = _a.host, providers = _a.providers, viewProviders = _a.viewProviders, queries = _a.queries, guards = _a.guards, viewQueries = _a.viewQueries, entryComponents = _a.entryComponents, template = _a.template, componentViewType = _a.componentViewType, rendererType = _a.rendererType, componentFactory = _a.componentFactory; var hostListeners = {}; var hostProperties = {}; var hostAttributes = {}; if (host != null) { Object.keys(host).forEach(function (key) { var value = host[key]; var matches = key.match(HOST_REG_EXP); if (matches === null) { hostAttributes[key] = value; } else if (matches[1] != null) { hostProperties[matches[1]] = value; } else if (matches[2] != null) { hostListeners[matches[2]] = value; } }); } var inputsMap = {}; if (inputs != null) { inputs.forEach(function (bindConfig) { // canonical syntax: `dirProp: elProp` // if there is no `:`, use dirProp = elProp var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]); inputsMap[parts[0]] = parts[1]; }); } var outputsMap = {}; if (outputs != null) { outputs.forEach(function (bindConfig) { // canonical syntax: `dirProp: elProp` // if there is no `:`, use dirProp = elProp var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]); outputsMap[parts[0]] = parts[1]; }); } return new CompileDirectiveMetadata({ isHost: isHost, type: type, isComponent: !!isComponent, selector: selector, exportAs: exportAs, changeDetection: changeDetection, inputs: inputsMap, outputs: outputsMap, hostListeners: hostListeners, hostProperties: hostProperties, hostAttributes: hostAttributes, providers: providers, viewProviders: viewProviders, queries: queries, guards: guards, viewQueries: viewQueries, entryComponents: entryComponents, template: template, componentViewType: componentViewType, rendererType: rendererType, componentFactory: componentFactory, }); }; CompileDirectiveMetadata.prototype.toSummary = function () { return { summaryKind: exports.CompileSummaryKind.Directive, type: this.type, isComponent: this.isComponent, selector: this.selector, exportAs: this.exportAs, inputs: this.inputs, outputs: this.outputs, hostListeners: this.hostListeners, hostProperties: this.hostProperties, hostAttributes: this.hostAttributes, providers: this.providers, viewProviders: this.viewProviders, queries: this.queries, guards: this.guards, viewQueries: this.viewQueries, entryComponents: this.entryComponents, changeDetection: this.changeDetection, template: this.template && this.template.toSummary(), componentViewType: this.componentViewType, rendererType: this.rendererType, componentFactory: this.componentFactory }; }; return CompileDirectiveMetadata; }()); var CompilePipeMetadata = /** @class */ (function () { function CompilePipeMetadata(_a) { var type = _a.type, name = _a.name, pure = _a.pure; this.type = type; this.name = name; this.pure = !!pure; } CompilePipeMetadata.prototype.toSummary = function () { return { summaryKind: exports.CompileSummaryKind.Pipe, type: this.type, name: this.name, pure: this.pure }; }; return CompilePipeMetadata; }()); var CompileShallowModuleMetadata = /** @class */ (function () { function CompileShallowModuleMetadata() { } return CompileShallowModuleMetadata; }()); /** * Metadata regarding compilation of a module. */ var CompileNgModuleMetadata = /** @class */ (function () { function CompileNgModuleMetadata(_a) { var type = _a.type, providers = _a.providers, declaredDirectives = _a.declaredDirectives, exportedDirectives = _a.exportedDirectives, declaredPipes = _a.declaredPipes, exportedPipes = _a.exportedPipes, entryComponents = _a.entryComponents, bootstrapComponents = _a.bootstrapComponents, importedModules = _a.importedModules, exportedModules = _a.exportedModules, schemas = _a.schemas, transitiveModule = _a.transitiveModule, id = _a.id; this.type = type || null; this.declaredDirectives = _normalizeArray(declaredDirectives); this.exportedDirectives = _normalizeArray(exportedDirectives); this.declaredPipes = _normalizeArray(declaredPipes); this.exportedPipes = _normalizeArray(exportedPipes); this.providers = _normalizeArray(providers); this.entryComponents = _normalizeArray(entryComponents); this.bootstrapComponents = _normalizeArray(bootstrapComponents); this.importedModules = _normalizeArray(importedModules); this.exportedModules = _normalizeArray(exportedModules); this.schemas = _normalizeArray(schemas); this.id = id || null; this.transitiveModule = transitiveModule || null; } CompileNgModuleMetadata.prototype.toSummary = function () { var module = this.transitiveModule; return { summaryKind: exports.CompileSummaryKind.NgModule, type: this.type, entryComponents: module.entryComponents, providers: module.providers, modules: module.modules, exportedDirectives: module.exportedDirectives, exportedPipes: module.exportedPipes }; }; return CompileNgModuleMetadata; }()); var TransitiveCompileNgModuleMetadata = /** @class */ (function () { function TransitiveCompileNgModuleMetadata() { this.directivesSet = new Set(); this.directives = []; this.exportedDirectivesSet = new Set(); this.exportedDirectives = []; this.pipesSet = new Set(); this.pipes = []; this.exportedPipesSet = new Set(); this.exportedPipes = []; this.modulesSet = new Set(); this.modules = []; this.entryComponentsSet = new Set(); this.entryComponents = []; this.providers = []; } TransitiveCompileNgModuleMetadata.prototype.addProvider = function (provider, module) { this.providers.push({ provider: provider, module: module }); }; TransitiveCompileNgModuleMetadata.prototype.addDirective = function (id) { if (!this.directivesSet.has(id.reference)) { this.directivesSet.add(id.reference); this.directives.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addExportedDirective = function (id) { if (!this.exportedDirectivesSet.has(id.reference)) { this.exportedDirectivesSet.add(id.reference); this.exportedDirectives.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addPipe = function (id) { if (!this.pipesSet.has(id.reference)) { this.pipesSet.add(id.reference); this.pipes.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addExportedPipe = function (id) { if (!this.exportedPipesSet.has(id.reference)) { this.exportedPipesSet.add(id.reference); this.exportedPipes.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addModule = function (id) { if (!this.modulesSet.has(id.reference)) { this.modulesSet.add(id.reference); this.modules.push(id); } }; TransitiveCompileNgModuleMetadata.prototype.addEntryComponent = function (ec) { if (!this.entryComponentsSet.has(ec.componentType)) { this.entryComponentsSet.add(ec.componentType); this.entryComponents.push(ec); } }; return TransitiveCompileNgModuleMetadata; }()); function _normalizeArray(obj) { return obj || []; } var ProviderMeta = /** @class */ (function () { function ProviderMeta(token, _a) { var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi; this.token = token; this.useClass = useClass || null; this.useValue = useValue; this.useExisting = useExisting; this.useFactory = useFactory || null; this.dependencies = deps || null; this.multi = !!multi; } return ProviderMeta; }()); function flatten(list) { return list.reduce(function (flat, item) { var flatItem = Array.isArray(item) ? flatten(item) : item; return flat.concat(flatItem); }, []); } function jitSourceUrl(url) { // Note: We need 3 "/" so that ng shows up as a separate domain // in the chrome dev tools. return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///'); } function templateSourceUrl(ngModuleType, compMeta, templateMeta) { var url; if (templateMeta.isInline) { if (compMeta.type.reference instanceof StaticSymbol) { // Note: a .ts file might contain multiple components with inline templates, // so we need to give them unique urls, as these will be used for sourcemaps. url = compMeta.type.reference.filePath + "." + compMeta.type.reference.name + ".html"; } else { url = identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".html"; } } else { url = templateMeta.templateUrl; } return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url); } function sharedStylesheetJitUrl(meta, id) { var pathParts = meta.moduleUrl.split(/\/\\/g); var baseName = pathParts[pathParts.length - 1]; return jitSourceUrl("css/" + id + baseName + ".ngstyle.js"); } function ngModuleJitUrl(moduleMeta) { return jitSourceUrl(identifierName(moduleMeta.type) + "/module.ngfactory.js"); } function templateJitUrl(ngModuleType, compMeta) { return jitSourceUrl(identifierName(ngModuleType) + "/" + identifierName(compMeta.type) + ".ngfactory.js"); } /** * In TypeScript, tagged template functions expect a "template object", which is an array of * "cooked" strings plus a `raw` property that contains an array of "raw" strings. This is * typically constructed with a function called `__makeTemplateObject(cooked, raw)`, but it may not * be available in all environments. * * This is a JavaScript polyfill that uses __makeTemplateObject when it's available, but otherwise * creates an inline helper with the same functionality. * * In the inline function, if `Object.defineProperty` is available we use that to attach the `raw` * array. */ var makeTemplateObjectPolyfill = '(this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})'; var AbstractJsEmitterVisitor = /** @class */ (function (_super) { __extends(AbstractJsEmitterVisitor, _super); function AbstractJsEmitterVisitor() { return _super.call(this, false) || this; } AbstractJsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) { var _this = this; ctx.pushClass(stmt); this._visitClassConstructor(stmt, ctx); if (stmt.parent != null) { ctx.print(stmt, stmt.name + ".prototype = Object.create("); stmt.parent.visitExpression(this, ctx); ctx.println(stmt, ".prototype);"); } stmt.getters.forEach(function (getter) { return _this._visitClassGetter(stmt, getter, ctx); }); stmt.methods.forEach(function (method) { return _this._visitClassMethod(stmt, method, ctx); }); ctx.popClass(); return null; }; AbstractJsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) { ctx.print(stmt, "function " + stmt.name + "("); if (stmt.constructorMethod != null) { this._visitParams(stmt.constructorMethod.params, ctx); } ctx.println(stmt, ") {"); ctx.incIndent(); if (stmt.constructorMethod != null) { if (stmt.constructorMethod.body.length > 0) { ctx.println(stmt, "var self = this;"); this.visitAllStatements(stmt.constructorMethod.body, ctx); } } ctx.decIndent(); ctx.println(stmt, "}"); }; AbstractJsEmitterVisitor.prototype._visitClassGetter = function (stmt, getter, ctx) { ctx.println(stmt, "Object.defineProperty(" + stmt.name + ".prototype, '" + getter.name + "', { get: function() {"); ctx.incIndent(); if (getter.body.length > 0) { ctx.println(stmt, "var self = this;"); this.visitAllStatements(getter.body, ctx); } ctx.decIndent(); ctx.println(stmt, "}});"); }; AbstractJsEmitterVisitor.prototype._visitClassMethod = function (stmt, method, ctx) { ctx.print(stmt, stmt.name + ".prototype." + method.name + " = function("); this._visitParams(method.params, ctx); ctx.println(stmt, ") {"); ctx.incIndent(); if (method.body.length > 0) { ctx.println(stmt, "var self = this;"); this.visitAllStatements(method.body, ctx); } ctx.decIndent(); ctx.println(stmt, "};"); }; AbstractJsEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) { throw new Error('Cannot emit a WrappedNodeExpr in Javascript.'); }; AbstractJsEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) { if (ast.builtin === exports.BuiltinVar.This) { ctx.print(ast, 'self'); } else if (ast.builtin === exports.BuiltinVar.Super) { throw new Error("'super' needs to be handled at a parent ast node, not at the variable level!"); } else { _super.prototype.visitReadVarExpr.call(this, ast, ctx); } return null; }; AbstractJsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) { ctx.print(stmt, "var " + stmt.name); if (stmt.value) { ctx.print(stmt, ' = '); stmt.value.visitExpression(this, ctx); } ctx.println(stmt, ";"); return null; }; AbstractJsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) { ast.value.visitExpression(this, ctx); return null; }; AbstractJsEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) { var fnExpr = expr.fn; if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === exports.BuiltinVar.Super) { ctx.currentClass.parent.visitExpression(this, ctx); ctx.print(expr, ".call(this"); if (expr.args.length > 0) { ctx.print(expr, ", "); this.visitAllExpressions(expr.args, ctx, ','); } ctx.print(expr, ")"); } else { _super.prototype.visitInvokeFunctionExpr.call(this, expr, ctx); } return null; }; AbstractJsEmitterVisitor.prototype.visitTaggedTemplateExpr = function (ast, ctx) { var _this = this; // The following convoluted piece of code is effectively the downlevelled equivalent of // ``` // tag`...` // ``` // which is effectively like: // ``` // tag(__makeTemplateObject(cooked, raw), expression1, expression2, ...); // ``` var elements = ast.template.elements; ast.tag.visitExpression(this, ctx); ctx.print(ast, "(" + makeTemplateObjectPolyfill + "("); ctx.print(ast, "[" + elements.map(function (part) { return escapeIdentifier(part.text, false); }).join(', ') + "], "); ctx.print(ast, "[" + elements.map(function (part) { return escapeIdentifier(part.rawText, false); }).join(', ') + "])"); ast.template.expressions.forEach(function (expression) { ctx.print(ast, ', '); expression.visitExpression(_this, ctx); }); ctx.print(ast, ')'); return null; }; AbstractJsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) { ctx.print(ast, "function" + (ast.name ? ' ' + ast.name : '') + "("); this._visitParams(ast.params, ctx); ctx.println(ast, ") {"); ctx.incIndent(); this.visitAllStatements(ast.statements, ctx); ctx.decIndent(); ctx.print(ast, "}"); return null; }; AbstractJsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) { ctx.print(stmt, "function " + stmt.name + "("); this._visitParams(stmt.params, ctx); ctx.println(stmt, ") {"); ctx.incIndent(); this.visitAllStatements(stmt.statements, ctx); ctx.decIndent(); ctx.println(stmt, "}"); return null; }; AbstractJsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) { ctx.println(stmt, "try {"); ctx.incIndent(); this.visitAllStatements(stmt.bodyStmts, ctx); ctx.decIndent(); ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {"); ctx.incIndent(); var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [ exports.StmtModifier.Final ])].concat(stmt.catchStmts); this.visitAllStatements(catchStmts, ctx); ctx.decIndent(); ctx.println(stmt, "}"); return null; }; AbstractJsEmitterVisitor.prototype.visitLocalizedString = function (ast, ctx) { var _this = this; // The following convoluted piece of code is effectively the downlevelled equivalent of // ``` // $localize `...` // ``` // which is effectively like: // ``` // $localize(__makeTemplateObject(cooked, raw), expression1, expression2, ...); // ``` ctx.print(ast, "$localize(" + makeTemplateObjectPolyfill + "("); var parts = [ast.serializeI18nHead()]; for (var i = 1; i < ast.messageParts.length; i++) { parts.push(ast.serializeI18nTemplatePart(i)); } ctx.print(ast, "[" + parts.map(function (part) { return escapeIdentifier(part.cooked, false); }).join(', ') + "], "); ctx.print(ast, "[" + parts.map(function (part) { return escapeIdentifier(part.raw, false); }).join(', ') + "])"); ast.expressions.forEach(function (expression) { ctx.print(ast, ', '); expression.visitExpression(_this, ctx); }); ctx.print(ast, ')'); return null; }; AbstractJsEmitterVisitor.prototype._visitParams = function (params, ctx) { this.visitAllObjects(function (param) { return ctx.print(null, param.name); }, params, ctx, ','); }; AbstractJsEmitterVisitor.prototype.getBuiltinMethodName = function (method) { var name; switch (method) { case exports.BuiltinMethod.ConcatArray: name = 'concat'; break; case exports.BuiltinMethod.SubscribeObservable: name = 'subscribe'; break; case exports.BuiltinMethod.Bind: name = 'bind'; break; default: throw new Error("Unknown builtin method: " + method); } return name; }; return AbstractJsEmitterVisitor; }(AbstractEmitterVisitor)); /** * The Trusted Types policy, or null if Trusted Types are not * enabled/supported, or undefined if the policy has not been created yet. */ var policy; /** * Returns the Trusted Types policy, or null if Trusted Types are not * enabled/supported. The first call to this function will create the policy. */ function getPolicy() { if (policy === undefined) { policy = null; if (_global.trustedTypes) { try { policy = _global.trustedTypes.createPolicy('angular#unsafe-jit', { createScript: function (s) { return s; }, }); } catch (_a) { // trustedTypes.createPolicy throws if called with a name that is // already registered, even in report-only mode. Until the API changes, // catch the error not to break the applications functionally. In such // cases, the code will fall back to using strings. } } } return policy; } /** * Unsafely promote a string to a TrustedScript, falling back to strings when * Trusted Types are not available. * @security In particular, it must be assured that the provided string will * never cause an XSS vulnerability if used in a context that will be * interpreted and executed as a script by a browser, e.g. when calling eval. */ function trustedScriptFromString(script) { var _a; return ((_a = getPolicy()) === null || _a === void 0 ? void 0 : _a.createScript(script)) || script; } /** * Unsafely call the Function constructor with the given string arguments. * @security This is a security-sensitive function; any use of this function * must go through security review. In particular, it must be assured that it * is only called from the JIT compiler, as use in other code can lead to XSS * vulnerabilities. */ function newTrustedFunctionForJIT() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!_global.trustedTypes) { // In environments that don't support Trusted Types, fall back to the most // straightforward implementation: return new (Function.bind.apply(Function, __spreadArray([void 0], __read(args))))(); } // Chrome currently does not support passing TrustedScript to the Function // constructor. The following implements the workaround proposed on the page // below, where the Chromium bug is also referenced: // https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor var fnArgs = args.slice(0, -1).join(','); var fnBody = args[args.length - 1]; var body = "(function anonymous(" + fnArgs + "\n) { " + fnBody + "\n})"; // Using eval directly confuses the compiler and prevents this module from // being stripped out of JS binaries even if not used. The global['eval'] // indirection fixes that. var fn = _global['eval'](trustedScriptFromString(body)); if (fn.bind === undefined) { // Workaround for a browser bug that only exists in Chrome 83, where passing // a TrustedScript to eval just returns the TrustedScript back without // evaluating it. In that case, fall back to the most straightforward // implementation: return new (Function.bind.apply(Function, __spreadArray([void 0], __read(args))))(); } // To completely mimic the behavior of calling "new Function", two more // things need to happen: // 1. Stringifying the resulting function should return its source code fn.toString = function () { return body; }; // 2. When calling the resulting function, `this` should refer to `global` return fn.bind(_global); // When Trusted Types support in Function constructors is widely available, // the implementation of this function can be simplified to: // return new Function(...args.map(a => trustedScriptFromString(a))); } /** * A helper class to manage the evaluation of JIT generated code. */ var JitEvaluator = /** @class */ (function () { function JitEvaluator() { } /** * * @param sourceUrl The URL of the generated code. * @param statements An array of Angular statement AST nodes to be evaluated. * @param reflector A helper used when converting the statements to executable code. * @param createSourceMaps If true then create a source-map for the generated code and include it * inline as a source-map comment. * @returns A map of all the variables in the generated code. */ JitEvaluator.prototype.evaluateStatements = function (sourceUrl, statements, reflector, createSourceMaps) { var converter = new JitEmitterVisitor(reflector); var ctx = EmitterVisitorContext.createRoot(); // Ensure generated code is in strict mode if (statements.length > 0 && !isUseStrictStatement(statements[0])) { statements = __spreadArray([ literal('use strict').toStmt() ], __read(statements)); } converter.visitAllStatements(statements, ctx); converter.createReturnStmt(ctx); return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps); }; /** * Evaluate a piece of JIT generated code. * @param sourceUrl The URL of this generated code. * @param ctx A context object that contains an AST of the code to be evaluated. * @param vars A map containing the names and values of variables that the evaluated code might * reference. * @param createSourceMap If true then create a source-map for the generated code and include it * inline as a source-map comment. * @returns The result of evaluating the code. */ JitEvaluator.prototype.evaluateCode = function (sourceUrl, ctx, vars, createSourceMap) { var fnBody = "\"use strict\";" + ctx.toSource() + "\n//# sourceURL=" + sourceUrl; var fnArgNames = []; var fnArgValues = []; for (var argName in vars) { fnArgValues.push(vars[argName]); fnArgNames.push(argName); } if (createSourceMap) { // using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise // E.g. ``` // function anonymous(a,b,c // /**/) { ... }``` // We don't want to hard code this fact, so we auto detect it via an empty function first. var emptyFn = newTrustedFunctionForJIT.apply(void 0, __spreadArray([], __read(fnArgNames.concat('return null;')))).toString(); var headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1; fnBody += "\n" + ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment(); } var fn = newTrustedFunctionForJIT.apply(void 0, __spreadArray([], __read(fnArgNames.concat(fnBody)))); return this.executeFunction(fn, fnArgValues); }; /** * Execute a JIT generated function by calling it. * * This method can be overridden in tests to capture the functions that are generated * by this `JitEvaluator` class. * * @param fn A function to execute. * @param args The arguments to pass to the function being executed. * @returns The return value of the executed function. */ JitEvaluator.prototype.executeFunction = function (fn, args) { return fn.apply(void 0, __spreadArray([], __read(args))); }; return JitEvaluator; }()); /** * An Angular AST visitor that converts AST nodes into executable JavaScript code. */ var JitEmitterVisitor = /** @class */ (function (_super) { __extends(JitEmitterVisitor, _super); function JitEmitterVisitor(reflector) { var _this = _super.call(this) || this; _this.reflector = reflector; _this._evalArgNames = []; _this._evalArgValues = []; _this._evalExportedVars = []; return _this; } JitEmitterVisitor.prototype.createReturnStmt = function (ctx) { var stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(function (resultVar) { return new LiteralMapEntry(resultVar, variable(resultVar), false); }))); stmt.visitStatement(this, ctx); }; JitEmitterVisitor.prototype.getArgs = function () { var result = {}; for (var i = 0; i < this._evalArgNames.length; i++) { result[this._evalArgNames[i]] = this._evalArgValues[i]; } return result; }; JitEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) { this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx); return null; }; JitEmitterVisitor.prototype.visitWrappedNodeExpr = function (ast, ctx) { this._emitReferenceToExternal(ast, ast.node, ctx); return null; }; JitEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) { if (stmt.hasModifier(exports.StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return _super.prototype.visitDeclareVarStmt.call(this, stmt, ctx); }; JitEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) { if (stmt.hasModifier(exports.StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return _super.prototype.visitDeclareFunctionStmt.call(this, stmt, ctx); }; JitEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) { if (stmt.hasModifier(exports.StmtModifier.Exported)) { this._evalExportedVars.push(stmt.name); } return _super.prototype.visitDeclareClassStmt.call(this, stmt, ctx); }; JitEmitterVisitor.prototype._emitReferenceToExternal = function (ast, value, ctx) { var id = this._evalArgValues.indexOf(value); if (id === -1) { id = this._evalArgValues.length; this._evalArgValues.push(value); var name = identifierName({ reference: value }) || 'val'; this._evalArgNames.push("jit_" + name + "_" + id); } ctx.print(ast, this._evalArgNames[id]); }; return JitEmitterVisitor; }(AbstractJsEmitterVisitor)); function isUseStrictStatement(statement) { return statement.isEquivalent(literal('use strict').toStmt()); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var $EOF = 0; var $BSPACE = 8; var $TAB = 9; var $LF = 10; var $VTAB = 11; var $FF = 12; var $CR = 13; var $SPACE = 32; var $BANG = 33; var $DQ = 34; var $HASH = 35; var $$ = 36; var $PERCENT = 37; var $AMPERSAND = 38; var $SQ = 39; var $LPAREN = 40; var $RPAREN = 41; var $STAR = 42; var $PLUS = 43; var $COMMA = 44; var $MINUS = 45; var $PERIOD = 46; var $SLASH = 47; var $COLON = 58; var $SEMICOLON = 59; var $LT = 60; var $EQ = 61; var $GT = 62; var $QUESTION = 63; var $0 = 48; var $7 = 55; var $9 = 57; var $A = 65; var $E = 69; var $F = 70; var $X = 88; var $Z = 90; var $LBRACKET = 91; var $BACKSLASH = 92; var $RBRACKET = 93; var $CARET = 94; var $_ = 95; var $a = 97; var $b = 98; var $e = 101; var $f = 102; var $n = 110; var $r = 114; var $t = 116; var $u = 117; var $v = 118; var $x = 120; var $z = 122; var $LBRACE = 123; var $BAR = 124; var $RBRACE = 125; var $NBSP = 160; var $PIPE = 124; var $TILDA = 126; var $AT = 64; var $BT = 96; function isWhitespace(code) { return (code >= $TAB && code <= $SPACE) || (code == $NBSP); } function isDigit(code) { return $0 <= code && code <= $9; } function isAsciiLetter(code) { return code >= $a && code <= $z || code >= $A && code <= $Z; } function isAsciiHexDigit(code) { return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code); } function isNewLine(code) { return code === $LF || code === $CR; } function isOctalDigit(code) { return $0 <= code && code <= $7; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ParseLocation = /** @class */ (function () { function ParseLocation(file, offset, line, col) { this.file = file; this.offset = offset; this.line = line; this.col = col; } ParseLocation.prototype.toString = function () { return this.offset != null ? this.file.url + "@" + this.line + ":" + this.col : this.file.url; }; ParseLocation.prototype.moveBy = function (delta) { var source = this.file.content; var len = source.length; var offset = this.offset; var line = this.line; var col = this.col; while (offset > 0 && delta < 0) { offset--; delta++; var ch = source.charCodeAt(offset); if (ch == $LF) { line--; var priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF)); col = priorLine > 0 ? offset - priorLine : offset; } else { col--; } } while (offset < len && delta > 0) { var ch = source.charCodeAt(offset); offset++; delta--; if (ch == $LF) { line++; col = 0; } else { col++; } } return new ParseLocation(this.file, offset, line, col); }; // Return the source around the location // Up to `maxChars` or `maxLines` on each side of the location ParseLocation.prototype.getContext = function (maxChars, maxLines) { var content = this.file.content; var startOffset = this.offset; if (startOffset != null) { if (startOffset > content.length - 1) { startOffset = content.length - 1; } var endOffset = startOffset; var ctxChars = 0; var ctxLines = 0; while (ctxChars < maxChars && startOffset > 0) { startOffset--; ctxChars++; if (content[startOffset] == '\n') { if (++ctxLines == maxLines) { break; } } } ctxChars = 0; ctxLines = 0; while (ctxChars < maxChars && endOffset < content.length - 1) { endOffset++; ctxChars++; if (content[endOffset] == '\n') { if (++ctxLines == maxLines) { break; } } } return { before: content.substring(startOffset, this.offset), after: content.substring(this.offset, endOffset + 1), }; } return null; }; return ParseLocation; }()); var ParseSourceFile = /** @class */ (function () { function ParseSourceFile(content, url) { this.content = content; this.url = url; } return ParseSourceFile; }()); var ParseSourceSpan = /** @class */ (function () { /** * Create an object that holds information about spans of tokens/nodes captured during * lexing/parsing of text. * * @param start * The location of the start of the span (having skipped leading trivia). * Skipping leading trivia makes source-spans more "user friendly", since things like HTML * elements will appear to begin at the start of the opening tag, rather than at the start of any * leading trivia, which could include newlines. * * @param end * The location of the end of the span. * * @param fullStart * The start of the token without skipping the leading trivia. * This is used by tooling that splits tokens further, such as extracting Angular interpolations * from text tokens. Such tooling creates new source-spans relative to the original token's * source-span. If leading trivia characters have been skipped then the new source-spans may be * incorrectly offset. * * @param details * Additional information (such as identifier names) that should be associated with the span. */ function ParseSourceSpan(start, end, fullStart, details) { if (fullStart === void 0) { fullStart = start; } if (details === void 0) { details = null; } this.start = start; this.end = end; this.fullStart = fullStart; this.details = details; } ParseSourceSpan.prototype.toString = function () { return this.start.file.content.substring(this.start.offset, this.end.offset); }; return ParseSourceSpan; }()); (function (ParseErrorLevel) { ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING"; ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR"; })(exports.ParseErrorLevel || (exports.ParseErrorLevel = {})); var ParseError = /** @class */ (function () { function ParseError(span, msg, level) { if (level === void 0) { level = exports.ParseErrorLevel.ERROR; } this.span = span; this.msg = msg; this.level = level; } ParseError.prototype.contextualMessage = function () { var ctx = this.span.start.getContext(100, 3); return ctx ? this.msg + " (\"" + ctx.before + "[" + exports.ParseErrorLevel[this.level] + " ->]" + ctx.after + "\")" : this.msg; }; ParseError.prototype.toString = function () { var details = this.span.details ? ", " + this.span.details : ''; return this.contextualMessage() + ": " + this.span.start + details; }; return ParseError; }()); function typeSourceSpan(kind, type) { var moduleUrl = identifierModuleUrl(type); var sourceFileName = moduleUrl != null ? "in " + kind + " " + identifierName(type) + " in " + moduleUrl : "in " + kind + " " + identifierName(type); var sourceFile = new ParseSourceFile('', sourceFileName); return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1)); } /** * Generates Source Span object for a given R3 Type for JIT mode. * * @param kind Component or Directive. * @param typeName name of the Component or Directive. * @param sourceUrl reference to Component or Directive source. * @returns instance of ParseSourceSpan that represent a given Component or Directive. */ function r3JitTypeSourceSpan(kind, typeName, sourceUrl) { var sourceFileName = "in " + kind + " " + typeName + " in " + sourceUrl; var sourceFile = new ParseSourceFile('', sourceFileName); return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1)); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function compileInjector(meta) { var definitionMap = new DefinitionMap(); if (meta.providers !== null) { definitionMap.set('providers', meta.providers); } if (meta.imports.length > 0) { definitionMap.set('imports', literalArr(meta.imports)); } var expression = importExpr(Identifiers.defineInjector).callFn([definitionMap.toLiteralMap()], undefined, true); var type = createInjectorType(meta); return { expression: expression, type: type, statements: [] }; } function createInjectorType(meta) { return new ExpressionType(importExpr(Identifiers.InjectorDeclaration, [new ExpressionType(meta.type.type)])); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Implementation of `CompileReflector` which resolves references to @angular/core * symbols at runtime, according to a consumer-provided mapping. * * Only supports `resolveExternalReference`, all other methods throw. */ var R3JitReflector = /** @class */ (function () { function R3JitReflector(context) { this.context = context; } R3JitReflector.prototype.resolveExternalReference = function (ref) { // This reflector only handles @angular/core imports. if (ref.moduleName !== '@angular/core') { throw new Error("Cannot resolve external reference to " + ref.moduleName + ", only references to @angular/core are supported."); } if (!this.context.hasOwnProperty(ref.name)) { throw new Error("No value provided for @angular/core symbol '" + ref.name + "'."); } return this.context[ref.name]; }; R3JitReflector.prototype.parameters = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.annotations = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.shallowAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.tryAnnotations = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.propMetadata = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.hasLifecycleHook = function (type, lcProperty) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.guards = function (typeOrFunc) { throw new Error('Not implemented.'); }; R3JitReflector.prototype.componentModuleUrl = function (type, cmpMetadata) { throw new Error('Not implemented.'); }; return R3JitReflector; }()); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`. */ function compileNgModule(meta) { var internalType = meta.internalType, bootstrap = meta.bootstrap, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, schemas = meta.schemas, containsForwardDecls = meta.containsForwardDecls, emitInline = meta.emitInline, id = meta.id; var statements = []; var definitionMap = new DefinitionMap(); definitionMap.set('type', internalType); if (bootstrap.length > 0) { definitionMap.set('bootstrap', refsToArray(bootstrap, containsForwardDecls)); } // If requested to emit scope information inline, pass the `declarations`, `imports` and `exports` // to the `ɵɵdefineNgModule()` call. The JIT compilation uses this. if (emitInline) { if (declarations.length > 0) { definitionMap.set('declarations', refsToArray(declarations, containsForwardDecls)); } if (imports.length > 0) { definitionMap.set('imports', refsToArray(imports, containsForwardDecls)); } if (exports.length > 0) { definitionMap.set('exports', refsToArray(exports, containsForwardDecls)); } } // If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would // prevent tree-shaking of the declarations, imports and exports references. else { var setNgModuleScopeCall = generateSetNgModuleScopeCall(meta); if (setNgModuleScopeCall !== null) { statements.push(setNgModuleScopeCall); } } if (schemas !== null && schemas.length > 0) { definitionMap.set('schemas', literalArr(schemas.map(function (ref) { return ref.value; }))); } if (id !== null) { definitionMap.set('id', id); } var expression = importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()], undefined, true); var type = createNgModuleType(meta); return { expression: expression, type: type, statements: statements }; } /** * This function is used in JIT mode to generate the call to `ɵɵdefineNgModule()` from a call to * `ɵɵngDeclareNgModule()`. */ function compileNgModuleDeclarationExpression(meta) { var definitionMap = new DefinitionMap(); definitionMap.set('type', new WrappedNodeExpr(meta.type)); if (meta.bootstrap !== undefined) { definitionMap.set('bootstrap', new WrappedNodeExpr(meta.bootstrap)); } if (meta.declarations !== undefined) { definitionMap.set('declarations', new WrappedNodeExpr(meta.declarations)); } if (meta.imports !== undefined) { definitionMap.set('imports', new WrappedNodeExpr(meta.imports)); } if (meta.exports !== undefined) { definitionMap.set('exports', new WrappedNodeExpr(meta.exports)); } if (meta.schemas !== undefined) { definitionMap.set('schemas', new WrappedNodeExpr(meta.schemas)); } if (meta.id !== undefined) { definitionMap.set('id', new WrappedNodeExpr(meta.id)); } return importExpr(Identifiers.defineNgModule).callFn([definitionMap.toLiteralMap()]); } function createNgModuleType(_a) { var moduleType = _a.type, declarations = _a.declarations, imports = _a.imports, exports = _a.exports; return new ExpressionType(importExpr(Identifiers.NgModuleDeclaration, [ new ExpressionType(moduleType.type), tupleTypeOf(declarations), tupleTypeOf(imports), tupleTypeOf(exports) ])); } /** * Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the * transitive module scope can be computed during runtime in JIT mode. This call is marked pure * such that the references to declarations, imports and exports may be elided causing these * symbols to become tree-shakeable. */ function generateSetNgModuleScopeCall(meta) { var moduleType = meta.adjacentType, declarations = meta.declarations, imports = meta.imports, exports = meta.exports, containsForwardDecls = meta.containsForwardDecls; var scopeMap = new DefinitionMap(); if (declarations.length > 0) { scopeMap.set('declarations', refsToArray(declarations, containsForwardDecls)); } if (imports.length > 0) { scopeMap.set('imports', refsToArray(imports, containsForwardDecls)); } if (exports.length > 0) { scopeMap.set('exports', refsToArray(exports, containsForwardDecls)); } if (Object.keys(scopeMap.values).length === 0) { return null; } // setNgModuleScope(...) var fnCall = new InvokeFunctionExpr( /* fn */ importExpr(Identifiers.setNgModuleScope), /* args */ [moduleType, scopeMap.toLiteralMap()]); // (ngJitMode guard) && setNgModuleScope(...) var guardedCall = jitOnlyGuardedExpression(fnCall); // function() { (ngJitMode guard) && setNgModuleScope(...); } var iife = new FunctionExpr( /* params */ [], /* statements */ [guardedCall.toStmt()]); // (function() { (ngJitMode guard) && setNgModuleScope(...); })() var iifeCall = new InvokeFunctionExpr( /* fn */ iife, /* args */ []); return iifeCall.toStmt(); } function tupleTypeOf(exp) { var types = exp.map(function (ref) { return typeofExpr(ref.type); }); return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function compilePipeFromMetadata(metadata) { var definitionMapValues = []; // e.g. `name: 'myPipe'` definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false }); // e.g. `type: MyPipe` definitionMapValues.push({ key: 'type', value: metadata.type.value, quoted: false }); // e.g. `pure: true` definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false }); var expression = importExpr(Identifiers.definePipe).callFn([literalMap(definitionMapValues)], undefined, true); var type = createPipeType(metadata); return { expression: expression, type: type, statements: [] }; } function createPipeType(metadata) { return new ExpressionType(importExpr(Identifiers.PipeDeclaration, [ typeWithParameters(metadata.type.type, metadata.typeArgumentCount), new ExpressionType(new LiteralExpr(metadata.pipeName)), ])); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var ParserError = /** @class */ (function () { function ParserError(message, input, errLocation, ctxLocation) { this.input = input; this.errLocation = errLocation; this.ctxLocation = ctxLocation; this.message = "Parser Error: " + message + " " + errLocation + " [" + input + "] in " + ctxLocation; } return ParserError; }()); var ParseSpan = /** @class */ (function () { function ParseSpan(start, end) { this.start = start; this.end = end; } ParseSpan.prototype.toAbsolute = function (absoluteOffset) { return new AbsoluteSourceSpan(absoluteOffset + this.start, absoluteOffset + this.end); }; return ParseSpan; }()); var AST = /** @class */ (function () { function AST(span, /** * Absolute location of the expression AST in a source code file. */ sourceSpan) { this.span = span; this.sourceSpan = sourceSpan; } AST.prototype.toString = function () { return 'AST'; }; return AST; }()); var ASTWithName = /** @class */ (function (_super) { __extends(ASTWithName, _super); function ASTWithName(span, sourceSpan, nameSpan) { var _this = _super.call(this, span, sourceSpan) || this; _this.nameSpan = nameSpan; return _this; } return ASTWithName; }(AST)); /** * Represents a quoted expression of the form: * * quote = prefix `:` uninterpretedExpression * prefix = identifier * uninterpretedExpression = arbitrary string * * A quoted expression is meant to be pre-processed by an AST transformer that * converts it into another AST that no longer contains quoted expressions. * It is meant to allow third-party developers to extend Angular template * expression language. The `uninterpretedExpression` part of the quote is * therefore not interpreted by the Angular's own expression parser. */ var Quote = /** @class */ (function (_super) { __extends(Quote, _super); function Quote(span, sourceSpan, prefix, uninterpretedExpression, location) { var _this = _super.call(this, span, sourceSpan) || this; _this.prefix = prefix; _this.uninterpretedExpression = uninterpretedExpression; _this.location = location; return _this; } Quote.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitQuote(this, context); }; Quote.prototype.toString = function () { return 'Quote'; }; return Quote; }(AST)); var EmptyExpr = /** @class */ (function (_super) { __extends(EmptyExpr, _super); function EmptyExpr() { return _super !== null && _super.apply(this, arguments) || this; } EmptyExpr.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } // do nothing }; return EmptyExpr; }(AST)); var ImplicitReceiver = /** @class */ (function (_super) { __extends(ImplicitReceiver, _super); function ImplicitReceiver() { return _super !== null && _super.apply(this, arguments) || this; } ImplicitReceiver.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitImplicitReceiver(this, context); }; return ImplicitReceiver; }(AST)); /** * Receiver when something is accessed through `this` (e.g. `this.foo`). Note that this class * inherits from `ImplicitReceiver`, because accessing something through `this` is treated the * same as accessing it implicitly inside of an Angular template (e.g. `[attr.title]="this.title"` * is the same as `[attr.title]="title"`.). Inheriting allows for the `this` accesses to be treated * the same as implicit ones, except for a couple of exceptions like `$event` and `$any`. * TODO: we should find a way for this class not to extend from `ImplicitReceiver` in the future. */ var ThisReceiver = /** @class */ (function (_super) { __extends(ThisReceiver, _super); function ThisReceiver() { return _super !== null && _super.apply(this, arguments) || this; } ThisReceiver.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } var _a; return (_a = visitor.visitThisReceiver) === null || _a === void 0 ? void 0 : _a.call(visitor, this, context); }; return ThisReceiver; }(ImplicitReceiver)); /** * Multiple expressions separated by a semicolon. */ var Chain = /** @class */ (function (_super) { __extends(Chain, _super); function Chain(span, sourceSpan, expressions) { var _this = _super.call(this, span, sourceSpan) || this; _this.expressions = expressions; return _this; } Chain.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitChain(this, context); }; return Chain; }(AST)); var Conditional = /** @class */ (function (_super) { __extends(Conditional, _super); function Conditional(span, sourceSpan, condition, trueExp, falseExp) { var _this = _super.call(this, span, sourceSpan) || this; _this.condition = condition; _this.trueExp = trueExp; _this.falseExp = falseExp; return _this; } Conditional.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitConditional(this, context); }; return Conditional; }(AST)); var PropertyRead = /** @class */ (function (_super) { __extends(PropertyRead, _super); function PropertyRead(span, sourceSpan, nameSpan, receiver, name) { var _this = _super.call(this, span, sourceSpan, nameSpan) || this; _this.receiver = receiver; _this.name = name; return _this; } PropertyRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPropertyRead(this, context); }; return PropertyRead; }(ASTWithName)); var PropertyWrite = /** @class */ (function (_super) { __extends(PropertyWrite, _super); function PropertyWrite(span, sourceSpan, nameSpan, receiver, name, value) { var _this = _super.call(this, span, sourceSpan, nameSpan) || this; _this.receiver = receiver; _this.name = name; _this.value = value; return _this; } PropertyWrite.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPropertyWrite(this, context); }; return PropertyWrite; }(ASTWithName)); var SafePropertyRead = /** @class */ (function (_super) { __extends(SafePropertyRead, _super); function SafePropertyRead(span, sourceSpan, nameSpan, receiver, name) { var _this = _super.call(this, span, sourceSpan, nameSpan) || this; _this.receiver = receiver; _this.name = name; return _this; } SafePropertyRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitSafePropertyRead(this, context); }; return SafePropertyRead; }(ASTWithName)); var KeyedRead = /** @class */ (function (_super) { __extends(KeyedRead, _super); function KeyedRead(span, sourceSpan, receiver, key) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.key = key; return _this; } KeyedRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitKeyedRead(this, context); }; return KeyedRead; }(AST)); var SafeKeyedRead = /** @class */ (function (_super) { __extends(SafeKeyedRead, _super); function SafeKeyedRead(span, sourceSpan, receiver, key) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.key = key; return _this; } SafeKeyedRead.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitSafeKeyedRead(this, context); }; return SafeKeyedRead; }(AST)); var KeyedWrite = /** @class */ (function (_super) { __extends(KeyedWrite, _super); function KeyedWrite(span, sourceSpan, receiver, key, value) { var _this = _super.call(this, span, sourceSpan) || this; _this.receiver = receiver; _this.key = key; _this.value = value; return _this; } KeyedWrite.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitKeyedWrite(this, context); }; return KeyedWrite; }(AST)); var BindingPipe = /** @class */ (function (_super) { __extends(BindingPipe, _super); function BindingPipe(span, sourceSpan, exp, name, args, nameSpan) { var _this = _super.call(this, span, sourceSpan, nameSpan) || this; _this.exp = exp; _this.name = name; _this.args = args; return _this; } BindingPipe.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPipe(this, context); }; return BindingPipe; }(ASTWithName)); var LiteralPrimitive = /** @class */ (function (_super) { __extends(LiteralPrimitive, _super); function LiteralPrimitive(span, sourceSpan, value) { var _this = _super.call(this, span, sourceSpan) || this; _this.value = value; return _this; } LiteralPrimitive.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitLiteralPrimitive(this, context); }; return LiteralPrimitive; }(AST)); var LiteralArray = /** @class */ (function (_super) { __extends(LiteralArray, _super); function LiteralArray(span, sourceSpan, expressions) { var _this = _super.call(this, span, sourceSpan) || this; _this.expressions = expressions; return _this; } LiteralArray.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitLiteralArray(this, context); }; return LiteralArray; }(AST)); var LiteralMap = /** @class */ (function (_super) { __extends(LiteralMap, _super); function LiteralMap(span, sourceSpan, keys, values) { var _this = _super.call(this, span, sourceSpan) || this; _this.keys = keys; _this.values = values; return _this; } LiteralMap.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitLiteralMap(this, context); }; return LiteralMap; }(AST)); var Interpolation = /** @class */ (function (_super) { __extends(Interpolation, _super); function Interpolation(span, sourceSpan, strings, expressions) { var _this = _super.call(this, span, sourceSpan) || this; _this.strings = strings; _this.expressions = expressions; return _this; } Interpolation.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitInterpolation(this, context); }; return Interpolation; }(AST)); var Binary = /** @class */ (function (_super) { __extends(Binary, _super); function Binary(span, sourceSpan, operation, left, right) { var _this = _super.call(this, span, sourceSpan) || this; _this.operation = operation; _this.left = left; _this.right = right; return _this; } Binary.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitBinary(this, context); }; return Binary; }(AST)); /** * For backwards compatibility reasons, `Unary` inherits from `Binary` and mimics the binary AST * node that was originally used. This inheritance relation can be deleted in some future major, * after consumers have been given a chance to fully support Unary. */ var Unary = /** @class */ (function (_super) { __extends(Unary, _super); /** * During the deprecation period this constructor is private, to avoid consumers from creating * a `Unary` with the fallback properties for `Binary`. */ function Unary(span, sourceSpan, operator, expr, binaryOp, binaryLeft, binaryRight) { var _this = _super.call(this, span, sourceSpan, binaryOp, binaryLeft, binaryRight) || this; _this.operator = operator; _this.expr = expr; return _this; } /** * Creates a unary minus expression "-x", represented as `Binary` using "0 - x". */ Unary.createMinus = function (span, sourceSpan, expr) { return new Unary(span, sourceSpan, '-', expr, '-', new LiteralPrimitive(span, sourceSpan, 0), expr); }; /** * Creates a unary plus expression "+x", represented as `Binary` using "x - 0". */ Unary.createPlus = function (span, sourceSpan, expr) { return new Unary(span, sourceSpan, '+', expr, '-', expr, new LiteralPrimitive(span, sourceSpan, 0)); }; Unary.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } if (visitor.visitUnary !== undefined) { return visitor.visitUnary(this, context); } return visitor.visitBinary(this, context); }; return Unary; }(Binary)); var PrefixNot = /** @class */ (function (_super) { __extends(PrefixNot, _super); function PrefixNot(span, sourceSpan, expression) { var _this = _super.call(this, span, sourceSpan) || this; _this.expression = expression; return _this; } PrefixNot.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitPrefixNot(this, context); }; return PrefixNot; }(AST)); var NonNullAssert = /** @class */ (function (_super) { __extends(NonNullAssert, _super); function NonNullAssert(span, sourceSpan, expression) { var _this = _super.call(this, span, sourceSpan) || this; _this.expression = expression; return _this; } NonNullAssert.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitNonNullAssert(this, context); }; return NonNullAssert; }(AST)); var MethodCall = /** @class */ (function (_super) { __extends(MethodCall, _super); function MethodCall(span, sourceSpan, nameSpan, receiver, name, args, argumentSpan) { var _this = _super.call(this, span, sourceSpan, nameSpan) || this; _this.receiver = receiver; _this.name = name; _this.args = args; _this.argumentSpan = argumentSpan; return _this; } MethodCall.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitMethodCall(this, context); }; return MethodCall; }(ASTWithName)); var SafeMethodCall = /** @class */ (function (_super) { __extends(SafeMethodCall, _super); function SafeMethodCall(span, sourceSpan, nameSpan, receiver, name, args, argumentSpan) { var _this = _super.call(this, span, sourceSpan, nameSpan) || this; _this.receiver = receiver; _this.name = name; _this.args = args; _this.argumentSpan = argumentSpan; return _this; } SafeMethodCall.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitSafeMethodCall(this, context); }; return SafeMethodCall; }(ASTWithName)); var FunctionCall = /** @class */ (function (_super) { __extends(FunctionCall, _super); function FunctionCall(span, sourceSpan, target, args) { var _this = _super.call(this, span, sourceSpan) || this; _this.target = target; _this.args = args; return _this; } FunctionCall.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } return visitor.visitFunctionCall(this, context); }; return FunctionCall; }(AST)); /** * Records the absolute position of a text span in a source file, where `start` and `end` are the * starting and ending byte offsets, respectively, of the text span in a source file. */ var AbsoluteSourceSpan = /** @class */ (function () { function AbsoluteSourceSpan(start, end) { this.start = start; this.end = end; } return AbsoluteSourceSpan; }()); var ASTWithSource = /** @class */ (function (_super) { __extends(ASTWithSource, _super); function ASTWithSource(ast, source, location, absoluteOffset, errors) { var _this = _super.call(this, new ParseSpan(0, source === null ? 0 : source.length), new AbsoluteSourceSpan(absoluteOffset, source === null ? absoluteOffset : absoluteOffset + source.length)) || this; _this.ast = ast; _this.source = source; _this.location = location; _this.errors = errors; return _this; } ASTWithSource.prototype.visit = function (visitor, context) { if (context === void 0) { context = null; } if (visitor.visitASTWithSource) { return visitor.visitASTWithSource(this, context); } return this.ast.visit(visitor, context); }; ASTWithSource.prototype.toString = function () { return this.source + " in " + this.location; }; return ASTWithSource; }(AST)); var VariableBinding = /** @class */ (function () { /** * @param sourceSpan entire span of the binding. * @param key name of the LHS along with its span. * @param value optional value for the RHS along with its span. */ function VariableBinding(sourceSpan, key, value) { this.sourceSpan = sourceSpan; this.key = key; this.value = value; } return VariableBinding; }()); var ExpressionBinding = /** @class */ (function () { /** * @param sourceSpan entire span of the binding. * @param key binding name, like ngForOf, ngForTrackBy, ngIf, along with its * span. Note that the length of the span may not be the same as * `key.source.length`. For example, * 1. key.source = ngFor, key.span is for "ngFor" * 2. key.source = ngForOf, key.span is for "of" * 3. key.source = ngForTrackBy, key.span is for "trackBy" * @param value optional expression for the RHS. */ function ExpressionBinding(sourceSpan, key, value) { this.sourceSpan = sourceSpan; this.key = key; this.value = value; } return ExpressionBinding; }()); var RecursiveAstVisitor$1 = /** @class */ (function () { function RecursiveAstVisitor() { } RecursiveAstVisitor.prototype.visit = function (ast, context) { // The default implementation just visits every node. // Classes that extend RecursiveAstVisitor should override this function // to selectively visit the specified node. ast.visit(this, context); }; RecursiveAstVisitor.prototype.visitUnary = function (ast, context) { this.visit(ast.expr, context); }; RecursiveAstVisitor.prototype.visitBinary = function (ast, context) { this.visit(ast.left, context); this.visit(ast.right, context); }; RecursiveAstVisitor.prototype.visitChain = function (ast, context) { this.visitAll(ast.expressions, context); }; RecursiveAstVisitor.prototype.visitConditional = function (ast, context) { this.visit(ast.condition, context); this.visit(ast.trueExp, context); this.visit(ast.falseExp, context); }; RecursiveAstVisitor.prototype.visitPipe = function (ast, context) { this.visit(ast.exp, context); this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitFunctionCall = function (ast, context) { if (ast.target) { this.visit(ast.target, context); } this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitImplicitReceiver = function (ast, context) { }; RecursiveAstVisitor.prototype.visitThisReceiver = function (ast, context) { }; RecursiveAstVisitor.prototype.visitInterpolation = function (ast, context) { this.visitAll(ast.expressions, context); }; RecursiveAstVisitor.prototype.visitKeyedRead = function (ast, context) { this.visit(ast.receiver, context); this.visit(ast.key, context); }; RecursiveAstVisitor.prototype.visitKeyedWrite = function (ast, context) { this.visit(ast.receiver, context); this.visit(ast.key, context); this.visit(ast.value, context); }; RecursiveAstVisitor.prototype.visitLiteralArray = function (ast, context) { this.visitAll(ast.expressions, context); }; RecursiveAstVisitor.prototype.visitLiteralMap = function (ast, context) { this.visitAll(ast.values, context); }; RecursiveAstVisitor.prototype.visitLiteralPrimitive = function (ast, context) { }; RecursiveAstVisitor.prototype.visitMethodCall = function (ast, context) { this.visit(ast.receiver, context); this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitPrefixNot = function (ast, context) { this.visit(ast.expression, context); }; RecursiveAstVisitor.prototype.visitNonNullAssert = function (ast, context) { this.visit(ast.expression, context); }; RecursiveAstVisitor.prototype.visitPropertyRead = function (ast, context) { this.visit(ast.receiver, context); }; RecursiveAstVisitor.prototype.visitPropertyWrite = function (ast, context) { this.visit(ast.receiver, context); this.visit(ast.value, context); }; RecursiveAstVisitor.prototype.visitSafePropertyRead = function (ast, context) { this.visit(ast.receiver, context); }; RecursiveAstVisitor.prototype.visitSafeMethodCall = function (ast, context) { this.visit(ast.receiver, context); this.visitAll(ast.args, context); }; RecursiveAstVisitor.prototype.visitSafeKeyedRead = function (ast, context) { this.visit(ast.receiver, context); this.visit(ast.key, context); }; RecursiveAstVisitor.prototype.visitQuote = function (ast, context) { }; // This is not part of the AstVisitor interface, just a helper method RecursiveAstVisitor.prototype.visitAll = function (asts, context) { var e_1, _b; try { for (var asts_1 = __values(asts), asts_1_1 = asts_1.next(); !asts_1_1.done; asts_1_1 = asts_1.next()) { var ast = asts_1_1.value; this.visit(ast, context); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (asts_1_1 && !asts_1_1.done && (_b = asts_1.return)) _b.call(asts_1); } finally { if (e_1) throw e_1.error; } } }; return RecursiveAstVisitor; }()); var AstTransformer$1 = /** @class */ (function () { function AstTransformer() { } AstTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; }; AstTransformer.prototype.visitThisReceiver = function (ast, context) { return ast; }; AstTransformer.prototype.visitInterpolation = function (ast, context) { return new Interpolation(ast.span, ast.sourceSpan, ast.strings, this.visitAll(ast.expressions)); }; AstTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return new LiteralPrimitive(ast.span, ast.sourceSpan, ast.value); }; AstTransformer.prototype.visitPropertyRead = function (ast, context) { return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name); }; AstTransformer.prototype.visitPropertyWrite = function (ast, context) { return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, ast.value.visit(this)); }; AstTransformer.prototype.visitSafePropertyRead = function (ast, context) { return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name); }; AstTransformer.prototype.visitMethodCall = function (ast, context) { return new MethodCall(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args), ast.argumentSpan); }; AstTransformer.prototype.visitSafeMethodCall = function (ast, context) { return new SafeMethodCall(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args), ast.argumentSpan); }; AstTransformer.prototype.visitFunctionCall = function (ast, context) { return new FunctionCall(ast.span, ast.sourceSpan, ast.target.visit(this), this.visitAll(ast.args)); }; AstTransformer.prototype.visitLiteralArray = function (ast, context) { return new LiteralArray(ast.span, ast.sourceSpan, this.visitAll(ast.expressions)); }; AstTransformer.prototype.visitLiteralMap = function (ast, context) { return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, this.visitAll(ast.values)); }; AstTransformer.prototype.visitUnary = function (ast, context) { switch (ast.operator) { case '+': return Unary.createPlus(ast.span, ast.sourceSpan, ast.expr.visit(this)); case '-': return Unary.createMinus(ast.span, ast.sourceSpan, ast.expr.visit(this)); default: throw new Error("Unknown unary operator " + ast.operator); } }; AstTransformer.prototype.visitBinary = function (ast, context) { return new Binary(ast.span, ast.sourceSpan, ast.operation, ast.left.visit(this), ast.right.visit(this)); }; AstTransformer.prototype.visitPrefixNot = function (ast, context) { return new PrefixNot(ast.span, ast.sourceSpan, ast.expression.visit(this)); }; AstTransformer.prototype.visitNonNullAssert = function (ast, context) { return new NonNullAssert(ast.span, ast.sourceSpan, ast.expression.visit(this)); }; AstTransformer.prototype.visitConditional = function (ast, context) { return new Conditional(ast.span, ast.sourceSpan, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this)); }; AstTransformer.prototype.visitPipe = function (ast, context) { return new BindingPipe(ast.span, ast.sourceSpan, ast.exp.visit(this), ast.name, this.visitAll(ast.args), ast.nameSpan); }; AstTransformer.prototype.visitKeyedRead = function (ast, context) { return new KeyedRead(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.key.visit(this)); }; AstTransformer.prototype.visitKeyedWrite = function (ast, context) { return new KeyedWrite(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.key.visit(this), ast.value.visit(this)); }; AstTransformer.prototype.visitAll = function (asts) { var res = []; for (var i = 0; i < asts.length; ++i) { res[i] = asts[i].visit(this); } return res; }; AstTransformer.prototype.visitChain = function (ast, context) { return new Chain(ast.span, ast.sourceSpan, this.visitAll(ast.expressions)); }; AstTransformer.prototype.visitQuote = function (ast, context) { return new Quote(ast.span, ast.sourceSpan, ast.prefix, ast.uninterpretedExpression, ast.location); }; AstTransformer.prototype.visitSafeKeyedRead = function (ast, context) { return new SafeKeyedRead(ast.span, ast.sourceSpan, ast.receiver.visit(this), ast.key.visit(this)); }; return AstTransformer; }()); // A transformer that only creates new nodes if the transformer makes a change or // a change is made a child node. var AstMemoryEfficientTransformer = /** @class */ (function () { function AstMemoryEfficientTransformer() { } AstMemoryEfficientTransformer.prototype.visitImplicitReceiver = function (ast, context) { return ast; }; AstMemoryEfficientTransformer.prototype.visitThisReceiver = function (ast, context) { return ast; }; AstMemoryEfficientTransformer.prototype.visitInterpolation = function (ast, context) { var expressions = this.visitAll(ast.expressions); if (expressions !== ast.expressions) return new Interpolation(ast.span, ast.sourceSpan, ast.strings, expressions); return ast; }; AstMemoryEfficientTransformer.prototype.visitLiteralPrimitive = function (ast, context) { return ast; }; AstMemoryEfficientTransformer.prototype.visitPropertyRead = function (ast, context) { var receiver = ast.receiver.visit(this); if (receiver !== ast.receiver) { return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name); } return ast; }; AstMemoryEfficientTransformer.prototype.visitPropertyWrite = function (ast, context) { var receiver = ast.receiver.visit(this); var value = ast.value.visit(this); if (receiver !== ast.receiver || value !== ast.value) { return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, value); } return ast; }; AstMemoryEfficientTransformer.prototype.visitSafePropertyRead = function (ast, context) { var receiver = ast.receiver.visit(this); if (receiver !== ast.receiver) { return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name); } return ast; }; AstMemoryEfficientTransformer.prototype.visitMethodCall = function (ast, context) { var receiver = ast.receiver.visit(this); var args = this.visitAll(ast.args); if (receiver !== ast.receiver || args !== ast.args) { return new MethodCall(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, args, ast.argumentSpan); } return ast; }; AstMemoryEfficientTransformer.prototype.visitSafeMethodCall = function (ast, context) { var receiver = ast.receiver.visit(this); var args = this.visitAll(ast.args); if (receiver !== ast.receiver || args !== ast.args) { return new SafeMethodCall(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, args, ast.argumentSpan); } return ast; }; AstMemoryEfficientTransformer.prototype.visitFunctionCall = function (ast, context) { var target = ast.target && ast.target.visit(this); var args = this.visitAll(ast.args); if (target !== ast.target || args !== ast.args) { return new FunctionCall(ast.span, ast.sourceSpan, target, args); } return ast; }; AstMemoryEfficientTransformer.prototype.visitLiteralArray = function (ast, context) { var expressions = this.visitAll(ast.expressions); if (expressions !== ast.expressions) { return new LiteralArray(ast.span, ast.sourceSpan, expressions); } return ast; }; AstMemoryEfficientTransformer.prototype.visitLiteralMap = function (ast, context) { var values = this.visitAll(ast.values); if (values !== ast.values) { return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, values); } return ast; }; AstMemoryEfficientTransformer.prototype.visitUnary = function (ast, context) { var expr = ast.expr.visit(this); if (expr !== ast.expr) { switch (ast.operator) { case '+': return Unary.createPlus(ast.span, ast.sourceSpan, expr); case '-': return Unary.createMinus(ast.span, ast.sourceSpan, expr); default: throw new Error("Unknown unary operator " + ast.operator); } } return ast; }; AstMemoryEfficientTransformer.prototype.visitBinary = function (ast, context) { var left = ast.left.visit(this); var right = ast.right.visit(this); if (left !== ast.left || right !== ast.right) { return new Binary(ast.span, ast.sourceSpan, ast.operation, left, right); } return ast; }; AstMemoryEfficientTransformer.prototype.visitPrefixNot = function (ast, context) { var expression = ast.expression.visit(this); if (expression !== ast.expression) { return new PrefixNot(ast.span, ast.sourceSpan, expression); } return ast; }; AstMemoryEfficientTransformer.prototype.visitNonNullAssert = function (ast, context) { var expression = ast.expression.visit(this); if (expression !== ast.expression) { return new NonNullAssert(ast.span, ast.sourceSpan, expression); } return ast; }; AstMemoryEfficientTransformer.prototype.visitConditional = function (ast, context) { var condition = ast.condition.visit(this); var trueExp = ast.trueExp.visit(this); var falseExp = ast.falseExp.visit(this); if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) { return new Conditional(ast.span, ast.sourceSpan, condition, trueExp, falseExp); } return ast; }; AstMemoryEfficientTransformer.prototype.visitPipe = function (ast, context) { var exp = ast.exp.visit(this); var args = this.visitAll(ast.args); if (exp !== ast.exp || args !== ast.args) { return new BindingPipe(ast.span, ast.sourceSpan, exp, ast.name, args, ast.nameSpan); } return ast; }; AstMemoryEfficientTransformer.prototype.visitKeyedRead = function (ast, context) { var obj = ast.receiver.visit(this); var key = ast.key.visit(this); if (obj !== ast.receiver || key !== ast.key) { return new KeyedRead(ast.span, ast.sourceSpan, obj, key); } return ast; }; AstMemoryEfficientTransformer.prototype.visitKeyedWrite = function (ast, context) { var obj = ast.receiver.visit(this); var key = ast.key.visit(this); var value = ast.value.visit(this); if (obj !== ast.receiver || key !== ast.key || value !== ast.value) { return new KeyedWrite(ast.span, ast.sourceSpan, obj, key, value); } return ast; }; AstMemoryEfficientTransformer.prototype.visitAll = function (asts) { var res = []; var modified = false; for (var i = 0; i < asts.length; ++i) { var original = asts[i]; var value = original.visit(this); res[i] = value; modified = modified || value !== original; } return modified ? res : asts; }; AstMemoryEfficientTransformer.prototype.visitChain = function (ast, context) { var expressions = this.visitAll(ast.expressions); if (expressions !== ast.expressions) { return new Chain(ast.span, ast.sourceSpan, expressions); } return ast; }; AstMemoryEfficientTransformer.prototype.visitQuote = function (ast, context) { return ast; }; AstMemoryEfficientTransformer.prototype.visitSafeKeyedRead = function (ast, context) { var obj = ast.receiver.visit(this); var key = ast.key.visit(this); if (obj !== ast.receiver || key !== ast.key) { return new SafeKeyedRead(ast.span, ast.sourceSpan, obj, key); } return ast; }; return AstMemoryEfficientTransformer; }()); // Bindings var ParsedProperty = /** @class */ (function () { function ParsedProperty(name, expression, type, // TODO(FW-2095): `keySpan` should really be required but allows `undefined` so VE does // not need to be updated. Make `keySpan` required when VE is removed. sourceSpan, keySpan, valueSpan) { this.name = name; this.expression = expression; this.type = type; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; this.isLiteral = this.type === exports.ParsedPropertyType.LITERAL_ATTR; this.isAnimation = this.type === exports.ParsedPropertyType.ANIMATION; } return ParsedProperty; }()); (function (ParsedPropertyType) { ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT"; ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR"; ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION"; })(exports.ParsedPropertyType || (exports.ParsedPropertyType = {})); var ParsedEvent = /** @class */ (function () { // Regular events have a target // Animation events have a phase function ParsedEvent(name, targetOrPhase, type, handler, sourceSpan, // TODO(FW-2095): keySpan should be required but was made optional to avoid changing VE handlerSpan, keySpan) { this.name = name; this.targetOrPhase = targetOrPhase; this.type = type; this.handler = handler; this.sourceSpan = sourceSpan; this.handlerSpan = handlerSpan; this.keySpan = keySpan; } return ParsedEvent; }()); /** * ParsedVariable represents a variable declaration in a microsyntax expression. */ var ParsedVariable = /** @class */ (function () { function ParsedVariable(name, value, sourceSpan, keySpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; } return ParsedVariable; }()); var BoundElementProperty = /** @class */ (function () { function BoundElementProperty(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan) { this.name = name; this.type = type; this.securityContext = securityContext; this.value = value; this.unit = unit; this.sourceSpan = sourceSpan; this.keySpan = keySpan; this.valueSpan = valueSpan; } return BoundElementProperty; }()); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var CORE$1 = '@angular/core'; var Identifiers$1 = /** @class */ (function () { function Identifiers() { } return Identifiers; }()); Identifiers$1.ANALYZE_FOR_ENTRY_COMPONENTS = { name: 'ANALYZE_FOR_ENTRY_COMPONENTS', moduleName: CORE$1, }; Identifiers$1.ElementRef = { name: 'ElementRef', moduleName: CORE$1 }; Identifiers$1.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE$1 }; Identifiers$1.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE$1 }; Identifiers$1.ChangeDetectorRef = { name: 'ChangeDetectorRef', moduleName: CORE$1, }; Identifiers$1.QueryList = { name: 'QueryList', moduleName: CORE$1 }; Identifiers$1.TemplateRef = { name: 'TemplateRef', moduleName: CORE$1 }; Identifiers$1.Renderer2 = { name: 'Renderer2', moduleName: CORE$1 }; Identifiers$1.CodegenComponentFactoryResolver = { name: 'ɵCodegenComponentFactoryResolver', moduleName: CORE$1, }; Identifiers$1.ComponentFactoryResolver = { name: 'ComponentFactoryResolver', moduleName: CORE$1, }; Identifiers$1.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE$1 }; Identifiers$1.ComponentRef = { name: 'ComponentRef', moduleName: CORE$1 }; Identifiers$1.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE$1 }; Identifiers$1.createModuleFactory = { name: 'ɵcmf', moduleName: CORE$1, }; Identifiers$1.moduleDef = { name: 'ɵmod', moduleName: CORE$1, }; Identifiers$1.moduleProviderDef = { name: 'ɵmpd', moduleName: CORE$1, }; Identifiers$1.RegisterModuleFactoryFn = { name: 'ɵregisterModuleFactory', moduleName: CORE$1, }; Identifiers$1.inject = { name: 'ɵɵinject', moduleName: CORE$1 }; Identifiers$1.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 }; Identifiers$1.INJECTOR = { name: 'INJECTOR', moduleName: CORE$1 }; Identifiers$1.Injector = { name: 'Injector', moduleName: CORE$1 }; Identifiers$1.ViewEncapsulation = { name: 'ViewEncapsulation', moduleName: CORE$1, }; Identifiers$1.ChangeDetectionStrategy = { name: 'ChangeDetectionStrategy', moduleName: CORE$1, }; Identifiers$1.SecurityContext = { name: 'SecurityContext', moduleName: CORE$1, }; Identifiers$1.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE$1 }; Identifiers$1.TRANSLATIONS_FORMAT = { name: 'TRANSLATIONS_FORMAT', moduleName: CORE$1, }; Identifiers$1.inlineInterpolate = { name: 'ɵinlineInterpolate', moduleName: CORE$1, }; Identifiers$1.interpolate = { name: 'ɵinterpolate', moduleName: CORE$1 }; Identifiers$1.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE$1 }; Identifiers$1.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE$1 }; Identifiers$1.Renderer = { name: 'Renderer', moduleName: CORE$1 }; Identifiers$1.viewDef = { name: 'ɵvid', moduleName: CORE$1 }; Identifiers$1.elementDef = { name: 'ɵeld', moduleName: CORE$1 }; Identifiers$1.anchorDef = { name: 'ɵand', moduleName: CORE$1 }; Identifiers$1.textDef = { name: 'ɵted', moduleName: CORE$1 }; Identifiers$1.directiveDef = { name: 'ɵdid', moduleName: CORE$1 }; Identifiers$1.providerDef = { name: 'ɵprd', moduleName: CORE$1 }; Identifiers$1.queryDef = { name: 'ɵqud', moduleName: CORE$1 }; Identifiers$1.pureArrayDef = { name: 'ɵpad', moduleName: CORE$1 }; Identifiers$1.pureObjectDef = { name: 'ɵpod', moduleName: CORE$1 }; Identifiers$1.purePipeDef = { name: 'ɵppd', moduleName: CORE$1 }; Identifiers$1.pipeDef = { name: 'ɵpid', moduleName: CORE$1 }; Identifiers$1.nodeValue = { name: 'ɵnov', moduleName: CORE$1 }; Identifiers$1.ngContentDef = { name: 'ɵncd', moduleName: CORE$1 }; Identifiers$1.unwrapValue = { name: 'ɵunv', moduleName: CORE$1 }; Identifiers$1.createRendererType2 = { name: 'ɵcrt', moduleName: CORE$1 }; // type only Identifiers$1.RendererType2 = { name: 'RendererType2', moduleName: CORE$1, }; // type only Identifiers$1.ViewDefinition = { name: 'ɵViewDefinition', moduleName: CORE$1, }; Identifiers$1.createComponentFactory = { name: 'ɵccf', moduleName: CORE$1 }; function createTokenForReference(reference) { return { identifier: { reference: reference } }; } function createTokenForExternalReference(reflector, reference) { return createTokenForReference(reflector.resolveExternalReference(reference)); } var EventHandlerVars = /** @class */ (function () { function EventHandlerVars() { } return EventHandlerVars; }()); EventHandlerVars.event = variable('$event'); var ConvertActionBindingResult = /** @class */ (function () { function ConvertActionBindingResult( /** * Render2 compatible statements, */ stmts, /** * Variable name used with render2 compatible statements. */ allowDefault) { this.stmts = stmts; this.allowDefault = allowDefault; /** * This is bit of a hack. It converts statements which render2 expects to statements which are * expected by render3. * * Example: `
    ` will generate: * * Render3: * ``` * const pd_b:any = ((ctx.doSomething($event)) !== false); * return pd_b; * ``` * * but render2 expects: * ``` * return ctx.doSomething($event); * ``` */ // TODO(misko): remove this hack once we no longer support ViewEngine. this.render3Stmts = stmts.map(function (statement) { if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name && statement.value instanceof BinaryOperatorExpr) { var lhs = statement.value.lhs; return new ReturnStatement(lhs.value); } return statement; }); } return ConvertActionBindingResult; }()); /** * Converts the given expression AST into an executable output AST, assuming the expression is * used in an action binding (e.g. an event handler). */ function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses, globals) { if (!localResolver) { localResolver = new DefaultLocalResolver(globals); } var actionWithoutBuiltins = convertPropertyBindingBuiltins({ createLiteralArrayConverter: function (argCount) { // Note: no caching for literal arrays in actions. return function (args) { return literalArr(args); }; }, createLiteralMapConverter: function (keys) { // Note: no caching for literal maps in actions. return function (values) { var entries = keys.map(function (k, i) { return ({ key: k.key, value: values[i], quoted: k.quoted, }); }); return literalMap(entries); }; }, createPipeConverter: function (name) { throw new Error("Illegal State: Actions are not allowed to contain pipes. Pipe: " + name); } }, action); var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses); var actionStmts = []; flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts); prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts); if (visitor.usesImplicitReceiver) { localResolver.notifyImplicitReceiverUse(); } var lastIndex = actionStmts.length - 1; var preventDefaultVar = null; if (lastIndex >= 0) { var lastStatement = actionStmts[lastIndex]; var returnExpr = convertStmtIntoExpression(lastStatement); if (returnExpr) { // Note: We need to cast the result of the method call to dynamic, // as it might be a void method! preventDefaultVar = createPreventDefaultVar(bindingId); actionStmts[lastIndex] = preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false))) .toDeclStmt(null, [exports.StmtModifier.Final]); } } return new ConvertActionBindingResult(actionStmts, preventDefaultVar); } function convertPropertyBindingBuiltins(converterFactory, ast) { return convertBuiltins(converterFactory, ast); } var ConvertPropertyBindingResult = /** @class */ (function () { function ConvertPropertyBindingResult(stmts, currValExpr) { this.stmts = stmts; this.currValExpr = currValExpr; } return ConvertPropertyBindingResult; }()); var BindingForm; (function (BindingForm) { // The general form of binding expression, supports all expressions. BindingForm[BindingForm["General"] = 0] = "General"; // Try to generate a simple binding (no temporaries or statements) // otherwise generate a general binding BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple"; // Inlines assignment of temporaries into the generated expression. The result may still // have statements attached for declarations of temporary variables. // This is the only relevant form for Ivy, the other forms are only used in ViewEngine. BindingForm[BindingForm["Expression"] = 2] = "Expression"; })(BindingForm || (BindingForm = {})); /** * Converts the given expression AST into an executable output AST, assuming the expression * is used in property binding. The expression has to be preprocessed via * `convertPropertyBindingBuiltins`. */ function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) { if (!localResolver) { localResolver = new DefaultLocalResolver(); } var visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction); var outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression); var stmts = getStatementsFromVisitor(visitor, bindingId); if (visitor.usesImplicitReceiver) { localResolver.notifyImplicitReceiverUse(); } if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) { return new ConvertPropertyBindingResult([], outputExpr); } else if (form === BindingForm.Expression) { return new ConvertPropertyBindingResult(stmts, outputExpr); } var currValExpr = createCurrValueExpr(bindingId); stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [exports.StmtModifier.Final])); return new ConvertPropertyBindingResult(stmts, currValExpr); } /** * Given some expression, such as a binding or interpolation expression, and a context expression to * look values up on, visit each facet of the given expression resolving values from the context * expression such that a list of arguments can be derived from the found values that can be used as * arguments to an external update instruction. * * @param localResolver The resolver to use to look up expressions by name appropriately * @param contextVariableExpression The expression representing the context variable used to create * the final argument expressions * @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to * be resolved and what arguments list to build. * @param bindingId A name prefix used to create temporary variable names if they're needed for the * arguments generated * @returns An array of expressions that can be passed as arguments to instruction expressions like * `o.importExpr(R3.propertyInterpolate).callFn(result)` */ function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) { var visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined); var outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression); if (visitor.usesImplicitReceiver) { localResolver.notifyImplicitReceiverUse(); } var stmts = getStatementsFromVisitor(visitor, bindingId); // Removing the first argument, because it was a length for ViewEngine, not Ivy. var args = outputExpr.args.slice(1); if (expressionWithArgumentsToExtract instanceof Interpolation) { // If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the // args returned to just the value, because we're going to pass it to a special instruction. var strings = expressionWithArgumentsToExtract.strings; if (args.length === 3 && strings[0] === '' && strings[1] === '') { // Single argument interpolate instructions. args = [args[1]]; } else if (args.length >= 19) { // 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept // an array of arguments args = [literalArr(args)]; } } return { stmts: stmts, args: args }; } function getStatementsFromVisitor(visitor, bindingId) { var stmts = []; for (var i = 0; i < visitor.temporaryCount; i++) { stmts.push(temporaryDeclaration(bindingId, i)); } return stmts; } function convertBuiltins(converterFactory, ast) { var visitor = new _BuiltinAstConverter(converterFactory); return ast.visit(visitor); } function temporaryName(bindingId, temporaryNumber) { return "tmp_" + bindingId + "_" + temporaryNumber; } function temporaryDeclaration(bindingId, temporaryNumber) { return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber)); } function prependTemporaryDecls(temporaryCount, bindingId, statements) { for (var i = temporaryCount - 1; i >= 0; i--) { statements.unshift(temporaryDeclaration(bindingId, i)); } } var _Mode; (function (_Mode) { _Mode[_Mode["Statement"] = 0] = "Statement"; _Mode[_Mode["Expression"] = 1] = "Expression"; })(_Mode || (_Mode = {})); function ensureStatementMode(mode, ast) { if (mode !== _Mode.Statement) { throw new Error("Expected a statement, but saw " + ast); } } function ensureExpressionMode(mode, ast) { if (mode !== _Mode.Expression) { throw new Error("Expected an expression, but saw " + ast); } } function convertToStatementIfNeeded(mode, expr) { if (mode === _Mode.Statement) { return expr.toStmt(); } else { return expr; } } var _BuiltinAstConverter = /** @class */ (function (_super) { __extends(_BuiltinAstConverter, _super); function _BuiltinAstConverter(_converterFactory) { var _this = _super.call(this) || this; _this._converterFactory = _converterFactory; return _this; } _BuiltinAstConverter.prototype.visitPipe = function (ast, context) { var _this = this; var args = __spreadArray([ast.exp], __read(ast.args)).map(function (ast) { return ast.visit(_this, context); }); return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createPipeConverter(ast.name, args.length)); }; _BuiltinAstConverter.prototype.visitLiteralArray = function (ast, context) { var _this = this; var args = ast.expressions.map(function (ast) { return ast.visit(_this, context); }); return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length)); }; _BuiltinAstConverter.prototype.visitLiteralMap = function (ast, context) { var _this = this; var args = ast.values.map(function (ast) { return ast.visit(_this, context); }); return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralMapConverter(ast.keys)); }; return _BuiltinAstConverter; }(AstTransformer$1)); var _AstToIrVisitor = /** @class */ (function () { function _AstToIrVisitor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses) { this._localResolver = _localResolver; this._implicitReceiver = _implicitReceiver; this.bindingId = bindingId; this.interpolationFunction = interpolationFunction; this.baseSourceSpan = baseSourceSpan; this.implicitReceiverAccesses = implicitReceiverAccesses; this._nodeMap = new Map(); this._resultMap = new Map(); this._currentTemporary = 0; this.temporaryCount = 0; this.usesImplicitReceiver = false; } _AstToIrVisitor.prototype.visitUnary = function (ast, mode) { var op; switch (ast.operator) { case '+': op = exports.UnaryOperator.Plus; break; case '-': op = exports.UnaryOperator.Minus; break; default: throw new Error("Unsupported operator " + ast.operator); } return convertToStatementIfNeeded(mode, new UnaryOperatorExpr(op, this._visit(ast.expr, _Mode.Expression), undefined, this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype.visitBinary = function (ast, mode) { var op; switch (ast.operation) { case '+': op = exports.BinaryOperator.Plus; break; case '-': op = exports.BinaryOperator.Minus; break; case '*': op = exports.BinaryOperator.Multiply; break; case '/': op = exports.BinaryOperator.Divide; break; case '%': op = exports.BinaryOperator.Modulo; break; case '&&': op = exports.BinaryOperator.And; break; case '||': op = exports.BinaryOperator.Or; break; case '==': op = exports.BinaryOperator.Equals; break; case '!=': op = exports.BinaryOperator.NotEquals; break; case '===': op = exports.BinaryOperator.Identical; break; case '!==': op = exports.BinaryOperator.NotIdentical; break; case '<': op = exports.BinaryOperator.Lower; break; case '>': op = exports.BinaryOperator.Bigger; break; case '<=': op = exports.BinaryOperator.LowerEquals; break; case '>=': op = exports.BinaryOperator.BiggerEquals; break; case '??': return this.convertNullishCoalesce(ast, mode); default: throw new Error("Unsupported operation " + ast.operation); } return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype.visitChain = function (ast, mode) { ensureStatementMode(mode, ast); return this.visitAll(ast.expressions, mode); }; _AstToIrVisitor.prototype.visitConditional = function (ast, mode) { var value = this._visit(ast.condition, _Mode.Expression); return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype.visitPipe = function (ast, mode) { throw new Error("Illegal state: Pipes should have been converted into functions. Pipe: " + ast.name); }; _AstToIrVisitor.prototype.visitFunctionCall = function (ast, mode) { var convertedArgs = this.visitAll(ast.args, _Mode.Expression); var fnResult; if (ast instanceof BuiltinFunctionCall) { fnResult = ast.converter(convertedArgs); } else { fnResult = this._visit(ast.target, _Mode.Expression) .callFn(convertedArgs, this.convertSourceSpan(ast.span)); } return convertToStatementIfNeeded(mode, fnResult); }; _AstToIrVisitor.prototype.visitImplicitReceiver = function (ast, mode) { ensureExpressionMode(mode, ast); this.usesImplicitReceiver = true; return this._implicitReceiver; }; _AstToIrVisitor.prototype.visitThisReceiver = function (ast, mode) { return this.visitImplicitReceiver(ast, mode); }; _AstToIrVisitor.prototype.visitInterpolation = function (ast, mode) { ensureExpressionMode(mode, ast); var args = [literal(ast.expressions.length)]; for (var i = 0; i < ast.strings.length - 1; i++) { args.push(literal(ast.strings[i])); args.push(this._visit(ast.expressions[i], _Mode.Expression)); } args.push(literal(ast.strings[ast.strings.length - 1])); if (this.interpolationFunction) { return this.interpolationFunction(args); } return ast.expressions.length <= 9 ? importExpr(Identifiers$1.inlineInterpolate).callFn(args) : importExpr(Identifiers$1.interpolate).callFn([ args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span)) ]); }; _AstToIrVisitor.prototype.visitKeyedRead = function (ast, mode) { var leftMostSafe = this.leftMostSafeNode(ast); if (leftMostSafe) { return this.convertSafeAccess(ast, leftMostSafe, mode); } else { return convertToStatementIfNeeded(mode, this._visit(ast.receiver, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression))); } }; _AstToIrVisitor.prototype.visitKeyedWrite = function (ast, mode) { var obj = this._visit(ast.receiver, _Mode.Expression); var key = this._visit(ast.key, _Mode.Expression); var value = this._visit(ast.value, _Mode.Expression); if (obj === this._implicitReceiver) { this._localResolver.maybeRestoreView(); } return convertToStatementIfNeeded(mode, obj.key(key).set(value)); }; _AstToIrVisitor.prototype.visitLiteralArray = function (ast, mode) { throw new Error("Illegal State: literal arrays should have been converted into functions"); }; _AstToIrVisitor.prototype.visitLiteralMap = function (ast, mode) { throw new Error("Illegal State: literal maps should have been converted into functions"); }; _AstToIrVisitor.prototype.visitLiteralPrimitive = function (ast, mode) { // For literal values of null, undefined, true, or false allow type interference // to infer the type. var type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ? INFERRED_TYPE : undefined; return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span))); }; _AstToIrVisitor.prototype._getLocal = function (name, receiver) { var _a; if (((_a = this._localResolver.globals) === null || _a === void 0 ? void 0 : _a.has(name)) && receiver instanceof ThisReceiver) { return null; } return this._localResolver.getLocal(name); }; _AstToIrVisitor.prototype.visitMethodCall = function (ast, mode) { if (ast.receiver instanceof ImplicitReceiver && !(ast.receiver instanceof ThisReceiver) && ast.name === '$any') { var args = this.visitAll(ast.args, _Mode.Expression); if (args.length != 1) { throw new Error("Invalid call to $any, expected 1 argument but received " + (args.length || 'none')); } return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span)); } var leftMostSafe = this.leftMostSafeNode(ast); if (leftMostSafe) { return this.convertSafeAccess(ast, leftMostSafe, mode); } else { var args = this.visitAll(ast.args, _Mode.Expression); var prevUsesImplicitReceiver = this.usesImplicitReceiver; var result = null; var receiver = this._visit(ast.receiver, _Mode.Expression); if (receiver === this._implicitReceiver) { var varExpr = this._getLocal(ast.name, ast.receiver); if (varExpr) { // Restore the previous "usesImplicitReceiver" state since the implicit // receiver has been replaced with a resolved local expression. this.usesImplicitReceiver = prevUsesImplicitReceiver; result = varExpr.callFn(args); this.addImplicitReceiverAccess(ast.name); } } if (result == null) { result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span)); } return convertToStatementIfNeeded(mode, result); } }; _AstToIrVisitor.prototype.visitPrefixNot = function (ast, mode) { return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression))); }; _AstToIrVisitor.prototype.visitNonNullAssert = function (ast, mode) { return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression))); }; _AstToIrVisitor.prototype.visitPropertyRead = function (ast, mode) { var leftMostSafe = this.leftMostSafeNode(ast); if (leftMostSafe) { return this.convertSafeAccess(ast, leftMostSafe, mode); } else { var result = null; var prevUsesImplicitReceiver = this.usesImplicitReceiver; var receiver = this._visit(ast.receiver, _Mode.Expression); if (receiver === this._implicitReceiver) { result = this._getLocal(ast.name, ast.receiver); if (result) { // Restore the previous "usesImplicitReceiver" state since the implicit // receiver has been replaced with a resolved local expression. this.usesImplicitReceiver = prevUsesImplicitReceiver; this.addImplicitReceiverAccess(ast.name); } } if (result == null) { result = receiver.prop(ast.name); } return convertToStatementIfNeeded(mode, result); } }; _AstToIrVisitor.prototype.visitPropertyWrite = function (ast, mode) { var receiver = this._visit(ast.receiver, _Mode.Expression); var prevUsesImplicitReceiver = this.usesImplicitReceiver; var varExpr = null; if (receiver === this._implicitReceiver) { var localExpr = this._getLocal(ast.name, ast.receiver); if (localExpr) { if (localExpr instanceof ReadPropExpr) { // If the local variable is a property read expression, it's a reference // to a 'context.property' value and will be used as the target of the // write expression. varExpr = localExpr; // Restore the previous "usesImplicitReceiver" state since the implicit // receiver has been replaced with a resolved local expression. this.usesImplicitReceiver = prevUsesImplicitReceiver; this.addImplicitReceiverAccess(ast.name); } else { // Otherwise it's an error. var receiver_1 = ast.name; var value = (ast.value instanceof PropertyRead) ? ast.value.name : undefined; throw new Error("Cannot assign value \"" + value + "\" to template variable \"" + receiver_1 + "\". Template variables are read-only."); } } } // If no local expression could be produced, use the original receiver's // property as the target. if (varExpr === null) { varExpr = receiver.prop(ast.name); } return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression))); }; _AstToIrVisitor.prototype.visitSafePropertyRead = function (ast, mode) { return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode); }; _AstToIrVisitor.prototype.visitSafeMethodCall = function (ast, mode) { return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode); }; _AstToIrVisitor.prototype.visitSafeKeyedRead = function (ast, mode) { return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode); }; _AstToIrVisitor.prototype.visitAll = function (asts, mode) { var _this = this; return asts.map(function (ast) { return _this._visit(ast, mode); }); }; _AstToIrVisitor.prototype.visitQuote = function (ast, mode) { throw new Error("Quotes are not supported for evaluation!\n Statement: " + ast.uninterpretedExpression + " located at " + ast.location); }; _AstToIrVisitor.prototype._visit = function (ast, mode) { var result = this._resultMap.get(ast); if (result) return result; return (this._nodeMap.get(ast) || ast).visit(this, mode); }; _AstToIrVisitor.prototype.convertSafeAccess = function (ast, leftMostSafe, mode) { // If the expression contains a safe access node on the left it needs to be converted to // an expression that guards the access to the member by checking the receiver for blank. As // execution proceeds from left to right, the left most part of the expression must be guarded // first but, because member access is left associative, the right side of the expression is at // the top of the AST. The desired result requires lifting a copy of the left part of the // expression up to test it for blank before generating the unguarded version. // Consider, for example the following expression: a?.b.c?.d.e // This results in the ast: // . // / \ // ?. e // / \ // . d // / \ // ?. c // / \ // a b // The following tree should be generated: // // /---- ? ----\ // / | \ // a /--- ? ---\ null // / | \ // . . null // / \ / \ // . c . e // / \ / \ // a b . d // / \ // . c // / \ // a b // // Notice that the first guard condition is the left hand of the left most safe access node // which comes in as leftMostSafe to this routine. var guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression); var temporary = undefined; if (this.needsTemporaryInSafeAccess(leftMostSafe.receiver)) { // If the expression has method calls or pipes then we need to save the result into a // temporary variable to avoid calling stateful or impure code more than once. temporary = this.allocateTemporary(); // Preserve the result in the temporary variable guardedExpression = temporary.set(guardedExpression); // Ensure all further references to the guarded expression refer to the temporary instead. this._resultMap.set(leftMostSafe.receiver, temporary); } var condition = guardedExpression.isBlank(); // Convert the ast to an unguarded access to the receiver's member. The map will substitute // leftMostNode with its unguarded version in the call to `this.visit()`. if (leftMostSafe instanceof SafeMethodCall) { this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args, leftMostSafe.argumentSpan)); } else if (leftMostSafe instanceof SafeKeyedRead) { this._nodeMap.set(leftMostSafe, new KeyedRead(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.receiver, leftMostSafe.key)); } else { this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan, leftMostSafe.receiver, leftMostSafe.name)); } // Recursively convert the node now without the guarded member access. var access = this._visit(ast, _Mode.Expression); // Remove the mapping. This is not strictly required as the converter only traverses each node // once but is safer if the conversion is changed to traverse the nodes more than once. this._nodeMap.delete(leftMostSafe); // If we allocated a temporary, release it. if (temporary) { this.releaseTemporary(temporary); } // Produce the conditional return convertToStatementIfNeeded(mode, condition.conditional(NULL_EXPR, access)); }; _AstToIrVisitor.prototype.convertNullishCoalesce = function (ast, mode) { var left = this._visit(ast.left, _Mode.Expression); var right = this._visit(ast.right, _Mode.Expression); var temporary = this.allocateTemporary(); this.releaseTemporary(temporary); // Generate the following expression. It is identical to how TS // transpiles binary expressions with a nullish coalescing operator. // let temp; // (temp = a) !== null && temp !== undefined ? temp : b; return convertToStatementIfNeeded(mode, temporary.set(left) .notIdentical(NULL_EXPR) .and(temporary.notIdentical(literal(undefined))) .conditional(temporary, right)); }; // Given an expression of the form a?.b.c?.d.e then the left most safe node is // the (a?.b). The . and ?. are left associative thus can be rewritten as: // ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or // safe method call as this needs to be transformed initially to: // a == null ? null : a.c.b.c?.d.e // then to: // a == null ? null : a.b.c == null ? null : a.b.c.d.e _AstToIrVisitor.prototype.leftMostSafeNode = function (ast) { var _this = this; var visit = function (visitor, ast) { return (_this._nodeMap.get(ast) || ast).visit(visitor); }; return ast.visit({ visitUnary: function (ast) { return null; }, visitBinary: function (ast) { return null; }, visitChain: function (ast) { return null; }, visitConditional: function (ast) { return null; }, visitFunctionCall: function (ast) { return null; }, visitImplicitReceiver: function (ast) { return null; }, visitThisReceiver: function (ast) { return null; }, visitInterpolation: function (ast) { return null; }, visitKeyedRead: function (ast) { return visit(this, ast.receiver); }, visitKeyedWrite: function (ast) { return null; }, visitLiteralArray: function (ast) { return null; }, visitLiteralMap: function (ast) { return null; }, visitLiteralPrimitive: function (ast) { return null; }, visitMethodCall: function (ast) { return visit(this, ast.receiver); }, visitPipe: function (ast) { return null; }, visitPrefixNot: function (ast) { return null; }, visitNonNullAssert: function (ast) { return null; }, visitPropertyRead: function (ast) { return visit(this, ast.receiver); }, visitPropertyWrite: function (ast) { return null; }, visitQuote: function (ast) { return null; }, visitSafeMethodCall: function (ast) { return visit(this, ast.receiver) || ast; }, visitSafePropertyRead: function (ast) { return visit(this, ast.receiver) || ast; }, visitSafeKeyedRead: function (ast) { return visit(this, ast.receiver) || ast; } }); }; // Returns true of the AST includes a method or a pipe indicating that, if the // expression is used as the target of a safe property or method access then // the expression should be stored into a temporary variable. _AstToIrVisitor.prototype.needsTemporaryInSafeAccess = function (ast) { var _this = this; var visit = function (visitor, ast) { return ast && (_this._nodeMap.get(ast) || ast).visit(visitor); }; var visitSome = function (visitor, ast) { return ast.some(function (ast) { return visit(visitor, ast); }); }; return ast.visit({ visitUnary: function (ast) { return visit(this, ast.expr); }, visitBinary: function (ast) { return visit(this, ast.left) || visit(this, ast.right); }, visitChain: function (ast) { return false; }, visitConditional: function (ast) { return visit(this, ast.condition) || visit(this, ast.trueExp) || visit(this, ast.falseExp); }, visitFunctionCall: function (ast) { return true; }, visitImplicitReceiver: function (ast) { return false; }, visitThisReceiver: function (ast) { return false; }, visitInterpolation: function (ast) { return visitSome(this, ast.expressions); }, visitKeyedRead: function (ast) { return false; }, visitKeyedWrite: function (ast) { return false; }, visitLiteralArray: function (ast) { return true; }, visitLiteralMap: function (ast) { return true; }, visitLiteralPrimitive: function (ast) { return false; }, visitMethodCall: function (ast) { return true; }, visitPipe: function (ast) { return true; }, visitPrefixNot: function (ast) { return visit(this, ast.expression); }, visitNonNullAssert: function (ast) { return visit(this, ast.expression); }, visitPropertyRead: function (ast) { return false; }, visitPropertyWrite: function (ast) { return false; }, visitQuote: function (ast) { return false; }, visitSafeMethodCall: function (ast) { return true; }, visitSafePropertyRead: function (ast) { return false; }, visitSafeKeyedRead: function (ast) { return false; } }); }; _AstToIrVisitor.prototype.allocateTemporary = function () { var tempNumber = this._currentTemporary++; this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount); return new ReadVarExpr(temporaryName(this.bindingId, tempNumber)); }; _AstToIrVisitor.prototype.releaseTemporary = function (temporary) { this._currentTemporary--; if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) { throw new Error("Temporary " + temporary.name + " released out of order"); } }; /** * Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`. * * `ParseSpan` objects are relative to the start of the expression. * This method converts these to full `ParseSourceSpan` objects that * show where the span is within the overall source file. * * @param span the relative span to convert. * @returns a `ParseSourceSpan` for the given span or null if no * `baseSourceSpan` was provided to this class. */ _AstToIrVisitor.prototype.convertSourceSpan = function (span) { if (this.baseSourceSpan) { var start = this.baseSourceSpan.start.moveBy(span.start); var end = this.baseSourceSpan.start.moveBy(span.end); var fullStart = this.baseSourceSpan.fullStart.moveBy(span.start); return new ParseSourceSpan(start, end, fullStart); } else { return null; } }; /** Adds the name of an AST to the list of implicit receiver accesses. */ _AstToIrVisitor.prototype.addImplicitReceiverAccess = function (name) { if (this.implicitReceiverAccesses) { this.implicitReceiverAccesses.add(name); } }; return _AstToIrVisitor; }()); function flattenStatements(arg, output) { if (Array.isArray(arg)) { arg.forEach(function (entry) { return flattenStatements(entry, output); }); } else { output.push(arg); } } var DefaultLocalResolver = /** @class */ (function () { function DefaultLocalResolver(globals) { this.globals = globals; } DefaultLocalResolver.prototype.notifyImplicitReceiverUse = function () { }; DefaultLocalResolver.prototype.maybeRestoreView = function () { }; DefaultLocalResolver.prototype.getLocal = function (name) { if (name === EventHandlerVars.event.name) { return EventHandlerVars.event; } return null; }; return DefaultLocalResolver; }()); function createCurrValueExpr(bindingId) { return variable("currVal_" + bindingId); // fix syntax highlighting: ` } function createPreventDefaultVar(bindingId) { return variable("pd_" + bindingId); } function convertStmtIntoExpression(stmt) { if (stmt instanceof ExpressionStatement) { return stmt.expr; } else if (stmt instanceof ReturnStatement) { return stmt.value; } return null; } var BuiltinFunctionCall = /** @class */ (function (_super) { __extends(BuiltinFunctionCall, _super); function BuiltinFunctionCall(span, sourceSpan, args, converter) { var _this = _super.call(this, span, sourceSpan, null, args) || this; _this.converter = converter; return _this; } return BuiltinFunctionCall; }(FunctionCall)); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * This file is a port of shadowCSS from webcomponents.js to TypeScript. * * Please make sure to keep to edits in sync with the source file. * * Source: * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js * * The original file level comment is reproduced below */ /* This is a limited shim for ShadowDOM css styling. https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles The intention here is to support only the styling features which can be relatively simply implemented. The goal is to allow users to avoid the most obvious pitfalls and do so without compromising performance significantly. For ShadowDOM styling that's not covered here, a set of best practices can be provided that should allow users to accomplish more complex styling. The following is a list of specific ShadowDOM styling features and a brief discussion of the approach used to shim. Shimmed features: * :host, :host-context: ShadowDOM allows styling of the shadowRoot's host element using the :host rule. To shim this feature, the :host styles are reformatted and prefixed with a given scope name and promoted to a document level stylesheet. For example, given a scope name of .foo, a rule like this: :host { background: red; } } becomes: .foo { background: red; } * encapsulation: Styles defined within ShadowDOM, apply only to dom inside the ShadowDOM. Polymer uses one of two techniques to implement this feature. By default, rules are prefixed with the host element tag name as a descendant selector. This ensures styling does not leak out of the 'top' of the element's ShadowDOM. For example, div { font-weight: bold; } becomes: x-foo div { font-weight: bold; } becomes: Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then selectors are scoped by adding an attribute selector suffix to each simple selector that contains the host element tag name. Each element in the element's ShadowDOM template is also given the scope attribute. Thus, these rules match only elements that have the scope attribute. For example, given a scope name of x-foo, a rule like this: div { font-weight: bold; } becomes: div[x-foo] { font-weight: bold; } Note that elements that are dynamically added to a scope must have the scope selector added to them manually. * upper/lower bound encapsulation: Styles which are defined outside a shadowRoot should not cross the ShadowDOM boundary and should not apply inside a shadowRoot. This styling behavior is not emulated. Some possible ways to do this that were rejected due to complexity and/or performance concerns include: (1) reset every possible property for every possible selector for a given scope name; (2) re-implement css in javascript. As an alternative, users should make sure to use selectors specific to the scope in which they are working. * ::distributed: This behavior is not emulated. It's often not necessary to style the contents of a specific insertion point and instead, descendants of the host element can be styled selectively. Users can also create an extra node around an insertion point and style that node's contents via descendent selectors. For example, with a shadowRoot like this: could become:
    Note the use of @polyfill in the comment above a ShadowDOM specific style declaration. This is a directive to the styling shim to use the selector in comments in lieu of the next selector when running under polyfill. */ var ShadowCss = /** @class */ (function () { function ShadowCss() { this.strictStyling = true; } /* * Shim some cssText with the given selector. Returns cssText that can * be included in the document via WebComponents.ShadowCSS.addCssToDocument(css). * * When strictStyling is true: * - selector is the attribute added to all elements inside the host, * - hostSelector is the attribute added to the host itself. */ ShadowCss.prototype.shimCssText = function (cssText, selector, hostSelector) { if (hostSelector === void 0) { hostSelector = ''; } var commentsWithHash = extractCommentsWithHash(cssText); cssText = stripComments(cssText); cssText = this._insertDirectives(cssText); var scopedCssText = this._scopeCssText(cssText, selector, hostSelector); return __spreadArray([scopedCssText], __read(commentsWithHash)).join('\n'); }; ShadowCss.prototype._insertDirectives = function (cssText) { cssText = this._insertPolyfillDirectivesInCssText(cssText); return this._insertPolyfillRulesInCssText(cssText); }; /* * Process styles to convert native ShadowDOM rules that will trip * up the css parser; we rely on decorating the stylesheet with inert rules. * * For example, we convert this rule: * * polyfill-next-selector { content: ':host menu-item'; } * ::content menu-item { * * to this: * * scopeName menu-item { * **/ ShadowCss.prototype._insertPolyfillDirectivesInCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments return cssText.replace(_cssContentNextSelectorRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } return m[2] + '{'; }); }; /* * Process styles to add rules which will only apply under the polyfill * * For example, we convert this rule: * * polyfill-rule { * content: ':host menu-item'; * ... * } * * to this: * * scopeName menu-item {...} * **/ ShadowCss.prototype._insertPolyfillRulesInCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments return cssText.replace(_cssContentRuleRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } var rule = m[0].replace(m[1], '').replace(m[2], ''); return m[4] + rule; }); }; /* Ensure styles are scoped. Pseudo-scoping takes a rule like: * * .foo {... } * * and converts this to * * scopeName .foo { ... } */ ShadowCss.prototype._scopeCssText = function (cssText, scopeSelector, hostSelector) { var unscopedRules = this._extractUnscopedRulesFromCssText(cssText); // replace :host and :host-context -shadowcsshost and -shadowcsshost respectively cssText = this._insertPolyfillHostInCssText(cssText); cssText = this._convertColonHost(cssText); cssText = this._convertColonHostContext(cssText); cssText = this._convertShadowDOMSelectors(cssText); if (scopeSelector) { cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector); } cssText = cssText + '\n' + unscopedRules; return cssText.trim(); }; /* * Process styles to add rules which will only apply under the polyfill * and do not process via CSSOM. (CSSOM is destructive to rules on rare * occasions, e.g. -webkit-calc on Safari.) * For example, we convert this rule: * * @polyfill-unscoped-rule { * content: 'menu-item'; * ... } * * to this: * * menu-item {...} * **/ ShadowCss.prototype._extractUnscopedRulesFromCssText = function (cssText) { // Difference with webcomponents.js: does not handle comments var r = ''; var m; _cssContentUnscopedRuleRe.lastIndex = 0; while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) { var rule = m[0].replace(m[2], '').replace(m[1], m[4]); r += rule + '\n\n'; } return r; }; /* * convert a rule like :host(.foo) > .bar { } * * to * * .foo > .bar */ ShadowCss.prototype._convertColonHost = function (cssText) { return cssText.replace(_cssColonHostRe, function (_, hostSelectors, otherSelectors) { var e_1, _b; if (hostSelectors) { var convertedSelectors = []; var hostSelectorArray = hostSelectors.split(',').map(function (p) { return p.trim(); }); try { for (var hostSelectorArray_1 = __values(hostSelectorArray), hostSelectorArray_1_1 = hostSelectorArray_1.next(); !hostSelectorArray_1_1.done; hostSelectorArray_1_1 = hostSelectorArray_1.next()) { var hostSelector = hostSelectorArray_1_1.value; if (!hostSelector) break; var convertedSelector = _polyfillHostNoCombinator + hostSelector.replace(_polyfillHost, '') + otherSelectors; convertedSelectors.push(convertedSelector); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (hostSelectorArray_1_1 && !hostSelectorArray_1_1.done && (_b = hostSelectorArray_1.return)) _b.call(hostSelectorArray_1); } finally { if (e_1) throw e_1.error; } } return convertedSelectors.join(','); } else { return _polyfillHostNoCombinator + otherSelectors; } }); }; /* * convert a rule like :host-context(.foo) > .bar { } * * to * * .foo > .bar, .foo > .bar { } * * and * * :host-context(.foo:host) .bar { ... } * * to * * .foo .bar { ... } */ ShadowCss.prototype._convertColonHostContext = function (cssText) { return cssText.replace(_cssColonHostContextReGlobal, function (selectorText) { // We have captured a selector that contains a `:host-context` rule. var _a; // For backward compatibility `:host-context` may contain a comma separated list of selectors. // Each context selector group will contain a list of host-context selectors that must match // an ancestor of the host. // (Normally `contextSelectorGroups` will only contain a single array of context selectors.) var contextSelectorGroups = [[]]; // There may be more than `:host-context` in this selector so `selectorText` could look like: // `:host-context(.one):host-context(.two)`. // Execute `_cssColonHostContextRe` over and over until we have extracted all the // `:host-context` selectors from this selector. var match; while (match = _cssColonHostContextRe.exec(selectorText)) { // `match` = [':host-context()', , ] // The `` could actually be a comma separated list: `:host-context(.one, .two)`. var newContextSelectors = ((_a = match[1]) !== null && _a !== void 0 ? _a : '').trim().split(',').map(function (m) { return m.trim(); }).filter(function (m) { return m !== ''; }); // We must duplicate the current selector group for each of these new selectors. // For example if the current groups are: // ``` // [ // ['a', 'b', 'c'], // ['x', 'y', 'z'], // ] // ``` // And we have a new set of comma separated selectors: `:host-context(m,n)` then the new // groups are: // ``` // [ // ['a', 'b', 'c', 'm'], // ['x', 'y', 'z', 'm'], // ['a', 'b', 'c', 'n'], // ['x', 'y', 'z', 'n'], // ] // ``` var contextSelectorGroupsLength = contextSelectorGroups.length; repeatGroups(contextSelectorGroups, newContextSelectors.length); for (var i = 0; i < newContextSelectors.length; i++) { for (var j = 0; j < contextSelectorGroupsLength; j++) { contextSelectorGroups[j + (i * contextSelectorGroupsLength)].push(newContextSelectors[i]); } } // Update the `selectorText` and see repeat to see if there are more `:host-context`s. selectorText = match[2]; } // The context selectors now must be combined with each other to capture all the possible // selectors that `:host-context` can match. See `combineHostContextSelectors()` for more // info about how this is done. return contextSelectorGroups .map(function (contextSelectors) { return combineHostContextSelectors(contextSelectors, selectorText); }) .join(', '); }); }; /* * Convert combinators like ::shadow and pseudo-elements like ::content * by replacing with space. */ ShadowCss.prototype._convertShadowDOMSelectors = function (cssText) { return _shadowDOMSelectorsRe.reduce(function (result, pattern) { return result.replace(pattern, ' '); }, cssText); }; // change a selector like 'div' to 'name div' ShadowCss.prototype._scopeSelectors = function (cssText, scopeSelector, hostSelector) { var _this = this; return processRules(cssText, function (rule) { var selector = rule.selector; var content = rule.content; if (rule.selector[0] !== '@') { selector = _this._scopeSelector(rule.selector, scopeSelector, hostSelector, _this.strictStyling); } else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') || rule.selector.startsWith('@document')) { content = _this._scopeSelectors(rule.content, scopeSelector, hostSelector); } else if (rule.selector.startsWith('@font-face') || rule.selector.startsWith('@page')) { content = _this._stripScopingSelectors(rule.content); } return new CssRule(selector, content); }); }; /** * Handle a css text that is within a rule that should not contain scope selectors by simply * removing them! An example of such a rule is `@font-face`. * * `@font-face` rules cannot contain nested selectors. Nor can they be nested under a selector. * Normally this would be a syntax error by the author of the styles. But in some rare cases, such * as importing styles from a library, and applying `:host ::ng-deep` to the imported styles, we * can end up with broken css if the imported styles happen to contain @font-face rules. * * For example: * * ``` * :host ::ng-deep { * import 'some/lib/containing/font-face'; * } * * Similar logic applies to `@page` rules which can contain a particular set of properties, * as well as some specific at-rules. Since they can't be encapsulated, we have to strip * any scoping selectors from them. For more information: https://www.w3.org/TR/css-page-3 * ``` */ ShadowCss.prototype._stripScopingSelectors = function (cssText) { return processRules(cssText, function (rule) { var selector = rule.selector.replace(_shadowDeepSelectors, ' ') .replace(_polyfillHostNoCombinatorRe, ' '); return new CssRule(selector, rule.content); }); }; ShadowCss.prototype._scopeSelector = function (selector, scopeSelector, hostSelector, strict) { var _this = this; return selector.split(',') .map(function (part) { return part.trim().split(_shadowDeepSelectors); }) .map(function (deepParts) { var _b = __read(deepParts), shallowPart = _b[0], otherParts = _b.slice(1); var applyScope = function (shallowPart) { if (_this._selectorNeedsScoping(shallowPart, scopeSelector)) { return strict ? _this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) : _this._applySelectorScope(shallowPart, scopeSelector, hostSelector); } else { return shallowPart; } }; return __spreadArray([applyScope(shallowPart)], __read(otherParts)).join(' '); }) .join(', '); }; ShadowCss.prototype._selectorNeedsScoping = function (selector, scopeSelector) { var re = this._makeScopeMatcher(scopeSelector); return !re.test(selector); }; ShadowCss.prototype._makeScopeMatcher = function (scopeSelector) { var lre = /\[/g; var rre = /\]/g; scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]'); return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm'); }; ShadowCss.prototype._applySelectorScope = function (selector, scopeSelector, hostSelector) { // Difference from webcomponents.js: scopeSelector could not be an array return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector); }; // scope via name and [is=name] ShadowCss.prototype._applySimpleSelectorScope = function (selector, scopeSelector, hostSelector) { // In Android browser, the lastIndex is not reset when the regex is used in String.replace() _polyfillHostRe.lastIndex = 0; if (_polyfillHostRe.test(selector)) { var replaceBy_1 = this.strictStyling ? "[" + hostSelector + "]" : scopeSelector; return selector .replace(_polyfillHostNoCombinatorRe, function (hnc, selector) { return selector.replace(/([^:]*)(:*)(.*)/, function (_, before, colon, after) { return before + replaceBy_1 + colon + after; }); }) .replace(_polyfillHostRe, replaceBy_1 + ' '); } return scopeSelector + ' ' + selector; }; // return a selector with [name] suffix on each simple selector // e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */ ShadowCss.prototype._applyStrictSelectorScope = function (selector, scopeSelector, hostSelector) { var _this = this; var isRe = /\[is=([^\]]*)\]/g; scopeSelector = scopeSelector.replace(isRe, function (_) { var parts = []; for (var _i = 1; _i < arguments.length; _i++) { parts[_i - 1] = arguments[_i]; } return parts[0]; }); var attrName = '[' + scopeSelector + ']'; var _scopeSelectorPart = function (p) { var scopedP = p.trim(); if (!scopedP) { return ''; } if (p.indexOf(_polyfillHostNoCombinator) > -1) { scopedP = _this._applySimpleSelectorScope(p, scopeSelector, hostSelector); } else { // remove :host since it should be unnecessary var t = p.replace(_polyfillHostRe, ''); if (t.length > 0) { var matches = t.match(/([^:]*)(:*)(.*)/); if (matches) { scopedP = matches[1] + attrName + matches[2] + matches[3]; } } } return scopedP; }; var safeContent = new SafeSelector(selector); selector = safeContent.content(); var scopedSelector = ''; var startIndex = 0; var res; var sep = /( |>|\+|~(?!=))\s*/g; // If a selector appears before :host it should not be shimmed as it // matches on ancestor elements and not on elements in the host's shadow // `:host-context(div)` is transformed to // `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator` // the `div` is not part of the component in the 2nd selectors and should not be scoped. // Historically `component-tag:host` was matching the component so we also want to preserve // this behavior to avoid breaking legacy apps (it should not match). // The behavior should be: // - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything) // - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a // `:host-context(tag)`) var hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1; // Only scope parts after the first `-shadowcsshost-no-combinator` when it is present var shouldScope = !hasHost; while ((res = sep.exec(selector)) !== null) { var separator = res[1]; var part_1 = selector.slice(startIndex, res.index).trim(); shouldScope = shouldScope || part_1.indexOf(_polyfillHostNoCombinator) > -1; var scopedPart = shouldScope ? _scopeSelectorPart(part_1) : part_1; scopedSelector += scopedPart + " " + separator + " "; startIndex = sep.lastIndex; } var part = selector.substring(startIndex); shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1; scopedSelector += shouldScope ? _scopeSelectorPart(part) : part; // replace the placeholders with their original values return safeContent.restore(scopedSelector); }; ShadowCss.prototype._insertPolyfillHostInCssText = function (selector) { return selector.replace(_colonHostContextRe, _polyfillHostContext) .replace(_colonHostRe, _polyfillHost); }; return ShadowCss; }()); var SafeSelector = /** @class */ (function () { function SafeSelector(selector) { var _this = this; this.placeholders = []; this.index = 0; // Replaces attribute selectors with placeholders. // The WS in [attr="va lue"] would otherwise be interpreted as a selector separator. selector = this._escapeRegexMatches(selector, /(\[[^\]]*\])/g); // CSS allows for certain special characters to be used in selectors if they're escaped. // E.g. `.foo:blue` won't match a class called `foo:blue`, because the colon denotes a // pseudo-class, but writing `.foo\:blue` will match, because the colon was escaped. // Replace all escape sequences (`\` followed by a character) with a placeholder so // that our handling of pseudo-selectors doesn't mess with them. selector = this._escapeRegexMatches(selector, /(\\.)/g); // Replaces the expression in `:nth-child(2n + 1)` with a placeholder. // WS and "+" would otherwise be interpreted as selector separators. this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, function (_, pseudo, exp) { var replaceBy = "__ph-" + _this.index + "__"; _this.placeholders.push(exp); _this.index++; return pseudo + replaceBy; }); } SafeSelector.prototype.restore = function (content) { var _this = this; return content.replace(/__ph-(\d+)__/g, function (_ph, index) { return _this.placeholders[+index]; }); }; SafeSelector.prototype.content = function () { return this._content; }; /** * Replaces all of the substrings that match a regex within a * special string (e.g. `__ph-0__`, `__ph-1__`, etc). */ SafeSelector.prototype._escapeRegexMatches = function (content, pattern) { var _this = this; return content.replace(pattern, function (_, keep) { var replaceBy = "__ph-" + _this.index + "__"; _this.placeholders.push(keep); _this.index++; return replaceBy; }); }; return SafeSelector; }()); var _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim; var _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim; var _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim; var _polyfillHost = '-shadowcsshost'; // note: :host-context pre-processed to -shadowcsshostcontext. var _polyfillHostContext = '-shadowcsscontext'; var _parenSuffix = '(?:\\((' + '(?:\\([^)(]*\\)|[^)(]*)+?' + ')\\))?([^,{]*)'; var _cssColonHostRe = new RegExp(_polyfillHost + _parenSuffix, 'gim'); var _cssColonHostContextReGlobal = new RegExp(_polyfillHostContext + _parenSuffix, 'gim'); var _cssColonHostContextRe = new RegExp(_polyfillHostContext + _parenSuffix, 'im'); var _polyfillHostNoCombinator = _polyfillHost + '-no-combinator'; var _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/; var _shadowDOMSelectorsRe = [ /::shadow/g, /::content/g, // Deprecated selectors /\/shadow-deep\//g, /\/shadow\//g, ]; // The deep combinator is deprecated in the CSS spec // Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future. // see https://github.com/angular/angular/pull/17677 var _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g; var _selectorReSuffix = '([>\\s~+[.,{:][\\s\\S]*)?$'; var _polyfillHostRe = /-shadowcsshost/gim; var _colonHostRe = /:host/gim; var _colonHostContextRe = /:host-context/gim; var _commentRe = /\/\*\s*[\s\S]*?\*\//g; function stripComments(input) { return input.replace(_commentRe, ''); } var _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g; function extractCommentsWithHash(input) { return input.match(_commentWithHashRe) || []; } var BLOCK_PLACEHOLDER = '%BLOCK%'; var QUOTE_PLACEHOLDER = '%QUOTED%'; var _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g; var _quotedRe = /%QUOTED%/g; var CONTENT_PAIRS = new Map([['{', '}']]); var QUOTE_PAIRS = new Map([["\"", "\""], ["'", "'"]]); var CssRule = /** @class */ (function () { function CssRule(selector, content) { this.selector = selector; this.content = content; } return CssRule; }()); function processRules(input, ruleCallback) { var inputWithEscapedQuotes = escapeBlocks(input, QUOTE_PAIRS, QUOTE_PLACEHOLDER); var inputWithEscapedBlocks = escapeBlocks(inputWithEscapedQuotes.escapedString, CONTENT_PAIRS, BLOCK_PLACEHOLDER); var nextBlockIndex = 0; var nextQuoteIndex = 0; return inputWithEscapedBlocks.escapedString .replace(_ruleRe, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } var selector = m[2]; var content = ''; var suffix = m[4]; var contentPrefix = ''; if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) { content = inputWithEscapedBlocks.blocks[nextBlockIndex++]; suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1); contentPrefix = '{'; } var rule = ruleCallback(new CssRule(selector, content)); return "" + m[1] + rule.selector + m[3] + contentPrefix + rule.content + suffix; }) .replace(_quotedRe, function () { return inputWithEscapedQuotes.blocks[nextQuoteIndex++]; }); } var StringWithEscapedBlocks = /** @class */ (function () { function StringWithEscapedBlocks(escapedString, blocks) { this.escapedString = escapedString; this.blocks = blocks; } return StringWithEscapedBlocks; }()); function escapeBlocks(input, charPairs, placeholder) { var resultParts = []; var escapedBlocks = []; var openCharCount = 0; var nonBlockStartIndex = 0; var blockStartIndex = -1; var openChar; var closeChar; for (var i = 0; i < input.length; i++) { var char = input[i]; if (char === '\\') { i++; } else if (char === closeChar) { openCharCount--; if (openCharCount === 0) { escapedBlocks.push(input.substring(blockStartIndex, i)); resultParts.push(placeholder); nonBlockStartIndex = i; blockStartIndex = -1; openChar = closeChar = undefined; } } else if (char === openChar) { openCharCount++; } else if (openCharCount === 0 && charPairs.has(char)) { openChar = char; closeChar = charPairs.get(char); openCharCount = 1; blockStartIndex = i + 1; resultParts.push(input.substring(nonBlockStartIndex, blockStartIndex)); } } if (blockStartIndex !== -1) { escapedBlocks.push(input.substring(blockStartIndex)); resultParts.push(placeholder); } else { resultParts.push(input.substring(nonBlockStartIndex)); } return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks); } /** * Combine the `contextSelectors` with the `hostMarker` and the `otherSelectors` * to create a selector that matches the same as `:host-context()`. * * Given a single context selector `A` we need to output selectors that match on the host and as an * ancestor of the host: * * ``` * A , A {} * ``` * * When there is more than one context selector we also have to create combinations of those * selectors with each other. For example if there are `A` and `B` selectors the output is: * * ``` * AB, AB , A B, * B A, A B , B A {} * ``` * * And so on... * * @param hostMarker the string that selects the host element. * @param contextSelectors an array of context selectors that will be combined. * @param otherSelectors the rest of the selectors that are not context selectors. */ function combineHostContextSelectors(contextSelectors, otherSelectors) { var hostMarker = _polyfillHostNoCombinator; _polyfillHostRe.lastIndex = 0; // reset the regex to ensure we get an accurate test var otherSelectorsHasHost = _polyfillHostRe.test(otherSelectors); // If there are no context selectors then just output a host marker if (contextSelectors.length === 0) { return hostMarker + otherSelectors; } var combined = [contextSelectors.pop() || '']; while (contextSelectors.length > 0) { var length = combined.length; var contextSelector = contextSelectors.pop(); for (var i = 0; i < length; i++) { var previousSelectors = combined[i]; // Add the new selector as a descendant of the previous selectors combined[length * 2 + i] = previousSelectors + ' ' + contextSelector; // Add the new selector as an ancestor of the previous selectors combined[length + i] = contextSelector + ' ' + previousSelectors; // Add the new selector to act on the same element as the previous selectors combined[i] = contextSelector + previousSelectors; } } // Finally connect the selector to the `hostMarker`s: either acting directly on the host // (A) or as an ancestor (A ). return combined .map(function (s) { return otherSelectorsHasHost ? "" + s + otherSelectors : "" + s + hostMarker + otherSelectors + ", " + s + " " + hostMarker + otherSelectors; }) .join(','); } /** * Mutate the given `groups` array so that there are `multiples` clones of the original array * stored. * * For example `repeatGroups([a, b], 3)` will result in `[a, b, a, b, a, b]` - but importantly the * newly added groups will be clones of the original. * * @param groups An array of groups of strings that will be repeated. This array is mutated * in-place. * @param multiples The number of times the current groups should appear. */ function repeatGroups(groups, multiples) { var length = groups.length; for (var i = 1; i < multiples; i++) { for (var j = 0; j < length; j++) { groups[j + (i * length)] = groups[j].slice(0); } } } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var COMPONENT_VARIABLE = '%COMP%'; var HOST_ATTR = "_nghost-" + COMPONENT_VARIABLE; var CONTENT_ATTR = "_ngcontent-" + COMPONENT_VARIABLE; var StylesCompileDependency = /** @class */ (function () { function StylesCompileDependency(name, moduleUrl, setValue) { this.name = name; this.moduleUrl = moduleUrl; this.setValue = setValue; } return StylesCompileDependency; }()); var CompiledStylesheet = /** @class */ (function () { function CompiledStylesheet(outputCtx, stylesVar, dependencies, isShimmed, meta) { this.outputCtx = outputCtx; this.stylesVar = stylesVar; this.dependencies = dependencies; this.isShimmed = isShimmed; this.meta = meta; } return CompiledStylesheet; }()); var StyleCompiler = /** @class */ (function () { function StyleCompiler(_urlResolver) { this._urlResolver = _urlResolver; this._shadowCss = new ShadowCss(); } StyleCompiler.prototype.compileComponent = function (outputCtx, comp) { var template = comp.template; return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({ styles: template.styles, styleUrls: template.styleUrls, moduleUrl: identifierModuleUrl(comp.type) }), this.needsStyleShim(comp), true); }; StyleCompiler.prototype.compileStyles = function (outputCtx, comp, stylesheet, shim) { if (shim === void 0) { shim = this.needsStyleShim(comp); } return this._compileStyles(outputCtx, comp, stylesheet, shim, false); }; StyleCompiler.prototype.needsStyleShim = function (comp) { return comp.template.encapsulation === ViewEncapsulation.Emulated; }; StyleCompiler.prototype._compileStyles = function (outputCtx, comp, stylesheet, shim, isComponentStylesheet) { var _this = this; var styleExpressions = stylesheet.styles.map(function (plainStyle) { return literal(_this._shimIfNeeded(plainStyle, shim)); }); var dependencies = []; stylesheet.styleUrls.forEach(function (styleUrl) { var exprIndex = styleExpressions.length; // Note: This placeholder will be filled later. styleExpressions.push(null); dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, function (value) { return styleExpressions[exprIndex] = outputCtx.importExpr(value); })); }); // styles variable contains plain strings and arrays of other styles arrays (recursive), // so we set its type to dynamic. var stylesVar = getStylesVarName(isComponentStylesheet ? comp : null); var stmt = variable(stylesVar) .set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const]))) .toDeclStmt(null, isComponentStylesheet ? [exports.StmtModifier.Final] : [ exports.StmtModifier.Final, exports.StmtModifier.Exported ]); outputCtx.statements.push(stmt); return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet); }; StyleCompiler.prototype._shimIfNeeded = function (style, shim) { return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style; }; return StyleCompiler; }()); function getStylesVarName(component) { var result = "styles"; if (component) { result += "_" + identifierName(component.type); } return result; } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A path is an ordered set of elements. Typically a path is to a * particular offset in a source file. The head of the list is the top * most node. The tail is the node that contains the offset directly. * * For example, the expression `a + b + c` might have an ast that looks * like: * + * / \ * a + * / \ * b c * * The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10, * 'c' at 9-10]` and the path the node at offset 1 would be * `['+' at 1-10, 'a' at 1-2]`. */ var AstPath = /** @class */ (function () { function AstPath(path, position) { if (position === void 0) { position = -1; } this.path = path; this.position = position; } Object.defineProperty(AstPath.prototype, "empty", { get: function () { return !this.path || !this.path.length; }, enumerable: false, configurable: true }); Object.defineProperty(AstPath.prototype, "head", { get: function () { return this.path[0]; }, enumerable: false, configurable: true }); Object.defineProperty(AstPath.prototype, "tail", { get: function () { return this.path[this.path.length - 1]; }, enumerable: false, configurable: true }); AstPath.prototype.parentOf = function (node) { return node && this.path[this.path.indexOf(node) - 1]; }; AstPath.prototype.childOf = function (node) { return this.path[this.path.indexOf(node) + 1]; }; AstPath.prototype.first = function (ctor) { for (var i = this.path.length - 1; i >= 0; i--) { var item = this.path[i]; if (item instanceof ctor) return item; } }; AstPath.prototype.push = function (node) { this.path.push(node); }; AstPath.prototype.pop = function () { return this.path.pop(); }; return AstPath; }()); var NodeWithI18n = /** @class */ (function () { function NodeWithI18n(sourceSpan, i18n) { this.sourceSpan = sourceSpan; this.i18n = i18n; } return NodeWithI18n; }()); var Text$3 = /** @class */ (function (_super) { __extends(Text, _super); function Text(value, sourceSpan, i18n) { var _this = _super.call(this, sourceSpan, i18n) || this; _this.value = value; return _this; } Text.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return Text; }(NodeWithI18n)); var Expansion = /** @class */ (function (_super) { __extends(Expansion, _super); function Expansion(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) { var _this = _super.call(this, sourceSpan, i18n) || this; _this.switchValue = switchValue; _this.type = type; _this.cases = cases; _this.switchValueSourceSpan = switchValueSourceSpan; return _this; } Expansion.prototype.visit = function (visitor, context) { return visitor.visitExpansion(this, context); }; return Expansion; }(NodeWithI18n)); var ExpansionCase = /** @class */ (function () { function ExpansionCase(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) { this.value = value; this.expression = expression; this.sourceSpan = sourceSpan; this.valueSourceSpan = valueSourceSpan; this.expSourceSpan = expSourceSpan; } ExpansionCase.prototype.visit = function (visitor, context) { return visitor.visitExpansionCase(this, context); }; return ExpansionCase; }()); var Attribute = /** @class */ (function (_super) { __extends(Attribute, _super); function Attribute(name, value, sourceSpan, keySpan, valueSpan, i18n) { var _this = _super.call(this, sourceSpan, i18n) || this; _this.name = name; _this.value = value; _this.keySpan = keySpan; _this.valueSpan = valueSpan; return _this; } Attribute.prototype.visit = function (visitor, context) { return visitor.visitAttribute(this, context); }; return Attribute; }(NodeWithI18n)); var Element$1 = /** @class */ (function (_super) { __extends(Element, _super); function Element(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan, i18n) { if (endSourceSpan === void 0) { endSourceSpan = null; } var _this = _super.call(this, sourceSpan, i18n) || this; _this.name = name; _this.attrs = attrs; _this.children = children; _this.startSourceSpan = startSourceSpan; _this.endSourceSpan = endSourceSpan; return _this; } Element.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); }; return Element; }(NodeWithI18n)); var Comment$1 = /** @class */ (function () { function Comment(value, sourceSpan) { this.value = value; this.sourceSpan = sourceSpan; } Comment.prototype.visit = function (visitor, context) { return visitor.visitComment(this, context); }; return Comment; }()); function visitAll$1(visitor, nodes, context) { if (context === void 0) { context = null; } var result = []; var visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; nodes.forEach(function (ast) { var astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; } var RecursiveVisitor$1 = /** @class */ (function () { function RecursiveVisitor() { } RecursiveVisitor.prototype.visitElement = function (ast, context) { this.visitChildren(context, function (visit) { visit(ast.attrs); visit(ast.children); }); }; RecursiveVisitor.prototype.visitAttribute = function (ast, context) { }; RecursiveVisitor.prototype.visitText = function (ast, context) { }; RecursiveVisitor.prototype.visitComment = function (ast, context) { }; RecursiveVisitor.prototype.visitExpansion = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.cases); }); }; RecursiveVisitor.prototype.visitExpansionCase = function (ast, context) { }; RecursiveVisitor.prototype.visitChildren = function (context, cb) { var results = []; var t = this; function visit(children) { if (children) results.push(visitAll$1(t, children, context)); } cb(visit); return Array.prototype.concat.apply([], results); }; return RecursiveVisitor; }()); function spanOf(ast) { var start = ast.sourceSpan.start.offset; var end = ast.sourceSpan.end.offset; if (ast instanceof Element$1) { if (ast.endSourceSpan) { end = ast.endSourceSpan.end.offset; } else if (ast.children && ast.children.length) { end = spanOf(ast.children[ast.children.length - 1]).end; } } return { start: start, end: end }; } function findNode(nodes, position) { var path = []; var visitor = new /** @class */ (function (_super) { __extends(class_1, _super); function class_1() { return _super !== null && _super.apply(this, arguments) || this; } class_1.prototype.visit = function (ast, context) { var span = spanOf(ast); if (span.start <= position && position < span.end) { path.push(ast); } else { // Returning a value here will result in the children being skipped. return true; } }; return class_1; }(RecursiveVisitor$1)); visitAll$1(visitor, nodes); return new AstPath(path, position); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Mapping between all HTML entity names and their unicode representation. // Generated from https://html.spec.whatwg.org/multipage/entities.json by stripping // the `&` and `;` from the keys and removing the duplicates. // see https://www.w3.org/TR/html51/syntax.html#named-character-references var NAMED_ENTITIES = { 'AElig': '\u00C6', 'AMP': '\u0026', 'amp': '\u0026', 'Aacute': '\u00C1', 'Abreve': '\u0102', 'Acirc': '\u00C2', 'Acy': '\u0410', 'Afr': '\uD835\uDD04', 'Agrave': '\u00C0', 'Alpha': '\u0391', 'Amacr': '\u0100', 'And': '\u2A53', 'Aogon': '\u0104', 'Aopf': '\uD835\uDD38', 'ApplyFunction': '\u2061', 'af': '\u2061', 'Aring': '\u00C5', 'angst': '\u00C5', 'Ascr': '\uD835\uDC9C', 'Assign': '\u2254', 'colone': '\u2254', 'coloneq': '\u2254', 'Atilde': '\u00C3', 'Auml': '\u00C4', 'Backslash': '\u2216', 'setminus': '\u2216', 'setmn': '\u2216', 'smallsetminus': '\u2216', 'ssetmn': '\u2216', 'Barv': '\u2AE7', 'Barwed': '\u2306', 'doublebarwedge': '\u2306', 'Bcy': '\u0411', 'Because': '\u2235', 'becaus': '\u2235', 'because': '\u2235', 'Bernoullis': '\u212C', 'Bscr': '\u212C', 'bernou': '\u212C', 'Beta': '\u0392', 'Bfr': '\uD835\uDD05', 'Bopf': '\uD835\uDD39', 'Breve': '\u02D8', 'breve': '\u02D8', 'Bumpeq': '\u224E', 'HumpDownHump': '\u224E', 'bump': '\u224E', 'CHcy': '\u0427', 'COPY': '\u00A9', 'copy': '\u00A9', 'Cacute': '\u0106', 'Cap': '\u22D2', 'CapitalDifferentialD': '\u2145', 'DD': '\u2145', 'Cayleys': '\u212D', 'Cfr': '\u212D', 'Ccaron': '\u010C', 'Ccedil': '\u00C7', 'Ccirc': '\u0108', 'Cconint': '\u2230', 'Cdot': '\u010A', 'Cedilla': '\u00B8', 'cedil': '\u00B8', 'CenterDot': '\u00B7', 'centerdot': '\u00B7', 'middot': '\u00B7', 'Chi': '\u03A7', 'CircleDot': '\u2299', 'odot': '\u2299', 'CircleMinus': '\u2296', 'ominus': '\u2296', 'CirclePlus': '\u2295', 'oplus': '\u2295', 'CircleTimes': '\u2297', 'otimes': '\u2297', 'ClockwiseContourIntegral': '\u2232', 'cwconint': '\u2232', 'CloseCurlyDoubleQuote': '\u201D', 'rdquo': '\u201D', 'rdquor': '\u201D', 'CloseCurlyQuote': '\u2019', 'rsquo': '\u2019', 'rsquor': '\u2019', 'Colon': '\u2237', 'Proportion': '\u2237', 'Colone': '\u2A74', 'Congruent': '\u2261', 'equiv': '\u2261', 'Conint': '\u222F', 'DoubleContourIntegral': '\u222F', 'ContourIntegral': '\u222E', 'conint': '\u222E', 'oint': '\u222E', 'Copf': '\u2102', 'complexes': '\u2102', 'Coproduct': '\u2210', 'coprod': '\u2210', 'CounterClockwiseContourIntegral': '\u2233', 'awconint': '\u2233', 'Cross': '\u2A2F', 'Cscr': '\uD835\uDC9E', 'Cup': '\u22D3', 'CupCap': '\u224D', 'asympeq': '\u224D', 'DDotrahd': '\u2911', 'DJcy': '\u0402', 'DScy': '\u0405', 'DZcy': '\u040F', 'Dagger': '\u2021', 'ddagger': '\u2021', 'Darr': '\u21A1', 'Dashv': '\u2AE4', 'DoubleLeftTee': '\u2AE4', 'Dcaron': '\u010E', 'Dcy': '\u0414', 'Del': '\u2207', 'nabla': '\u2207', 'Delta': '\u0394', 'Dfr': '\uD835\uDD07', 'DiacriticalAcute': '\u00B4', 'acute': '\u00B4', 'DiacriticalDot': '\u02D9', 'dot': '\u02D9', 'DiacriticalDoubleAcute': '\u02DD', 'dblac': '\u02DD', 'DiacriticalGrave': '\u0060', 'grave': '\u0060', 'DiacriticalTilde': '\u02DC', 'tilde': '\u02DC', 'Diamond': '\u22C4', 'diam': '\u22C4', 'diamond': '\u22C4', 'DifferentialD': '\u2146', 'dd': '\u2146', 'Dopf': '\uD835\uDD3B', 'Dot': '\u00A8', 'DoubleDot': '\u00A8', 'die': '\u00A8', 'uml': '\u00A8', 'DotDot': '\u20DC', 'DotEqual': '\u2250', 'doteq': '\u2250', 'esdot': '\u2250', 'DoubleDownArrow': '\u21D3', 'Downarrow': '\u21D3', 'dArr': '\u21D3', 'DoubleLeftArrow': '\u21D0', 'Leftarrow': '\u21D0', 'lArr': '\u21D0', 'DoubleLeftRightArrow': '\u21D4', 'Leftrightarrow': '\u21D4', 'hArr': '\u21D4', 'iff': '\u21D4', 'DoubleLongLeftArrow': '\u27F8', 'Longleftarrow': '\u27F8', 'xlArr': '\u27F8', 'DoubleLongLeftRightArrow': '\u27FA', 'Longleftrightarrow': '\u27FA', 'xhArr': '\u27FA', 'DoubleLongRightArrow': '\u27F9', 'Longrightarrow': '\u27F9', 'xrArr': '\u27F9', 'DoubleRightArrow': '\u21D2', 'Implies': '\u21D2', 'Rightarrow': '\u21D2', 'rArr': '\u21D2', 'DoubleRightTee': '\u22A8', 'vDash': '\u22A8', 'DoubleUpArrow': '\u21D1', 'Uparrow': '\u21D1', 'uArr': '\u21D1', 'DoubleUpDownArrow': '\u21D5', 'Updownarrow': '\u21D5', 'vArr': '\u21D5', 'DoubleVerticalBar': '\u2225', 'par': '\u2225', 'parallel': '\u2225', 'shortparallel': '\u2225', 'spar': '\u2225', 'DownArrow': '\u2193', 'ShortDownArrow': '\u2193', 'darr': '\u2193', 'downarrow': '\u2193', 'DownArrowBar': '\u2913', 'DownArrowUpArrow': '\u21F5', 'duarr': '\u21F5', 'DownBreve': '\u0311', 'DownLeftRightVector': '\u2950', 'DownLeftTeeVector': '\u295E', 'DownLeftVector': '\u21BD', 'leftharpoondown': '\u21BD', 'lhard': '\u21BD', 'DownLeftVectorBar': '\u2956', 'DownRightTeeVector': '\u295F', 'DownRightVector': '\u21C1', 'rhard': '\u21C1', 'rightharpoondown': '\u21C1', 'DownRightVectorBar': '\u2957', 'DownTee': '\u22A4', 'top': '\u22A4', 'DownTeeArrow': '\u21A7', 'mapstodown': '\u21A7', 'Dscr': '\uD835\uDC9F', 'Dstrok': '\u0110', 'ENG': '\u014A', 'ETH': '\u00D0', 'Eacute': '\u00C9', 'Ecaron': '\u011A', 'Ecirc': '\u00CA', 'Ecy': '\u042D', 'Edot': '\u0116', 'Efr': '\uD835\uDD08', 'Egrave': '\u00C8', 'Element': '\u2208', 'in': '\u2208', 'isin': '\u2208', 'isinv': '\u2208', 'Emacr': '\u0112', 'EmptySmallSquare': '\u25FB', 'EmptyVerySmallSquare': '\u25AB', 'Eogon': '\u0118', 'Eopf': '\uD835\uDD3C', 'Epsilon': '\u0395', 'Equal': '\u2A75', 'EqualTilde': '\u2242', 'eqsim': '\u2242', 'esim': '\u2242', 'Equilibrium': '\u21CC', 'rightleftharpoons': '\u21CC', 'rlhar': '\u21CC', 'Escr': '\u2130', 'expectation': '\u2130', 'Esim': '\u2A73', 'Eta': '\u0397', 'Euml': '\u00CB', 'Exists': '\u2203', 'exist': '\u2203', 'ExponentialE': '\u2147', 'ee': '\u2147', 'exponentiale': '\u2147', 'Fcy': '\u0424', 'Ffr': '\uD835\uDD09', 'FilledSmallSquare': '\u25FC', 'FilledVerySmallSquare': '\u25AA', 'blacksquare': '\u25AA', 'squarf': '\u25AA', 'squf': '\u25AA', 'Fopf': '\uD835\uDD3D', 'ForAll': '\u2200', 'forall': '\u2200', 'Fouriertrf': '\u2131', 'Fscr': '\u2131', 'GJcy': '\u0403', 'GT': '\u003E', 'gt': '\u003E', 'Gamma': '\u0393', 'Gammad': '\u03DC', 'Gbreve': '\u011E', 'Gcedil': '\u0122', 'Gcirc': '\u011C', 'Gcy': '\u0413', 'Gdot': '\u0120', 'Gfr': '\uD835\uDD0A', 'Gg': '\u22D9', 'ggg': '\u22D9', 'Gopf': '\uD835\uDD3E', 'GreaterEqual': '\u2265', 'ge': '\u2265', 'geq': '\u2265', 'GreaterEqualLess': '\u22DB', 'gel': '\u22DB', 'gtreqless': '\u22DB', 'GreaterFullEqual': '\u2267', 'gE': '\u2267', 'geqq': '\u2267', 'GreaterGreater': '\u2AA2', 'GreaterLess': '\u2277', 'gl': '\u2277', 'gtrless': '\u2277', 'GreaterSlantEqual': '\u2A7E', 'geqslant': '\u2A7E', 'ges': '\u2A7E', 'GreaterTilde': '\u2273', 'gsim': '\u2273', 'gtrsim': '\u2273', 'Gscr': '\uD835\uDCA2', 'Gt': '\u226B', 'NestedGreaterGreater': '\u226B', 'gg': '\u226B', 'HARDcy': '\u042A', 'Hacek': '\u02C7', 'caron': '\u02C7', 'Hat': '\u005E', 'Hcirc': '\u0124', 'Hfr': '\u210C', 'Poincareplane': '\u210C', 'HilbertSpace': '\u210B', 'Hscr': '\u210B', 'hamilt': '\u210B', 'Hopf': '\u210D', 'quaternions': '\u210D', 'HorizontalLine': '\u2500', 'boxh': '\u2500', 'Hstrok': '\u0126', 'HumpEqual': '\u224F', 'bumpe': '\u224F', 'bumpeq': '\u224F', 'IEcy': '\u0415', 'IJlig': '\u0132', 'IOcy': '\u0401', 'Iacute': '\u00CD', 'Icirc': '\u00CE', 'Icy': '\u0418', 'Idot': '\u0130', 'Ifr': '\u2111', 'Im': '\u2111', 'image': '\u2111', 'imagpart': '\u2111', 'Igrave': '\u00CC', 'Imacr': '\u012A', 'ImaginaryI': '\u2148', 'ii': '\u2148', 'Int': '\u222C', 'Integral': '\u222B', 'int': '\u222B', 'Intersection': '\u22C2', 'bigcap': '\u22C2', 'xcap': '\u22C2', 'InvisibleComma': '\u2063', 'ic': '\u2063', 'InvisibleTimes': '\u2062', 'it': '\u2062', 'Iogon': '\u012E', 'Iopf': '\uD835\uDD40', 'Iota': '\u0399', 'Iscr': '\u2110', 'imagline': '\u2110', 'Itilde': '\u0128', 'Iukcy': '\u0406', 'Iuml': '\u00CF', 'Jcirc': '\u0134', 'Jcy': '\u0419', 'Jfr': '\uD835\uDD0D', 'Jopf': '\uD835\uDD41', 'Jscr': '\uD835\uDCA5', 'Jsercy': '\u0408', 'Jukcy': '\u0404', 'KHcy': '\u0425', 'KJcy': '\u040C', 'Kappa': '\u039A', 'Kcedil': '\u0136', 'Kcy': '\u041A', 'Kfr': '\uD835\uDD0E', 'Kopf': '\uD835\uDD42', 'Kscr': '\uD835\uDCA6', 'LJcy': '\u0409', 'LT': '\u003C', 'lt': '\u003C', 'Lacute': '\u0139', 'Lambda': '\u039B', 'Lang': '\u27EA', 'Laplacetrf': '\u2112', 'Lscr': '\u2112', 'lagran': '\u2112', 'Larr': '\u219E', 'twoheadleftarrow': '\u219E', 'Lcaron': '\u013D', 'Lcedil': '\u013B', 'Lcy': '\u041B', 'LeftAngleBracket': '\u27E8', 'lang': '\u27E8', 'langle': '\u27E8', 'LeftArrow': '\u2190', 'ShortLeftArrow': '\u2190', 'larr': '\u2190', 'leftarrow': '\u2190', 'slarr': '\u2190', 'LeftArrowBar': '\u21E4', 'larrb': '\u21E4', 'LeftArrowRightArrow': '\u21C6', 'leftrightarrows': '\u21C6', 'lrarr': '\u21C6', 'LeftCeiling': '\u2308', 'lceil': '\u2308', 'LeftDoubleBracket': '\u27E6', 'lobrk': '\u27E6', 'LeftDownTeeVector': '\u2961', 'LeftDownVector': '\u21C3', 'dharl': '\u21C3', 'downharpoonleft': '\u21C3', 'LeftDownVectorBar': '\u2959', 'LeftFloor': '\u230A', 'lfloor': '\u230A', 'LeftRightArrow': '\u2194', 'harr': '\u2194', 'leftrightarrow': '\u2194', 'LeftRightVector': '\u294E', 'LeftTee': '\u22A3', 'dashv': '\u22A3', 'LeftTeeArrow': '\u21A4', 'mapstoleft': '\u21A4', 'LeftTeeVector': '\u295A', 'LeftTriangle': '\u22B2', 'vartriangleleft': '\u22B2', 'vltri': '\u22B2', 'LeftTriangleBar': '\u29CF', 'LeftTriangleEqual': '\u22B4', 'ltrie': '\u22B4', 'trianglelefteq': '\u22B4', 'LeftUpDownVector': '\u2951', 'LeftUpTeeVector': '\u2960', 'LeftUpVector': '\u21BF', 'uharl': '\u21BF', 'upharpoonleft': '\u21BF', 'LeftUpVectorBar': '\u2958', 'LeftVector': '\u21BC', 'leftharpoonup': '\u21BC', 'lharu': '\u21BC', 'LeftVectorBar': '\u2952', 'LessEqualGreater': '\u22DA', 'leg': '\u22DA', 'lesseqgtr': '\u22DA', 'LessFullEqual': '\u2266', 'lE': '\u2266', 'leqq': '\u2266', 'LessGreater': '\u2276', 'lessgtr': '\u2276', 'lg': '\u2276', 'LessLess': '\u2AA1', 'LessSlantEqual': '\u2A7D', 'leqslant': '\u2A7D', 'les': '\u2A7D', 'LessTilde': '\u2272', 'lesssim': '\u2272', 'lsim': '\u2272', 'Lfr': '\uD835\uDD0F', 'Ll': '\u22D8', 'Lleftarrow': '\u21DA', 'lAarr': '\u21DA', 'Lmidot': '\u013F', 'LongLeftArrow': '\u27F5', 'longleftarrow': '\u27F5', 'xlarr': '\u27F5', 'LongLeftRightArrow': '\u27F7', 'longleftrightarrow': '\u27F7', 'xharr': '\u27F7', 'LongRightArrow': '\u27F6', 'longrightarrow': '\u27F6', 'xrarr': '\u27F6', 'Lopf': '\uD835\uDD43', 'LowerLeftArrow': '\u2199', 'swarr': '\u2199', 'swarrow': '\u2199', 'LowerRightArrow': '\u2198', 'searr': '\u2198', 'searrow': '\u2198', 'Lsh': '\u21B0', 'lsh': '\u21B0', 'Lstrok': '\u0141', 'Lt': '\u226A', 'NestedLessLess': '\u226A', 'll': '\u226A', 'Map': '\u2905', 'Mcy': '\u041C', 'MediumSpace': '\u205F', 'Mellintrf': '\u2133', 'Mscr': '\u2133', 'phmmat': '\u2133', 'Mfr': '\uD835\uDD10', 'MinusPlus': '\u2213', 'mnplus': '\u2213', 'mp': '\u2213', 'Mopf': '\uD835\uDD44', 'Mu': '\u039C', 'NJcy': '\u040A', 'Nacute': '\u0143', 'Ncaron': '\u0147', 'Ncedil': '\u0145', 'Ncy': '\u041D', 'NegativeMediumSpace': '\u200B', 'NegativeThickSpace': '\u200B', 'NegativeThinSpace': '\u200B', 'NegativeVeryThinSpace': '\u200B', 'ZeroWidthSpace': '\u200B', 'NewLine': '\u000A', 'Nfr': '\uD835\uDD11', 'NoBreak': '\u2060', 'NonBreakingSpace': '\u00A0', 'nbsp': '\u00A0', 'Nopf': '\u2115', 'naturals': '\u2115', 'Not': '\u2AEC', 'NotCongruent': '\u2262', 'nequiv': '\u2262', 'NotCupCap': '\u226D', 'NotDoubleVerticalBar': '\u2226', 'npar': '\u2226', 'nparallel': '\u2226', 'nshortparallel': '\u2226', 'nspar': '\u2226', 'NotElement': '\u2209', 'notin': '\u2209', 'notinva': '\u2209', 'NotEqual': '\u2260', 'ne': '\u2260', 'NotEqualTilde': '\u2242\u0338', 'nesim': '\u2242\u0338', 'NotExists': '\u2204', 'nexist': '\u2204', 'nexists': '\u2204', 'NotGreater': '\u226F', 'ngt': '\u226F', 'ngtr': '\u226F', 'NotGreaterEqual': '\u2271', 'nge': '\u2271', 'ngeq': '\u2271', 'NotGreaterFullEqual': '\u2267\u0338', 'ngE': '\u2267\u0338', 'ngeqq': '\u2267\u0338', 'NotGreaterGreater': '\u226B\u0338', 'nGtv': '\u226B\u0338', 'NotGreaterLess': '\u2279', 'ntgl': '\u2279', 'NotGreaterSlantEqual': '\u2A7E\u0338', 'ngeqslant': '\u2A7E\u0338', 'nges': '\u2A7E\u0338', 'NotGreaterTilde': '\u2275', 'ngsim': '\u2275', 'NotHumpDownHump': '\u224E\u0338', 'nbump': '\u224E\u0338', 'NotHumpEqual': '\u224F\u0338', 'nbumpe': '\u224F\u0338', 'NotLeftTriangle': '\u22EA', 'nltri': '\u22EA', 'ntriangleleft': '\u22EA', 'NotLeftTriangleBar': '\u29CF\u0338', 'NotLeftTriangleEqual': '\u22EC', 'nltrie': '\u22EC', 'ntrianglelefteq': '\u22EC', 'NotLess': '\u226E', 'nless': '\u226E', 'nlt': '\u226E', 'NotLessEqual': '\u2270', 'nle': '\u2270', 'nleq': '\u2270', 'NotLessGreater': '\u2278', 'ntlg': '\u2278', 'NotLessLess': '\u226A\u0338', 'nLtv': '\u226A\u0338', 'NotLessSlantEqual': '\u2A7D\u0338', 'nleqslant': '\u2A7D\u0338', 'nles': '\u2A7D\u0338', 'NotLessTilde': '\u2274', 'nlsim': '\u2274', 'NotNestedGreaterGreater': '\u2AA2\u0338', 'NotNestedLessLess': '\u2AA1\u0338', 'NotPrecedes': '\u2280', 'npr': '\u2280', 'nprec': '\u2280', 'NotPrecedesEqual': '\u2AAF\u0338', 'npre': '\u2AAF\u0338', 'npreceq': '\u2AAF\u0338', 'NotPrecedesSlantEqual': '\u22E0', 'nprcue': '\u22E0', 'NotReverseElement': '\u220C', 'notni': '\u220C', 'notniva': '\u220C', 'NotRightTriangle': '\u22EB', 'nrtri': '\u22EB', 'ntriangleright': '\u22EB', 'NotRightTriangleBar': '\u29D0\u0338', 'NotRightTriangleEqual': '\u22ED', 'nrtrie': '\u22ED', 'ntrianglerighteq': '\u22ED', 'NotSquareSubset': '\u228F\u0338', 'NotSquareSubsetEqual': '\u22E2', 'nsqsube': '\u22E2', 'NotSquareSuperset': '\u2290\u0338', 'NotSquareSupersetEqual': '\u22E3', 'nsqsupe': '\u22E3', 'NotSubset': '\u2282\u20D2', 'nsubset': '\u2282\u20D2', 'vnsub': '\u2282\u20D2', 'NotSubsetEqual': '\u2288', 'nsube': '\u2288', 'nsubseteq': '\u2288', 'NotSucceeds': '\u2281', 'nsc': '\u2281', 'nsucc': '\u2281', 'NotSucceedsEqual': '\u2AB0\u0338', 'nsce': '\u2AB0\u0338', 'nsucceq': '\u2AB0\u0338', 'NotSucceedsSlantEqual': '\u22E1', 'nsccue': '\u22E1', 'NotSucceedsTilde': '\u227F\u0338', 'NotSuperset': '\u2283\u20D2', 'nsupset': '\u2283\u20D2', 'vnsup': '\u2283\u20D2', 'NotSupersetEqual': '\u2289', 'nsupe': '\u2289', 'nsupseteq': '\u2289', 'NotTilde': '\u2241', 'nsim': '\u2241', 'NotTildeEqual': '\u2244', 'nsime': '\u2244', 'nsimeq': '\u2244', 'NotTildeFullEqual': '\u2247', 'ncong': '\u2247', 'NotTildeTilde': '\u2249', 'nap': '\u2249', 'napprox': '\u2249', 'NotVerticalBar': '\u2224', 'nmid': '\u2224', 'nshortmid': '\u2224', 'nsmid': '\u2224', 'Nscr': '\uD835\uDCA9', 'Ntilde': '\u00D1', 'Nu': '\u039D', 'OElig': '\u0152', 'Oacute': '\u00D3', 'Ocirc': '\u00D4', 'Ocy': '\u041E', 'Odblac': '\u0150', 'Ofr': '\uD835\uDD12', 'Ograve': '\u00D2', 'Omacr': '\u014C', 'Omega': '\u03A9', 'ohm': '\u03A9', 'Omicron': '\u039F', 'Oopf': '\uD835\uDD46', 'OpenCurlyDoubleQuote': '\u201C', 'ldquo': '\u201C', 'OpenCurlyQuote': '\u2018', 'lsquo': '\u2018', 'Or': '\u2A54', 'Oscr': '\uD835\uDCAA', 'Oslash': '\u00D8', 'Otilde': '\u00D5', 'Otimes': '\u2A37', 'Ouml': '\u00D6', 'OverBar': '\u203E', 'oline': '\u203E', 'OverBrace': '\u23DE', 'OverBracket': '\u23B4', 'tbrk': '\u23B4', 'OverParenthesis': '\u23DC', 'PartialD': '\u2202', 'part': '\u2202', 'Pcy': '\u041F', 'Pfr': '\uD835\uDD13', 'Phi': '\u03A6', 'Pi': '\u03A0', 'PlusMinus': '\u00B1', 'plusmn': '\u00B1', 'pm': '\u00B1', 'Popf': '\u2119', 'primes': '\u2119', 'Pr': '\u2ABB', 'Precedes': '\u227A', 'pr': '\u227A', 'prec': '\u227A', 'PrecedesEqual': '\u2AAF', 'pre': '\u2AAF', 'preceq': '\u2AAF', 'PrecedesSlantEqual': '\u227C', 'prcue': '\u227C', 'preccurlyeq': '\u227C', 'PrecedesTilde': '\u227E', 'precsim': '\u227E', 'prsim': '\u227E', 'Prime': '\u2033', 'Product': '\u220F', 'prod': '\u220F', 'Proportional': '\u221D', 'prop': '\u221D', 'propto': '\u221D', 'varpropto': '\u221D', 'vprop': '\u221D', 'Pscr': '\uD835\uDCAB', 'Psi': '\u03A8', 'QUOT': '\u0022', 'quot': '\u0022', 'Qfr': '\uD835\uDD14', 'Qopf': '\u211A', 'rationals': '\u211A', 'Qscr': '\uD835\uDCAC', 'RBarr': '\u2910', 'drbkarow': '\u2910', 'REG': '\u00AE', 'circledR': '\u00AE', 'reg': '\u00AE', 'Racute': '\u0154', 'Rang': '\u27EB', 'Rarr': '\u21A0', 'twoheadrightarrow': '\u21A0', 'Rarrtl': '\u2916', 'Rcaron': '\u0158', 'Rcedil': '\u0156', 'Rcy': '\u0420', 'Re': '\u211C', 'Rfr': '\u211C', 'real': '\u211C', 'realpart': '\u211C', 'ReverseElement': '\u220B', 'SuchThat': '\u220B', 'ni': '\u220B', 'niv': '\u220B', 'ReverseEquilibrium': '\u21CB', 'leftrightharpoons': '\u21CB', 'lrhar': '\u21CB', 'ReverseUpEquilibrium': '\u296F', 'duhar': '\u296F', 'Rho': '\u03A1', 'RightAngleBracket': '\u27E9', 'rang': '\u27E9', 'rangle': '\u27E9', 'RightArrow': '\u2192', 'ShortRightArrow': '\u2192', 'rarr': '\u2192', 'rightarrow': '\u2192', 'srarr': '\u2192', 'RightArrowBar': '\u21E5', 'rarrb': '\u21E5', 'RightArrowLeftArrow': '\u21C4', 'rightleftarrows': '\u21C4', 'rlarr': '\u21C4', 'RightCeiling': '\u2309', 'rceil': '\u2309', 'RightDoubleBracket': '\u27E7', 'robrk': '\u27E7', 'RightDownTeeVector': '\u295D', 'RightDownVector': '\u21C2', 'dharr': '\u21C2', 'downharpoonright': '\u21C2', 'RightDownVectorBar': '\u2955', 'RightFloor': '\u230B', 'rfloor': '\u230B', 'RightTee': '\u22A2', 'vdash': '\u22A2', 'RightTeeArrow': '\u21A6', 'map': '\u21A6', 'mapsto': '\u21A6', 'RightTeeVector': '\u295B', 'RightTriangle': '\u22B3', 'vartriangleright': '\u22B3', 'vrtri': '\u22B3', 'RightTriangleBar': '\u29D0', 'RightTriangleEqual': '\u22B5', 'rtrie': '\u22B5', 'trianglerighteq': '\u22B5', 'RightUpDownVector': '\u294F', 'RightUpTeeVector': '\u295C', 'RightUpVector': '\u21BE', 'uharr': '\u21BE', 'upharpoonright': '\u21BE', 'RightUpVectorBar': '\u2954', 'RightVector': '\u21C0', 'rharu': '\u21C0', 'rightharpoonup': '\u21C0', 'RightVectorBar': '\u2953', 'Ropf': '\u211D', 'reals': '\u211D', 'RoundImplies': '\u2970', 'Rrightarrow': '\u21DB', 'rAarr': '\u21DB', 'Rscr': '\u211B', 'realine': '\u211B', 'Rsh': '\u21B1', 'rsh': '\u21B1', 'RuleDelayed': '\u29F4', 'SHCHcy': '\u0429', 'SHcy': '\u0428', 'SOFTcy': '\u042C', 'Sacute': '\u015A', 'Sc': '\u2ABC', 'Scaron': '\u0160', 'Scedil': '\u015E', 'Scirc': '\u015C', 'Scy': '\u0421', 'Sfr': '\uD835\uDD16', 'ShortUpArrow': '\u2191', 'UpArrow': '\u2191', 'uarr': '\u2191', 'uparrow': '\u2191', 'Sigma': '\u03A3', 'SmallCircle': '\u2218', 'compfn': '\u2218', 'Sopf': '\uD835\uDD4A', 'Sqrt': '\u221A', 'radic': '\u221A', 'Square': '\u25A1', 'squ': '\u25A1', 'square': '\u25A1', 'SquareIntersection': '\u2293', 'sqcap': '\u2293', 'SquareSubset': '\u228F', 'sqsub': '\u228F', 'sqsubset': '\u228F', 'SquareSubsetEqual': '\u2291', 'sqsube': '\u2291', 'sqsubseteq': '\u2291', 'SquareSuperset': '\u2290', 'sqsup': '\u2290', 'sqsupset': '\u2290', 'SquareSupersetEqual': '\u2292', 'sqsupe': '\u2292', 'sqsupseteq': '\u2292', 'SquareUnion': '\u2294', 'sqcup': '\u2294', 'Sscr': '\uD835\uDCAE', 'Star': '\u22C6', 'sstarf': '\u22C6', 'Sub': '\u22D0', 'Subset': '\u22D0', 'SubsetEqual': '\u2286', 'sube': '\u2286', 'subseteq': '\u2286', 'Succeeds': '\u227B', 'sc': '\u227B', 'succ': '\u227B', 'SucceedsEqual': '\u2AB0', 'sce': '\u2AB0', 'succeq': '\u2AB0', 'SucceedsSlantEqual': '\u227D', 'sccue': '\u227D', 'succcurlyeq': '\u227D', 'SucceedsTilde': '\u227F', 'scsim': '\u227F', 'succsim': '\u227F', 'Sum': '\u2211', 'sum': '\u2211', 'Sup': '\u22D1', 'Supset': '\u22D1', 'Superset': '\u2283', 'sup': '\u2283', 'supset': '\u2283', 'SupersetEqual': '\u2287', 'supe': '\u2287', 'supseteq': '\u2287', 'THORN': '\u00DE', 'TRADE': '\u2122', 'trade': '\u2122', 'TSHcy': '\u040B', 'TScy': '\u0426', 'Tab': '\u0009', 'Tau': '\u03A4', 'Tcaron': '\u0164', 'Tcedil': '\u0162', 'Tcy': '\u0422', 'Tfr': '\uD835\uDD17', 'Therefore': '\u2234', 'there4': '\u2234', 'therefore': '\u2234', 'Theta': '\u0398', 'ThickSpace': '\u205F\u200A', 'ThinSpace': '\u2009', 'thinsp': '\u2009', 'Tilde': '\u223C', 'sim': '\u223C', 'thicksim': '\u223C', 'thksim': '\u223C', 'TildeEqual': '\u2243', 'sime': '\u2243', 'simeq': '\u2243', 'TildeFullEqual': '\u2245', 'cong': '\u2245', 'TildeTilde': '\u2248', 'ap': '\u2248', 'approx': '\u2248', 'asymp': '\u2248', 'thickapprox': '\u2248', 'thkap': '\u2248', 'Topf': '\uD835\uDD4B', 'TripleDot': '\u20DB', 'tdot': '\u20DB', 'Tscr': '\uD835\uDCAF', 'Tstrok': '\u0166', 'Uacute': '\u00DA', 'Uarr': '\u219F', 'Uarrocir': '\u2949', 'Ubrcy': '\u040E', 'Ubreve': '\u016C', 'Ucirc': '\u00DB', 'Ucy': '\u0423', 'Udblac': '\u0170', 'Ufr': '\uD835\uDD18', 'Ugrave': '\u00D9', 'Umacr': '\u016A', 'UnderBar': '\u005F', 'lowbar': '\u005F', 'UnderBrace': '\u23DF', 'UnderBracket': '\u23B5', 'bbrk': '\u23B5', 'UnderParenthesis': '\u23DD', 'Union': '\u22C3', 'bigcup': '\u22C3', 'xcup': '\u22C3', 'UnionPlus': '\u228E', 'uplus': '\u228E', 'Uogon': '\u0172', 'Uopf': '\uD835\uDD4C', 'UpArrowBar': '\u2912', 'UpArrowDownArrow': '\u21C5', 'udarr': '\u21C5', 'UpDownArrow': '\u2195', 'updownarrow': '\u2195', 'varr': '\u2195', 'UpEquilibrium': '\u296E', 'udhar': '\u296E', 'UpTee': '\u22A5', 'bot': '\u22A5', 'bottom': '\u22A5', 'perp': '\u22A5', 'UpTeeArrow': '\u21A5', 'mapstoup': '\u21A5', 'UpperLeftArrow': '\u2196', 'nwarr': '\u2196', 'nwarrow': '\u2196', 'UpperRightArrow': '\u2197', 'nearr': '\u2197', 'nearrow': '\u2197', 'Upsi': '\u03D2', 'upsih': '\u03D2', 'Upsilon': '\u03A5', 'Uring': '\u016E', 'Uscr': '\uD835\uDCB0', 'Utilde': '\u0168', 'Uuml': '\u00DC', 'VDash': '\u22AB', 'Vbar': '\u2AEB', 'Vcy': '\u0412', 'Vdash': '\u22A9', 'Vdashl': '\u2AE6', 'Vee': '\u22C1', 'bigvee': '\u22C1', 'xvee': '\u22C1', 'Verbar': '\u2016', 'Vert': '\u2016', 'VerticalBar': '\u2223', 'mid': '\u2223', 'shortmid': '\u2223', 'smid': '\u2223', 'VerticalLine': '\u007C', 'verbar': '\u007C', 'vert': '\u007C', 'VerticalSeparator': '\u2758', 'VerticalTilde': '\u2240', 'wr': '\u2240', 'wreath': '\u2240', 'VeryThinSpace': '\u200A', 'hairsp': '\u200A', 'Vfr': '\uD835\uDD19', 'Vopf': '\uD835\uDD4D', 'Vscr': '\uD835\uDCB1', 'Vvdash': '\u22AA', 'Wcirc': '\u0174', 'Wedge': '\u22C0', 'bigwedge': '\u22C0', 'xwedge': '\u22C0', 'Wfr': '\uD835\uDD1A', 'Wopf': '\uD835\uDD4E', 'Wscr': '\uD835\uDCB2', 'Xfr': '\uD835\uDD1B', 'Xi': '\u039E', 'Xopf': '\uD835\uDD4F', 'Xscr': '\uD835\uDCB3', 'YAcy': '\u042F', 'YIcy': '\u0407', 'YUcy': '\u042E', 'Yacute': '\u00DD', 'Ycirc': '\u0176', 'Ycy': '\u042B', 'Yfr': '\uD835\uDD1C', 'Yopf': '\uD835\uDD50', 'Yscr': '\uD835\uDCB4', 'Yuml': '\u0178', 'ZHcy': '\u0416', 'Zacute': '\u0179', 'Zcaron': '\u017D', 'Zcy': '\u0417', 'Zdot': '\u017B', 'Zeta': '\u0396', 'Zfr': '\u2128', 'zeetrf': '\u2128', 'Zopf': '\u2124', 'integers': '\u2124', 'Zscr': '\uD835\uDCB5', 'aacute': '\u00E1', 'abreve': '\u0103', 'ac': '\u223E', 'mstpos': '\u223E', 'acE': '\u223E\u0333', 'acd': '\u223F', 'acirc': '\u00E2', 'acy': '\u0430', 'aelig': '\u00E6', 'afr': '\uD835\uDD1E', 'agrave': '\u00E0', 'alefsym': '\u2135', 'aleph': '\u2135', 'alpha': '\u03B1', 'amacr': '\u0101', 'amalg': '\u2A3F', 'and': '\u2227', 'wedge': '\u2227', 'andand': '\u2A55', 'andd': '\u2A5C', 'andslope': '\u2A58', 'andv': '\u2A5A', 'ang': '\u2220', 'angle': '\u2220', 'ange': '\u29A4', 'angmsd': '\u2221', 'measuredangle': '\u2221', 'angmsdaa': '\u29A8', 'angmsdab': '\u29A9', 'angmsdac': '\u29AA', 'angmsdad': '\u29AB', 'angmsdae': '\u29AC', 'angmsdaf': '\u29AD', 'angmsdag': '\u29AE', 'angmsdah': '\u29AF', 'angrt': '\u221F', 'angrtvb': '\u22BE', 'angrtvbd': '\u299D', 'angsph': '\u2222', 'angzarr': '\u237C', 'aogon': '\u0105', 'aopf': '\uD835\uDD52', 'apE': '\u2A70', 'apacir': '\u2A6F', 'ape': '\u224A', 'approxeq': '\u224A', 'apid': '\u224B', 'apos': '\u0027', 'aring': '\u00E5', 'ascr': '\uD835\uDCB6', 'ast': '\u002A', 'midast': '\u002A', 'atilde': '\u00E3', 'auml': '\u00E4', 'awint': '\u2A11', 'bNot': '\u2AED', 'backcong': '\u224C', 'bcong': '\u224C', 'backepsilon': '\u03F6', 'bepsi': '\u03F6', 'backprime': '\u2035', 'bprime': '\u2035', 'backsim': '\u223D', 'bsim': '\u223D', 'backsimeq': '\u22CD', 'bsime': '\u22CD', 'barvee': '\u22BD', 'barwed': '\u2305', 'barwedge': '\u2305', 'bbrktbrk': '\u23B6', 'bcy': '\u0431', 'bdquo': '\u201E', 'ldquor': '\u201E', 'bemptyv': '\u29B0', 'beta': '\u03B2', 'beth': '\u2136', 'between': '\u226C', 'twixt': '\u226C', 'bfr': '\uD835\uDD1F', 'bigcirc': '\u25EF', 'xcirc': '\u25EF', 'bigodot': '\u2A00', 'xodot': '\u2A00', 'bigoplus': '\u2A01', 'xoplus': '\u2A01', 'bigotimes': '\u2A02', 'xotime': '\u2A02', 'bigsqcup': '\u2A06', 'xsqcup': '\u2A06', 'bigstar': '\u2605', 'starf': '\u2605', 'bigtriangledown': '\u25BD', 'xdtri': '\u25BD', 'bigtriangleup': '\u25B3', 'xutri': '\u25B3', 'biguplus': '\u2A04', 'xuplus': '\u2A04', 'bkarow': '\u290D', 'rbarr': '\u290D', 'blacklozenge': '\u29EB', 'lozf': '\u29EB', 'blacktriangle': '\u25B4', 'utrif': '\u25B4', 'blacktriangledown': '\u25BE', 'dtrif': '\u25BE', 'blacktriangleleft': '\u25C2', 'ltrif': '\u25C2', 'blacktriangleright': '\u25B8', 'rtrif': '\u25B8', 'blank': '\u2423', 'blk12': '\u2592', 'blk14': '\u2591', 'blk34': '\u2593', 'block': '\u2588', 'bne': '\u003D\u20E5', 'bnequiv': '\u2261\u20E5', 'bnot': '\u2310', 'bopf': '\uD835\uDD53', 'bowtie': '\u22C8', 'boxDL': '\u2557', 'boxDR': '\u2554', 'boxDl': '\u2556', 'boxDr': '\u2553', 'boxH': '\u2550', 'boxHD': '\u2566', 'boxHU': '\u2569', 'boxHd': '\u2564', 'boxHu': '\u2567', 'boxUL': '\u255D', 'boxUR': '\u255A', 'boxUl': '\u255C', 'boxUr': '\u2559', 'boxV': '\u2551', 'boxVH': '\u256C', 'boxVL': '\u2563', 'boxVR': '\u2560', 'boxVh': '\u256B', 'boxVl': '\u2562', 'boxVr': '\u255F', 'boxbox': '\u29C9', 'boxdL': '\u2555', 'boxdR': '\u2552', 'boxdl': '\u2510', 'boxdr': '\u250C', 'boxhD': '\u2565', 'boxhU': '\u2568', 'boxhd': '\u252C', 'boxhu': '\u2534', 'boxminus': '\u229F', 'minusb': '\u229F', 'boxplus': '\u229E', 'plusb': '\u229E', 'boxtimes': '\u22A0', 'timesb': '\u22A0', 'boxuL': '\u255B', 'boxuR': '\u2558', 'boxul': '\u2518', 'boxur': '\u2514', 'boxv': '\u2502', 'boxvH': '\u256A', 'boxvL': '\u2561', 'boxvR': '\u255E', 'boxvh': '\u253C', 'boxvl': '\u2524', 'boxvr': '\u251C', 'brvbar': '\u00A6', 'bscr': '\uD835\uDCB7', 'bsemi': '\u204F', 'bsol': '\u005C', 'bsolb': '\u29C5', 'bsolhsub': '\u27C8', 'bull': '\u2022', 'bullet': '\u2022', 'bumpE': '\u2AAE', 'cacute': '\u0107', 'cap': '\u2229', 'capand': '\u2A44', 'capbrcup': '\u2A49', 'capcap': '\u2A4B', 'capcup': '\u2A47', 'capdot': '\u2A40', 'caps': '\u2229\uFE00', 'caret': '\u2041', 'ccaps': '\u2A4D', 'ccaron': '\u010D', 'ccedil': '\u00E7', 'ccirc': '\u0109', 'ccups': '\u2A4C', 'ccupssm': '\u2A50', 'cdot': '\u010B', 'cemptyv': '\u29B2', 'cent': '\u00A2', 'cfr': '\uD835\uDD20', 'chcy': '\u0447', 'check': '\u2713', 'checkmark': '\u2713', 'chi': '\u03C7', 'cir': '\u25CB', 'cirE': '\u29C3', 'circ': '\u02C6', 'circeq': '\u2257', 'cire': '\u2257', 'circlearrowleft': '\u21BA', 'olarr': '\u21BA', 'circlearrowright': '\u21BB', 'orarr': '\u21BB', 'circledS': '\u24C8', 'oS': '\u24C8', 'circledast': '\u229B', 'oast': '\u229B', 'circledcirc': '\u229A', 'ocir': '\u229A', 'circleddash': '\u229D', 'odash': '\u229D', 'cirfnint': '\u2A10', 'cirmid': '\u2AEF', 'cirscir': '\u29C2', 'clubs': '\u2663', 'clubsuit': '\u2663', 'colon': '\u003A', 'comma': '\u002C', 'commat': '\u0040', 'comp': '\u2201', 'complement': '\u2201', 'congdot': '\u2A6D', 'copf': '\uD835\uDD54', 'copysr': '\u2117', 'crarr': '\u21B5', 'cross': '\u2717', 'cscr': '\uD835\uDCB8', 'csub': '\u2ACF', 'csube': '\u2AD1', 'csup': '\u2AD0', 'csupe': '\u2AD2', 'ctdot': '\u22EF', 'cudarrl': '\u2938', 'cudarrr': '\u2935', 'cuepr': '\u22DE', 'curlyeqprec': '\u22DE', 'cuesc': '\u22DF', 'curlyeqsucc': '\u22DF', 'cularr': '\u21B6', 'curvearrowleft': '\u21B6', 'cularrp': '\u293D', 'cup': '\u222A', 'cupbrcap': '\u2A48', 'cupcap': '\u2A46', 'cupcup': '\u2A4A', 'cupdot': '\u228D', 'cupor': '\u2A45', 'cups': '\u222A\uFE00', 'curarr': '\u21B7', 'curvearrowright': '\u21B7', 'curarrm': '\u293C', 'curlyvee': '\u22CE', 'cuvee': '\u22CE', 'curlywedge': '\u22CF', 'cuwed': '\u22CF', 'curren': '\u00A4', 'cwint': '\u2231', 'cylcty': '\u232D', 'dHar': '\u2965', 'dagger': '\u2020', 'daleth': '\u2138', 'dash': '\u2010', 'hyphen': '\u2010', 'dbkarow': '\u290F', 'rBarr': '\u290F', 'dcaron': '\u010F', 'dcy': '\u0434', 'ddarr': '\u21CA', 'downdownarrows': '\u21CA', 'ddotseq': '\u2A77', 'eDDot': '\u2A77', 'deg': '\u00B0', 'delta': '\u03B4', 'demptyv': '\u29B1', 'dfisht': '\u297F', 'dfr': '\uD835\uDD21', 'diamondsuit': '\u2666', 'diams': '\u2666', 'digamma': '\u03DD', 'gammad': '\u03DD', 'disin': '\u22F2', 'div': '\u00F7', 'divide': '\u00F7', 'divideontimes': '\u22C7', 'divonx': '\u22C7', 'djcy': '\u0452', 'dlcorn': '\u231E', 'llcorner': '\u231E', 'dlcrop': '\u230D', 'dollar': '\u0024', 'dopf': '\uD835\uDD55', 'doteqdot': '\u2251', 'eDot': '\u2251', 'dotminus': '\u2238', 'minusd': '\u2238', 'dotplus': '\u2214', 'plusdo': '\u2214', 'dotsquare': '\u22A1', 'sdotb': '\u22A1', 'drcorn': '\u231F', 'lrcorner': '\u231F', 'drcrop': '\u230C', 'dscr': '\uD835\uDCB9', 'dscy': '\u0455', 'dsol': '\u29F6', 'dstrok': '\u0111', 'dtdot': '\u22F1', 'dtri': '\u25BF', 'triangledown': '\u25BF', 'dwangle': '\u29A6', 'dzcy': '\u045F', 'dzigrarr': '\u27FF', 'eacute': '\u00E9', 'easter': '\u2A6E', 'ecaron': '\u011B', 'ecir': '\u2256', 'eqcirc': '\u2256', 'ecirc': '\u00EA', 'ecolon': '\u2255', 'eqcolon': '\u2255', 'ecy': '\u044D', 'edot': '\u0117', 'efDot': '\u2252', 'fallingdotseq': '\u2252', 'efr': '\uD835\uDD22', 'eg': '\u2A9A', 'egrave': '\u00E8', 'egs': '\u2A96', 'eqslantgtr': '\u2A96', 'egsdot': '\u2A98', 'el': '\u2A99', 'elinters': '\u23E7', 'ell': '\u2113', 'els': '\u2A95', 'eqslantless': '\u2A95', 'elsdot': '\u2A97', 'emacr': '\u0113', 'empty': '\u2205', 'emptyset': '\u2205', 'emptyv': '\u2205', 'varnothing': '\u2205', 'emsp13': '\u2004', 'emsp14': '\u2005', 'emsp': '\u2003', 'eng': '\u014B', 'ensp': '\u2002', 'eogon': '\u0119', 'eopf': '\uD835\uDD56', 'epar': '\u22D5', 'eparsl': '\u29E3', 'eplus': '\u2A71', 'epsi': '\u03B5', 'epsilon': '\u03B5', 'epsiv': '\u03F5', 'straightepsilon': '\u03F5', 'varepsilon': '\u03F5', 'equals': '\u003D', 'equest': '\u225F', 'questeq': '\u225F', 'equivDD': '\u2A78', 'eqvparsl': '\u29E5', 'erDot': '\u2253', 'risingdotseq': '\u2253', 'erarr': '\u2971', 'escr': '\u212F', 'eta': '\u03B7', 'eth': '\u00F0', 'euml': '\u00EB', 'euro': '\u20AC', 'excl': '\u0021', 'fcy': '\u0444', 'female': '\u2640', 'ffilig': '\uFB03', 'fflig': '\uFB00', 'ffllig': '\uFB04', 'ffr': '\uD835\uDD23', 'filig': '\uFB01', 'fjlig': '\u0066\u006A', 'flat': '\u266D', 'fllig': '\uFB02', 'fltns': '\u25B1', 'fnof': '\u0192', 'fopf': '\uD835\uDD57', 'fork': '\u22D4', 'pitchfork': '\u22D4', 'forkv': '\u2AD9', 'fpartint': '\u2A0D', 'frac12': '\u00BD', 'half': '\u00BD', 'frac13': '\u2153', 'frac14': '\u00BC', 'frac15': '\u2155', 'frac16': '\u2159', 'frac18': '\u215B', 'frac23': '\u2154', 'frac25': '\u2156', 'frac34': '\u00BE', 'frac35': '\u2157', 'frac38': '\u215C', 'frac45': '\u2158', 'frac56': '\u215A', 'frac58': '\u215D', 'frac78': '\u215E', 'frasl': '\u2044', 'frown': '\u2322', 'sfrown': '\u2322', 'fscr': '\uD835\uDCBB', 'gEl': '\u2A8C', 'gtreqqless': '\u2A8C', 'gacute': '\u01F5', 'gamma': '\u03B3', 'gap': '\u2A86', 'gtrapprox': '\u2A86', 'gbreve': '\u011F', 'gcirc': '\u011D', 'gcy': '\u0433', 'gdot': '\u0121', 'gescc': '\u2AA9', 'gesdot': '\u2A80', 'gesdoto': '\u2A82', 'gesdotol': '\u2A84', 'gesl': '\u22DB\uFE00', 'gesles': '\u2A94', 'gfr': '\uD835\uDD24', 'gimel': '\u2137', 'gjcy': '\u0453', 'glE': '\u2A92', 'gla': '\u2AA5', 'glj': '\u2AA4', 'gnE': '\u2269', 'gneqq': '\u2269', 'gnap': '\u2A8A', 'gnapprox': '\u2A8A', 'gne': '\u2A88', 'gneq': '\u2A88', 'gnsim': '\u22E7', 'gopf': '\uD835\uDD58', 'gscr': '\u210A', 'gsime': '\u2A8E', 'gsiml': '\u2A90', 'gtcc': '\u2AA7', 'gtcir': '\u2A7A', 'gtdot': '\u22D7', 'gtrdot': '\u22D7', 'gtlPar': '\u2995', 'gtquest': '\u2A7C', 'gtrarr': '\u2978', 'gvertneqq': '\u2269\uFE00', 'gvnE': '\u2269\uFE00', 'hardcy': '\u044A', 'harrcir': '\u2948', 'harrw': '\u21AD', 'leftrightsquigarrow': '\u21AD', 'hbar': '\u210F', 'hslash': '\u210F', 'planck': '\u210F', 'plankv': '\u210F', 'hcirc': '\u0125', 'hearts': '\u2665', 'heartsuit': '\u2665', 'hellip': '\u2026', 'mldr': '\u2026', 'hercon': '\u22B9', 'hfr': '\uD835\uDD25', 'hksearow': '\u2925', 'searhk': '\u2925', 'hkswarow': '\u2926', 'swarhk': '\u2926', 'hoarr': '\u21FF', 'homtht': '\u223B', 'hookleftarrow': '\u21A9', 'larrhk': '\u21A9', 'hookrightarrow': '\u21AA', 'rarrhk': '\u21AA', 'hopf': '\uD835\uDD59', 'horbar': '\u2015', 'hscr': '\uD835\uDCBD', 'hstrok': '\u0127', 'hybull': '\u2043', 'iacute': '\u00ED', 'icirc': '\u00EE', 'icy': '\u0438', 'iecy': '\u0435', 'iexcl': '\u00A1', 'ifr': '\uD835\uDD26', 'igrave': '\u00EC', 'iiiint': '\u2A0C', 'qint': '\u2A0C', 'iiint': '\u222D', 'tint': '\u222D', 'iinfin': '\u29DC', 'iiota': '\u2129', 'ijlig': '\u0133', 'imacr': '\u012B', 'imath': '\u0131', 'inodot': '\u0131', 'imof': '\u22B7', 'imped': '\u01B5', 'incare': '\u2105', 'infin': '\u221E', 'infintie': '\u29DD', 'intcal': '\u22BA', 'intercal': '\u22BA', 'intlarhk': '\u2A17', 'intprod': '\u2A3C', 'iprod': '\u2A3C', 'iocy': '\u0451', 'iogon': '\u012F', 'iopf': '\uD835\uDD5A', 'iota': '\u03B9', 'iquest': '\u00BF', 'iscr': '\uD835\uDCBE', 'isinE': '\u22F9', 'isindot': '\u22F5', 'isins': '\u22F4', 'isinsv': '\u22F3', 'itilde': '\u0129', 'iukcy': '\u0456', 'iuml': '\u00EF', 'jcirc': '\u0135', 'jcy': '\u0439', 'jfr': '\uD835\uDD27', 'jmath': '\u0237', 'jopf': '\uD835\uDD5B', 'jscr': '\uD835\uDCBF', 'jsercy': '\u0458', 'jukcy': '\u0454', 'kappa': '\u03BA', 'kappav': '\u03F0', 'varkappa': '\u03F0', 'kcedil': '\u0137', 'kcy': '\u043A', 'kfr': '\uD835\uDD28', 'kgreen': '\u0138', 'khcy': '\u0445', 'kjcy': '\u045C', 'kopf': '\uD835\uDD5C', 'kscr': '\uD835\uDCC0', 'lAtail': '\u291B', 'lBarr': '\u290E', 'lEg': '\u2A8B', 'lesseqqgtr': '\u2A8B', 'lHar': '\u2962', 'lacute': '\u013A', 'laemptyv': '\u29B4', 'lambda': '\u03BB', 'langd': '\u2991', 'lap': '\u2A85', 'lessapprox': '\u2A85', 'laquo': '\u00AB', 'larrbfs': '\u291F', 'larrfs': '\u291D', 'larrlp': '\u21AB', 'looparrowleft': '\u21AB', 'larrpl': '\u2939', 'larrsim': '\u2973', 'larrtl': '\u21A2', 'leftarrowtail': '\u21A2', 'lat': '\u2AAB', 'latail': '\u2919', 'late': '\u2AAD', 'lates': '\u2AAD\uFE00', 'lbarr': '\u290C', 'lbbrk': '\u2772', 'lbrace': '\u007B', 'lcub': '\u007B', 'lbrack': '\u005B', 'lsqb': '\u005B', 'lbrke': '\u298B', 'lbrksld': '\u298F', 'lbrkslu': '\u298D', 'lcaron': '\u013E', 'lcedil': '\u013C', 'lcy': '\u043B', 'ldca': '\u2936', 'ldrdhar': '\u2967', 'ldrushar': '\u294B', 'ldsh': '\u21B2', 'le': '\u2264', 'leq': '\u2264', 'leftleftarrows': '\u21C7', 'llarr': '\u21C7', 'leftthreetimes': '\u22CB', 'lthree': '\u22CB', 'lescc': '\u2AA8', 'lesdot': '\u2A7F', 'lesdoto': '\u2A81', 'lesdotor': '\u2A83', 'lesg': '\u22DA\uFE00', 'lesges': '\u2A93', 'lessdot': '\u22D6', 'ltdot': '\u22D6', 'lfisht': '\u297C', 'lfr': '\uD835\uDD29', 'lgE': '\u2A91', 'lharul': '\u296A', 'lhblk': '\u2584', 'ljcy': '\u0459', 'llhard': '\u296B', 'lltri': '\u25FA', 'lmidot': '\u0140', 'lmoust': '\u23B0', 'lmoustache': '\u23B0', 'lnE': '\u2268', 'lneqq': '\u2268', 'lnap': '\u2A89', 'lnapprox': '\u2A89', 'lne': '\u2A87', 'lneq': '\u2A87', 'lnsim': '\u22E6', 'loang': '\u27EC', 'loarr': '\u21FD', 'longmapsto': '\u27FC', 'xmap': '\u27FC', 'looparrowright': '\u21AC', 'rarrlp': '\u21AC', 'lopar': '\u2985', 'lopf': '\uD835\uDD5D', 'loplus': '\u2A2D', 'lotimes': '\u2A34', 'lowast': '\u2217', 'loz': '\u25CA', 'lozenge': '\u25CA', 'lpar': '\u0028', 'lparlt': '\u2993', 'lrhard': '\u296D', 'lrm': '\u200E', 'lrtri': '\u22BF', 'lsaquo': '\u2039', 'lscr': '\uD835\uDCC1', 'lsime': '\u2A8D', 'lsimg': '\u2A8F', 'lsquor': '\u201A', 'sbquo': '\u201A', 'lstrok': '\u0142', 'ltcc': '\u2AA6', 'ltcir': '\u2A79', 'ltimes': '\u22C9', 'ltlarr': '\u2976', 'ltquest': '\u2A7B', 'ltrPar': '\u2996', 'ltri': '\u25C3', 'triangleleft': '\u25C3', 'lurdshar': '\u294A', 'luruhar': '\u2966', 'lvertneqq': '\u2268\uFE00', 'lvnE': '\u2268\uFE00', 'mDDot': '\u223A', 'macr': '\u00AF', 'strns': '\u00AF', 'male': '\u2642', 'malt': '\u2720', 'maltese': '\u2720', 'marker': '\u25AE', 'mcomma': '\u2A29', 'mcy': '\u043C', 'mdash': '\u2014', 'mfr': '\uD835\uDD2A', 'mho': '\u2127', 'micro': '\u00B5', 'midcir': '\u2AF0', 'minus': '\u2212', 'minusdu': '\u2A2A', 'mlcp': '\u2ADB', 'models': '\u22A7', 'mopf': '\uD835\uDD5E', 'mscr': '\uD835\uDCC2', 'mu': '\u03BC', 'multimap': '\u22B8', 'mumap': '\u22B8', 'nGg': '\u22D9\u0338', 'nGt': '\u226B\u20D2', 'nLeftarrow': '\u21CD', 'nlArr': '\u21CD', 'nLeftrightarrow': '\u21CE', 'nhArr': '\u21CE', 'nLl': '\u22D8\u0338', 'nLt': '\u226A\u20D2', 'nRightarrow': '\u21CF', 'nrArr': '\u21CF', 'nVDash': '\u22AF', 'nVdash': '\u22AE', 'nacute': '\u0144', 'nang': '\u2220\u20D2', 'napE': '\u2A70\u0338', 'napid': '\u224B\u0338', 'napos': '\u0149', 'natur': '\u266E', 'natural': '\u266E', 'ncap': '\u2A43', 'ncaron': '\u0148', 'ncedil': '\u0146', 'ncongdot': '\u2A6D\u0338', 'ncup': '\u2A42', 'ncy': '\u043D', 'ndash': '\u2013', 'neArr': '\u21D7', 'nearhk': '\u2924', 'nedot': '\u2250\u0338', 'nesear': '\u2928', 'toea': '\u2928', 'nfr': '\uD835\uDD2B', 'nharr': '\u21AE', 'nleftrightarrow': '\u21AE', 'nhpar': '\u2AF2', 'nis': '\u22FC', 'nisd': '\u22FA', 'njcy': '\u045A', 'nlE': '\u2266\u0338', 'nleqq': '\u2266\u0338', 'nlarr': '\u219A', 'nleftarrow': '\u219A', 'nldr': '\u2025', 'nopf': '\uD835\uDD5F', 'not': '\u00AC', 'notinE': '\u22F9\u0338', 'notindot': '\u22F5\u0338', 'notinvb': '\u22F7', 'notinvc': '\u22F6', 'notnivb': '\u22FE', 'notnivc': '\u22FD', 'nparsl': '\u2AFD\u20E5', 'npart': '\u2202\u0338', 'npolint': '\u2A14', 'nrarr': '\u219B', 'nrightarrow': '\u219B', 'nrarrc': '\u2933\u0338', 'nrarrw': '\u219D\u0338', 'nscr': '\uD835\uDCC3', 'nsub': '\u2284', 'nsubE': '\u2AC5\u0338', 'nsubseteqq': '\u2AC5\u0338', 'nsup': '\u2285', 'nsupE': '\u2AC6\u0338', 'nsupseteqq': '\u2AC6\u0338', 'ntilde': '\u00F1', 'nu': '\u03BD', 'num': '\u0023', 'numero': '\u2116', 'numsp': '\u2007', 'nvDash': '\u22AD', 'nvHarr': '\u2904', 'nvap': '\u224D\u20D2', 'nvdash': '\u22AC', 'nvge': '\u2265\u20D2', 'nvgt': '\u003E\u20D2', 'nvinfin': '\u29DE', 'nvlArr': '\u2902', 'nvle': '\u2264\u20D2', 'nvlt': '\u003C\u20D2', 'nvltrie': '\u22B4\u20D2', 'nvrArr': '\u2903', 'nvrtrie': '\u22B5\u20D2', 'nvsim': '\u223C\u20D2', 'nwArr': '\u21D6', 'nwarhk': '\u2923', 'nwnear': '\u2927', 'oacute': '\u00F3', 'ocirc': '\u00F4', 'ocy': '\u043E', 'odblac': '\u0151', 'odiv': '\u2A38', 'odsold': '\u29BC', 'oelig': '\u0153', 'ofcir': '\u29BF', 'ofr': '\uD835\uDD2C', 'ogon': '\u02DB', 'ograve': '\u00F2', 'ogt': '\u29C1', 'ohbar': '\u29B5', 'olcir': '\u29BE', 'olcross': '\u29BB', 'olt': '\u29C0', 'omacr': '\u014D', 'omega': '\u03C9', 'omicron': '\u03BF', 'omid': '\u29B6', 'oopf': '\uD835\uDD60', 'opar': '\u29B7', 'operp': '\u29B9', 'or': '\u2228', 'vee': '\u2228', 'ord': '\u2A5D', 'order': '\u2134', 'orderof': '\u2134', 'oscr': '\u2134', 'ordf': '\u00AA', 'ordm': '\u00BA', 'origof': '\u22B6', 'oror': '\u2A56', 'orslope': '\u2A57', 'orv': '\u2A5B', 'oslash': '\u00F8', 'osol': '\u2298', 'otilde': '\u00F5', 'otimesas': '\u2A36', 'ouml': '\u00F6', 'ovbar': '\u233D', 'para': '\u00B6', 'parsim': '\u2AF3', 'parsl': '\u2AFD', 'pcy': '\u043F', 'percnt': '\u0025', 'period': '\u002E', 'permil': '\u2030', 'pertenk': '\u2031', 'pfr': '\uD835\uDD2D', 'phi': '\u03C6', 'phiv': '\u03D5', 'straightphi': '\u03D5', 'varphi': '\u03D5', 'phone': '\u260E', 'pi': '\u03C0', 'piv': '\u03D6', 'varpi': '\u03D6', 'planckh': '\u210E', 'plus': '\u002B', 'plusacir': '\u2A23', 'pluscir': '\u2A22', 'plusdu': '\u2A25', 'pluse': '\u2A72', 'plussim': '\u2A26', 'plustwo': '\u2A27', 'pointint': '\u2A15', 'popf': '\uD835\uDD61', 'pound': '\u00A3', 'prE': '\u2AB3', 'prap': '\u2AB7', 'precapprox': '\u2AB7', 'precnapprox': '\u2AB9', 'prnap': '\u2AB9', 'precneqq': '\u2AB5', 'prnE': '\u2AB5', 'precnsim': '\u22E8', 'prnsim': '\u22E8', 'prime': '\u2032', 'profalar': '\u232E', 'profline': '\u2312', 'profsurf': '\u2313', 'prurel': '\u22B0', 'pscr': '\uD835\uDCC5', 'psi': '\u03C8', 'puncsp': '\u2008', 'qfr': '\uD835\uDD2E', 'qopf': '\uD835\uDD62', 'qprime': '\u2057', 'qscr': '\uD835\uDCC6', 'quatint': '\u2A16', 'quest': '\u003F', 'rAtail': '\u291C', 'rHar': '\u2964', 'race': '\u223D\u0331', 'racute': '\u0155', 'raemptyv': '\u29B3', 'rangd': '\u2992', 'range': '\u29A5', 'raquo': '\u00BB', 'rarrap': '\u2975', 'rarrbfs': '\u2920', 'rarrc': '\u2933', 'rarrfs': '\u291E', 'rarrpl': '\u2945', 'rarrsim': '\u2974', 'rarrtl': '\u21A3', 'rightarrowtail': '\u21A3', 'rarrw': '\u219D', 'rightsquigarrow': '\u219D', 'ratail': '\u291A', 'ratio': '\u2236', 'rbbrk': '\u2773', 'rbrace': '\u007D', 'rcub': '\u007D', 'rbrack': '\u005D', 'rsqb': '\u005D', 'rbrke': '\u298C', 'rbrksld': '\u298E', 'rbrkslu': '\u2990', 'rcaron': '\u0159', 'rcedil': '\u0157', 'rcy': '\u0440', 'rdca': '\u2937', 'rdldhar': '\u2969', 'rdsh': '\u21B3', 'rect': '\u25AD', 'rfisht': '\u297D', 'rfr': '\uD835\uDD2F', 'rharul': '\u296C', 'rho': '\u03C1', 'rhov': '\u03F1', 'varrho': '\u03F1', 'rightrightarrows': '\u21C9', 'rrarr': '\u21C9', 'rightthreetimes': '\u22CC', 'rthree': '\u22CC', 'ring': '\u02DA', 'rlm': '\u200F', 'rmoust': '\u23B1', 'rmoustache': '\u23B1', 'rnmid': '\u2AEE', 'roang': '\u27ED', 'roarr': '\u21FE', 'ropar': '\u2986', 'ropf': '\uD835\uDD63', 'roplus': '\u2A2E', 'rotimes': '\u2A35', 'rpar': '\u0029', 'rpargt': '\u2994', 'rppolint': '\u2A12', 'rsaquo': '\u203A', 'rscr': '\uD835\uDCC7', 'rtimes': '\u22CA', 'rtri': '\u25B9', 'triangleright': '\u25B9', 'rtriltri': '\u29CE', 'ruluhar': '\u2968', 'rx': '\u211E', 'sacute': '\u015B', 'scE': '\u2AB4', 'scap': '\u2AB8', 'succapprox': '\u2AB8', 'scaron': '\u0161', 'scedil': '\u015F', 'scirc': '\u015D', 'scnE': '\u2AB6', 'succneqq': '\u2AB6', 'scnap': '\u2ABA', 'succnapprox': '\u2ABA', 'scnsim': '\u22E9', 'succnsim': '\u22E9', 'scpolint': '\u2A13', 'scy': '\u0441', 'sdot': '\u22C5', 'sdote': '\u2A66', 'seArr': '\u21D8', 'sect': '\u00A7', 'semi': '\u003B', 'seswar': '\u2929', 'tosa': '\u2929', 'sext': '\u2736', 'sfr': '\uD835\uDD30', 'sharp': '\u266F', 'shchcy': '\u0449', 'shcy': '\u0448', 'shy': '\u00AD', 'sigma': '\u03C3', 'sigmaf': '\u03C2', 'sigmav': '\u03C2', 'varsigma': '\u03C2', 'simdot': '\u2A6A', 'simg': '\u2A9E', 'simgE': '\u2AA0', 'siml': '\u2A9D', 'simlE': '\u2A9F', 'simne': '\u2246', 'simplus': '\u2A24', 'simrarr': '\u2972', 'smashp': '\u2A33', 'smeparsl': '\u29E4', 'smile': '\u2323', 'ssmile': '\u2323', 'smt': '\u2AAA', 'smte': '\u2AAC', 'smtes': '\u2AAC\uFE00', 'softcy': '\u044C', 'sol': '\u002F', 'solb': '\u29C4', 'solbar': '\u233F', 'sopf': '\uD835\uDD64', 'spades': '\u2660', 'spadesuit': '\u2660', 'sqcaps': '\u2293\uFE00', 'sqcups': '\u2294\uFE00', 'sscr': '\uD835\uDCC8', 'star': '\u2606', 'sub': '\u2282', 'subset': '\u2282', 'subE': '\u2AC5', 'subseteqq': '\u2AC5', 'subdot': '\u2ABD', 'subedot': '\u2AC3', 'submult': '\u2AC1', 'subnE': '\u2ACB', 'subsetneqq': '\u2ACB', 'subne': '\u228A', 'subsetneq': '\u228A', 'subplus': '\u2ABF', 'subrarr': '\u2979', 'subsim': '\u2AC7', 'subsub': '\u2AD5', 'subsup': '\u2AD3', 'sung': '\u266A', 'sup1': '\u00B9', 'sup2': '\u00B2', 'sup3': '\u00B3', 'supE': '\u2AC6', 'supseteqq': '\u2AC6', 'supdot': '\u2ABE', 'supdsub': '\u2AD8', 'supedot': '\u2AC4', 'suphsol': '\u27C9', 'suphsub': '\u2AD7', 'suplarr': '\u297B', 'supmult': '\u2AC2', 'supnE': '\u2ACC', 'supsetneqq': '\u2ACC', 'supne': '\u228B', 'supsetneq': '\u228B', 'supplus': '\u2AC0', 'supsim': '\u2AC8', 'supsub': '\u2AD4', 'supsup': '\u2AD6', 'swArr': '\u21D9', 'swnwar': '\u292A', 'szlig': '\u00DF', 'target': '\u2316', 'tau': '\u03C4', 'tcaron': '\u0165', 'tcedil': '\u0163', 'tcy': '\u0442', 'telrec': '\u2315', 'tfr': '\uD835\uDD31', 'theta': '\u03B8', 'thetasym': '\u03D1', 'thetav': '\u03D1', 'vartheta': '\u03D1', 'thorn': '\u00FE', 'times': '\u00D7', 'timesbar': '\u2A31', 'timesd': '\u2A30', 'topbot': '\u2336', 'topcir': '\u2AF1', 'topf': '\uD835\uDD65', 'topfork': '\u2ADA', 'tprime': '\u2034', 'triangle': '\u25B5', 'utri': '\u25B5', 'triangleq': '\u225C', 'trie': '\u225C', 'tridot': '\u25EC', 'triminus': '\u2A3A', 'triplus': '\u2A39', 'trisb': '\u29CD', 'tritime': '\u2A3B', 'trpezium': '\u23E2', 'tscr': '\uD835\uDCC9', 'tscy': '\u0446', 'tshcy': '\u045B', 'tstrok': '\u0167', 'uHar': '\u2963', 'uacute': '\u00FA', 'ubrcy': '\u045E', 'ubreve': '\u016D', 'ucirc': '\u00FB', 'ucy': '\u0443', 'udblac': '\u0171', 'ufisht': '\u297E', 'ufr': '\uD835\uDD32', 'ugrave': '\u00F9', 'uhblk': '\u2580', 'ulcorn': '\u231C', 'ulcorner': '\u231C', 'ulcrop': '\u230F', 'ultri': '\u25F8', 'umacr': '\u016B', 'uogon': '\u0173', 'uopf': '\uD835\uDD66', 'upsi': '\u03C5', 'upsilon': '\u03C5', 'upuparrows': '\u21C8', 'uuarr': '\u21C8', 'urcorn': '\u231D', 'urcorner': '\u231D', 'urcrop': '\u230E', 'uring': '\u016F', 'urtri': '\u25F9', 'uscr': '\uD835\uDCCA', 'utdot': '\u22F0', 'utilde': '\u0169', 'uuml': '\u00FC', 'uwangle': '\u29A7', 'vBar': '\u2AE8', 'vBarv': '\u2AE9', 'vangrt': '\u299C', 'varsubsetneq': '\u228A\uFE00', 'vsubne': '\u228A\uFE00', 'varsubsetneqq': '\u2ACB\uFE00', 'vsubnE': '\u2ACB\uFE00', 'varsupsetneq': '\u228B\uFE00', 'vsupne': '\u228B\uFE00', 'varsupsetneqq': '\u2ACC\uFE00', 'vsupnE': '\u2ACC\uFE00', 'vcy': '\u0432', 'veebar': '\u22BB', 'veeeq': '\u225A', 'vellip': '\u22EE', 'vfr': '\uD835\uDD33', 'vopf': '\uD835\uDD67', 'vscr': '\uD835\uDCCB', 'vzigzag': '\u299A', 'wcirc': '\u0175', 'wedbar': '\u2A5F', 'wedgeq': '\u2259', 'weierp': '\u2118', 'wp': '\u2118', 'wfr': '\uD835\uDD34', 'wopf': '\uD835\uDD68', 'wscr': '\uD835\uDCCC', 'xfr': '\uD835\uDD35', 'xi': '\u03BE', 'xnis': '\u22FB', 'xopf': '\uD835\uDD69', 'xscr': '\uD835\uDCCD', 'yacute': '\u00FD', 'yacy': '\u044F', 'ycirc': '\u0177', 'ycy': '\u044B', 'yen': '\u00A5', 'yfr': '\uD835\uDD36', 'yicy': '\u0457', 'yopf': '\uD835\uDD6A', 'yscr': '\uD835\uDCCE', 'yucy': '\u044E', 'yuml': '\u00FF', 'zacute': '\u017A', 'zcaron': '\u017E', 'zcy': '\u0437', 'zdot': '\u017C', 'zeta': '\u03B6', 'zfr': '\uD835\uDD37', 'zhcy': '\u0436', 'zigrarr': '\u21DD', 'zopf': '\uD835\uDD6B', 'zscr': '\uD835\uDCCF', 'zwj': '\u200D', 'zwnj': '\u200C' }; // The &ngsp; pseudo-entity is denoting a space. see: // https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart var NGSP_UNICODE = '\uE500'; NAMED_ENTITIES['ngsp'] = NGSP_UNICODE; var TokenType; (function (TokenType) { TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START"; TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END"; TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID"; TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE"; TokenType[TokenType["INCOMPLETE_TAG_OPEN"] = 4] = "INCOMPLETE_TAG_OPEN"; TokenType[TokenType["TEXT"] = 5] = "TEXT"; TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 6] = "ESCAPABLE_RAW_TEXT"; TokenType[TokenType["RAW_TEXT"] = 7] = "RAW_TEXT"; TokenType[TokenType["COMMENT_START"] = 8] = "COMMENT_START"; TokenType[TokenType["COMMENT_END"] = 9] = "COMMENT_END"; TokenType[TokenType["CDATA_START"] = 10] = "CDATA_START"; TokenType[TokenType["CDATA_END"] = 11] = "CDATA_END"; TokenType[TokenType["ATTR_NAME"] = 12] = "ATTR_NAME"; TokenType[TokenType["ATTR_QUOTE"] = 13] = "ATTR_QUOTE"; TokenType[TokenType["ATTR_VALUE"] = 14] = "ATTR_VALUE"; TokenType[TokenType["DOC_TYPE"] = 15] = "DOC_TYPE"; TokenType[TokenType["EXPANSION_FORM_START"] = 16] = "EXPANSION_FORM_START"; TokenType[TokenType["EXPANSION_CASE_VALUE"] = 17] = "EXPANSION_CASE_VALUE"; TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 18] = "EXPANSION_CASE_EXP_START"; TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 19] = "EXPANSION_CASE_EXP_END"; TokenType[TokenType["EXPANSION_FORM_END"] = 20] = "EXPANSION_FORM_END"; TokenType[TokenType["EOF"] = 21] = "EOF"; })(TokenType || (TokenType = {})); var Token = /** @class */ (function () { function Token(type, parts, sourceSpan) { this.type = type; this.parts = parts; this.sourceSpan = sourceSpan; } return Token; }()); var TokenError = /** @class */ (function (_super) { __extends(TokenError, _super); function TokenError(errorMsg, tokenType, span) { var _this = _super.call(this, span, errorMsg) || this; _this.tokenType = tokenType; return _this; } return TokenError; }(ParseError)); var TokenizeResult = /** @class */ (function () { function TokenizeResult(tokens, errors, nonNormalizedIcuExpressions) { this.tokens = tokens; this.errors = errors; this.nonNormalizedIcuExpressions = nonNormalizedIcuExpressions; } return TokenizeResult; }()); function tokenize(source, url, getTagDefinition, options) { if (options === void 0) { options = {}; } var tokenizer = new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options); tokenizer.tokenize(); return new TokenizeResult(mergeTextTokens(tokenizer.tokens), tokenizer.errors, tokenizer.nonNormalizedIcuExpressions); } var _CR_OR_CRLF_REGEXP = /\r\n?/g; function _unexpectedCharacterErrorMsg(charCode) { var char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode); return "Unexpected character \"" + char + "\""; } function _unknownEntityErrorMsg(entitySrc) { return "Unknown entity \"" + entitySrc + "\" - use the \"&#;\" or \"&#x;\" syntax"; } function _unparsableEntityErrorMsg(type, entityStr) { return "Unable to parse entity \"" + entityStr + "\" - " + type + " character reference entities must end with \";\""; } var CharacterReferenceType; (function (CharacterReferenceType) { CharacterReferenceType["HEX"] = "hexadecimal"; CharacterReferenceType["DEC"] = "decimal"; })(CharacterReferenceType || (CharacterReferenceType = {})); var _ControlFlowError = /** @class */ (function () { function _ControlFlowError(error) { this.error = error; } return _ControlFlowError; }()); // See https://www.w3.org/TR/html51/syntax.html#writing-html-documents var _Tokenizer = /** @class */ (function () { /** * @param _file The html source file being tokenized. * @param _getTagDefinition A function that will retrieve a tag definition for a given tag name. * @param options Configuration of the tokenization. */ function _Tokenizer(_file, _getTagDefinition, options) { this._getTagDefinition = _getTagDefinition; this._currentTokenStart = null; this._currentTokenType = null; this._expansionCaseStack = []; this._inInterpolation = false; this.tokens = []; this.errors = []; this.nonNormalizedIcuExpressions = []; this._tokenizeIcu = options.tokenizeExpansionForms || false; this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG; this._leadingTriviaCodePoints = options.leadingTriviaChars && options.leadingTriviaChars.map(function (c) { return c.codePointAt(0) || 0; }); var range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 }; this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) : new PlainCharacterCursor(_file, range); this._preserveLineEndings = options.preserveLineEndings || false; this._escapedString = options.escapedString || false; this._i18nNormalizeLineEndingsInICUs = options.i18nNormalizeLineEndingsInICUs || false; try { this._cursor.init(); } catch (e) { this.handleError(e); } } _Tokenizer.prototype._processCarriageReturns = function (content) { if (this._preserveLineEndings) { return content; } // https://www.w3.org/TR/html51/syntax.html#preprocessing-the-input-stream // In order to keep the original position in the source, we can not // pre-process it. // Instead CRs are processed right before instantiating the tokens. return content.replace(_CR_OR_CRLF_REGEXP, '\n'); }; _Tokenizer.prototype.tokenize = function () { while (this._cursor.peek() !== $EOF) { var start = this._cursor.clone(); try { if (this._attemptCharCode($LT)) { if (this._attemptCharCode($BANG)) { if (this._attemptCharCode($LBRACKET)) { this._consumeCdata(start); } else if (this._attemptCharCode($MINUS)) { this._consumeComment(start); } else { this._consumeDocType(start); } } else if (this._attemptCharCode($SLASH)) { this._consumeTagClose(start); } else { this._consumeTagOpen(start); } } else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) { this._consumeText(); } } catch (e) { this.handleError(e); } } this._beginToken(TokenType.EOF); this._endToken([]); }; /** * @returns whether an ICU token has been created * @internal */ _Tokenizer.prototype._tokenizeExpansionForm = function () { if (this.isExpansionFormStart()) { this._consumeExpansionFormStart(); return true; } if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) { this._consumeExpansionCaseStart(); return true; } if (this._cursor.peek() === $RBRACE) { if (this._isInExpansionCase()) { this._consumeExpansionCaseEnd(); return true; } if (this._isInExpansionForm()) { this._consumeExpansionFormEnd(); return true; } } return false; }; _Tokenizer.prototype._beginToken = function (type, start) { if (start === void 0) { start = this._cursor.clone(); } this._currentTokenStart = start; this._currentTokenType = type; }; _Tokenizer.prototype._endToken = function (parts, end) { if (this._currentTokenStart === null) { throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end)); } if (this._currentTokenType === null) { throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart)); } var token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints)); this.tokens.push(token); this._currentTokenStart = null; this._currentTokenType = null; return token; }; _Tokenizer.prototype._createError = function (msg, span) { if (this._isInExpansionForm()) { msg += " (Do you have an unescaped \"{\" in your template? Use \"{{ '{' }}\") to escape it.)"; } var error = new TokenError(msg, this._currentTokenType, span); this._currentTokenStart = null; this._currentTokenType = null; return new _ControlFlowError(error); }; _Tokenizer.prototype.handleError = function (e) { if (e instanceof CursorError) { e = this._createError(e.msg, this._cursor.getSpan(e.cursor)); } if (e instanceof _ControlFlowError) { this.errors.push(e.error); } else { throw e; } }; _Tokenizer.prototype._attemptCharCode = function (charCode) { if (this._cursor.peek() === charCode) { this._cursor.advance(); return true; } return false; }; _Tokenizer.prototype._attemptCharCodeCaseInsensitive = function (charCode) { if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) { this._cursor.advance(); return true; } return false; }; _Tokenizer.prototype._requireCharCode = function (charCode) { var location = this._cursor.clone(); if (!this._attemptCharCode(charCode)) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location)); } }; _Tokenizer.prototype._attemptStr = function (chars) { var len = chars.length; if (this._cursor.charsLeft() < len) { return false; } var initialPosition = this._cursor.clone(); for (var i = 0; i < len; i++) { if (!this._attemptCharCode(chars.charCodeAt(i))) { // If attempting to parse the string fails, we want to reset the parser // to where it was before the attempt this._cursor = initialPosition; return false; } } return true; }; _Tokenizer.prototype._attemptStrCaseInsensitive = function (chars) { for (var i = 0; i < chars.length; i++) { if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) { return false; } } return true; }; _Tokenizer.prototype._requireStr = function (chars) { var location = this._cursor.clone(); if (!this._attemptStr(chars)) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location)); } }; _Tokenizer.prototype._attemptCharCodeUntilFn = function (predicate) { while (!predicate(this._cursor.peek())) { this._cursor.advance(); } }; _Tokenizer.prototype._requireCharCodeUntilFn = function (predicate, len) { var start = this._cursor.clone(); this._attemptCharCodeUntilFn(predicate); if (this._cursor.diff(start) < len) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start)); } }; _Tokenizer.prototype._attemptUntilChar = function (char) { while (this._cursor.peek() !== char) { this._cursor.advance(); } }; _Tokenizer.prototype._readChar = function (decodeEntities) { if (decodeEntities && this._cursor.peek() === $AMPERSAND) { return this._decodeEntity(); } else { // Don't rely upon reading directly from `_input` as the actual char value // may have been generated from an escape sequence. var char = String.fromCodePoint(this._cursor.peek()); this._cursor.advance(); return char; } }; _Tokenizer.prototype._decodeEntity = function () { var start = this._cursor.clone(); this._cursor.advance(); if (this._attemptCharCode($HASH)) { var isHex = this._attemptCharCode($x) || this._attemptCharCode($X); var codeStart = this._cursor.clone(); this._attemptCharCodeUntilFn(isDigitEntityEnd); if (this._cursor.peek() != $SEMICOLON) { // Advance cursor to include the peeked character in the string provided to the error // message. this._cursor.advance(); var entityType = isHex ? CharacterReferenceType.HEX : CharacterReferenceType.DEC; throw this._createError(_unparsableEntityErrorMsg(entityType, this._cursor.getChars(start)), this._cursor.getSpan()); } var strNum = this._cursor.getChars(codeStart); this._cursor.advance(); try { var charCode = parseInt(strNum, isHex ? 16 : 10); return String.fromCharCode(charCode); } catch (_a) { throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan()); } } else { var nameStart = this._cursor.clone(); this._attemptCharCodeUntilFn(isNamedEntityEnd); if (this._cursor.peek() != $SEMICOLON) { this._cursor = nameStart; return '&'; } var name = this._cursor.getChars(nameStart); this._cursor.advance(); var char = NAMED_ENTITIES[name]; if (!char) { throw this._createError(_unknownEntityErrorMsg(name), this._cursor.getSpan(start)); } return char; } }; _Tokenizer.prototype._consumeRawText = function (decodeEntities, endMarkerPredicate) { this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT); var parts = []; while (true) { var tagCloseStart = this._cursor.clone(); var foundEndMarker = endMarkerPredicate(); this._cursor = tagCloseStart; if (foundEndMarker) { break; } parts.push(this._readChar(decodeEntities)); } return this._endToken([this._processCarriageReturns(parts.join(''))]); }; _Tokenizer.prototype._consumeComment = function (start) { var _this = this; this._beginToken(TokenType.COMMENT_START, start); this._requireCharCode($MINUS); this._endToken([]); this._consumeRawText(false, function () { return _this._attemptStr('-->'); }); this._beginToken(TokenType.COMMENT_END); this._requireStr('-->'); this._endToken([]); }; _Tokenizer.prototype._consumeCdata = function (start) { var _this = this; this._beginToken(TokenType.CDATA_START, start); this._requireStr('CDATA['); this._endToken([]); this._consumeRawText(false, function () { return _this._attemptStr(']]>'); }); this._beginToken(TokenType.CDATA_END); this._requireStr(']]>'); this._endToken([]); }; _Tokenizer.prototype._consumeDocType = function (start) { this._beginToken(TokenType.DOC_TYPE, start); var contentStart = this._cursor.clone(); this._attemptUntilChar($GT); var content = this._cursor.getChars(contentStart); this._cursor.advance(); this._endToken([content]); }; _Tokenizer.prototype._consumePrefixAndName = function () { var nameOrPrefixStart = this._cursor.clone(); var prefix = ''; while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) { this._cursor.advance(); } var nameStart; if (this._cursor.peek() === $COLON) { prefix = this._cursor.getChars(nameOrPrefixStart); this._cursor.advance(); nameStart = this._cursor.clone(); } else { nameStart = nameOrPrefixStart; } this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1); var name = this._cursor.getChars(nameStart); return [prefix, name]; }; _Tokenizer.prototype._consumeTagOpen = function (start) { var tagName; var prefix; var openTagToken; try { if (!isAsciiLetter(this._cursor.peek())) { throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start)); } openTagToken = this._consumeTagOpenStart(start); prefix = openTagToken.parts[0]; tagName = openTagToken.parts[1]; this._attemptCharCodeUntilFn(isNotWhitespace); while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT && this._cursor.peek() !== $LT && this._cursor.peek() !== $EOF) { this._consumeAttributeName(); this._attemptCharCodeUntilFn(isNotWhitespace); if (this._attemptCharCode($EQ)) { this._attemptCharCodeUntilFn(isNotWhitespace); this._consumeAttributeValue(); } this._attemptCharCodeUntilFn(isNotWhitespace); } this._consumeTagOpenEnd(); } catch (e) { if (e instanceof _ControlFlowError) { if (openTagToken) { // We errored before we could close the opening tag, so it is incomplete. openTagToken.type = TokenType.INCOMPLETE_TAG_OPEN; } else { // When the start tag is invalid, assume we want a "<" as text. // Back to back text tokens are merged at the end. this._beginToken(TokenType.TEXT, start); this._endToken(['<']); } return; } throw e; } var contentTokenType = this._getTagDefinition(tagName).getContentType(prefix); if (contentTokenType === exports.TagContentType.RAW_TEXT) { this._consumeRawTextWithTagClose(prefix, tagName, false); } else if (contentTokenType === exports.TagContentType.ESCAPABLE_RAW_TEXT) { this._consumeRawTextWithTagClose(prefix, tagName, true); } }; _Tokenizer.prototype._consumeRawTextWithTagClose = function (prefix, tagName, decodeEntities) { var _this = this; this._consumeRawText(decodeEntities, function () { if (!_this._attemptCharCode($LT)) return false; if (!_this._attemptCharCode($SLASH)) return false; _this._attemptCharCodeUntilFn(isNotWhitespace); if (!_this._attemptStrCaseInsensitive(tagName)) return false; _this._attemptCharCodeUntilFn(isNotWhitespace); return _this._attemptCharCode($GT); }); this._beginToken(TokenType.TAG_CLOSE); this._requireCharCodeUntilFn(function (code) { return code === $GT; }, 3); this._cursor.advance(); // Consume the `>` this._endToken([prefix, tagName]); }; _Tokenizer.prototype._consumeTagOpenStart = function (start) { this._beginToken(TokenType.TAG_OPEN_START, start); var parts = this._consumePrefixAndName(); return this._endToken(parts); }; _Tokenizer.prototype._consumeAttributeName = function () { var attrNameStart = this._cursor.peek(); if (attrNameStart === $SQ || attrNameStart === $DQ) { throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan()); } this._beginToken(TokenType.ATTR_NAME); var prefixAndName = this._consumePrefixAndName(); this._endToken(prefixAndName); }; _Tokenizer.prototype._consumeAttributeValue = function () { var value; if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) { this._beginToken(TokenType.ATTR_QUOTE); var quoteChar = this._cursor.peek(); this._cursor.advance(); this._endToken([String.fromCodePoint(quoteChar)]); this._beginToken(TokenType.ATTR_VALUE); var parts = []; while (this._cursor.peek() !== quoteChar) { parts.push(this._readChar(true)); } value = parts.join(''); this._endToken([this._processCarriageReturns(value)]); this._beginToken(TokenType.ATTR_QUOTE); this._cursor.advance(); this._endToken([String.fromCodePoint(quoteChar)]); } else { this._beginToken(TokenType.ATTR_VALUE); var valueStart = this._cursor.clone(); this._requireCharCodeUntilFn(isNameEnd, 1); value = this._cursor.getChars(valueStart); this._endToken([this._processCarriageReturns(value)]); } }; _Tokenizer.prototype._consumeTagOpenEnd = function () { var tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END; this._beginToken(tokenType); this._requireCharCode($GT); this._endToken([]); }; _Tokenizer.prototype._consumeTagClose = function (start) { this._beginToken(TokenType.TAG_CLOSE, start); this._attemptCharCodeUntilFn(isNotWhitespace); var prefixAndName = this._consumePrefixAndName(); this._attemptCharCodeUntilFn(isNotWhitespace); this._requireCharCode($GT); this._endToken(prefixAndName); }; _Tokenizer.prototype._consumeExpansionFormStart = function () { this._beginToken(TokenType.EXPANSION_FORM_START); this._requireCharCode($LBRACE); this._endToken([]); this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START); this._beginToken(TokenType.RAW_TEXT); var condition = this._readUntil($COMMA); var normalizedCondition = this._processCarriageReturns(condition); if (this._i18nNormalizeLineEndingsInICUs) { // We explicitly want to normalize line endings for this text. this._endToken([normalizedCondition]); } else { // We are not normalizing line endings. var conditionToken = this._endToken([condition]); if (normalizedCondition !== condition) { this.nonNormalizedIcuExpressions.push(conditionToken); } } this._requireCharCode($COMMA); this._attemptCharCodeUntilFn(isNotWhitespace); this._beginToken(TokenType.RAW_TEXT); var type = this._readUntil($COMMA); this._endToken([type]); this._requireCharCode($COMMA); this._attemptCharCodeUntilFn(isNotWhitespace); }; _Tokenizer.prototype._consumeExpansionCaseStart = function () { this._beginToken(TokenType.EXPANSION_CASE_VALUE); var value = this._readUntil($LBRACE).trim(); this._endToken([value]); this._attemptCharCodeUntilFn(isNotWhitespace); this._beginToken(TokenType.EXPANSION_CASE_EXP_START); this._requireCharCode($LBRACE); this._endToken([]); this._attemptCharCodeUntilFn(isNotWhitespace); this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START); }; _Tokenizer.prototype._consumeExpansionCaseEnd = function () { this._beginToken(TokenType.EXPANSION_CASE_EXP_END); this._requireCharCode($RBRACE); this._endToken([]); this._attemptCharCodeUntilFn(isNotWhitespace); this._expansionCaseStack.pop(); }; _Tokenizer.prototype._consumeExpansionFormEnd = function () { this._beginToken(TokenType.EXPANSION_FORM_END); this._requireCharCode($RBRACE); this._endToken([]); this._expansionCaseStack.pop(); }; _Tokenizer.prototype._consumeText = function () { var start = this._cursor.clone(); this._beginToken(TokenType.TEXT, start); var parts = []; do { if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) { parts.push(this._interpolationConfig.start); this._inInterpolation = true; } else if (this._interpolationConfig && this._inInterpolation && this._attemptStr(this._interpolationConfig.end)) { parts.push(this._interpolationConfig.end); this._inInterpolation = false; } else { parts.push(this._readChar(true)); } } while (!this._isTextEnd()); // It is possible that an interpolation was started but not ended inside this text token. // Make sure that we reset the state of the lexer correctly. this._inInterpolation = false; this._endToken([this._processCarriageReturns(parts.join(''))]); }; _Tokenizer.prototype._isTextEnd = function () { if (this._isTagStart() || this._cursor.peek() === $EOF) { return true; } if (this._tokenizeIcu && !this._inInterpolation) { if (this.isExpansionFormStart()) { // start of an expansion form return true; } if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) { // end of and expansion case return true; } } return false; }; /** * Returns true if the current cursor is pointing to the start of a tag * (opening/closing/comments/cdata/etc). */ _Tokenizer.prototype._isTagStart = function () { if (this._cursor.peek() === $LT) { // We assume that `<` followed by whitespace is not the start of an HTML element. var tmp = this._cursor.clone(); tmp.advance(); // If the next character is alphabetic, ! nor / then it is a tag start var code = tmp.peek(); if (($a <= code && code <= $z) || ($A <= code && code <= $Z) || code === $SLASH || code === $BANG) { return true; } } return false; }; _Tokenizer.prototype._readUntil = function (char) { var start = this._cursor.clone(); this._attemptUntilChar(char); return this._cursor.getChars(start); }; _Tokenizer.prototype._isInExpansionCase = function () { return this._expansionCaseStack.length > 0 && this._expansionCaseStack[this._expansionCaseStack.length - 1] === TokenType.EXPANSION_CASE_EXP_START; }; _Tokenizer.prototype._isInExpansionForm = function () { return this._expansionCaseStack.length > 0 && this._expansionCaseStack[this._expansionCaseStack.length - 1] === TokenType.EXPANSION_FORM_START; }; _Tokenizer.prototype.isExpansionFormStart = function () { if (this._cursor.peek() !== $LBRACE) { return false; } if (this._interpolationConfig) { var start = this._cursor.clone(); var isInterpolation = this._attemptStr(this._interpolationConfig.start); this._cursor = start; return !isInterpolation; } return true; }; return _Tokenizer; }()); function isNotWhitespace(code) { return !isWhitespace(code) || code === $EOF; } function isNameEnd(code) { return isWhitespace(code) || code === $GT || code === $LT || code === $SLASH || code === $SQ || code === $DQ || code === $EQ || code === $EOF; } function isPrefixEnd(code) { return (code < $a || $z < code) && (code < $A || $Z < code) && (code < $0 || code > $9); } function isDigitEntityEnd(code) { return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code); } function isNamedEntityEnd(code) { return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code); } function isExpansionCaseStart(peek) { return peek !== $RBRACE; } function compareCharCodeCaseInsensitive(code1, code2) { return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2); } function toUpperCaseCharCode(code) { return code >= $a && code <= $z ? code - $a + $A : code; } function mergeTextTokens(srcTokens) { var dstTokens = []; var lastDstToken = undefined; for (var i = 0; i < srcTokens.length; i++) { var token = srcTokens[i]; if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) { lastDstToken.parts[0] += token.parts[0]; lastDstToken.sourceSpan.end = token.sourceSpan.end; } else { lastDstToken = token; dstTokens.push(lastDstToken); } } return dstTokens; } var PlainCharacterCursor = /** @class */ (function () { function PlainCharacterCursor(fileOrCursor, range) { if (fileOrCursor instanceof PlainCharacterCursor) { this.file = fileOrCursor.file; this.input = fileOrCursor.input; this.end = fileOrCursor.end; var state = fileOrCursor.state; // Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty. // In ES5 bundles the object spread operator is translated into the `__assign` helper, which // is not optimized by VMs as efficiently as a raw object literal. Since this constructor is // called in tight loops, this difference matters. this.state = { peek: state.peek, offset: state.offset, line: state.line, column: state.column, }; } else { if (!range) { throw new Error('Programming error: the range argument must be provided with a file argument.'); } this.file = fileOrCursor; this.input = fileOrCursor.content; this.end = range.endPos; this.state = { peek: -1, offset: range.startPos, line: range.startLine, column: range.startCol, }; } } PlainCharacterCursor.prototype.clone = function () { return new PlainCharacterCursor(this); }; PlainCharacterCursor.prototype.peek = function () { return this.state.peek; }; PlainCharacterCursor.prototype.charsLeft = function () { return this.end - this.state.offset; }; PlainCharacterCursor.prototype.diff = function (other) { return this.state.offset - other.state.offset; }; PlainCharacterCursor.prototype.advance = function () { this.advanceState(this.state); }; PlainCharacterCursor.prototype.init = function () { this.updatePeek(this.state); }; PlainCharacterCursor.prototype.getSpan = function (start, leadingTriviaCodePoints) { start = start || this; var fullStart = start; if (leadingTriviaCodePoints) { while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) { if (fullStart === start) { start = start.clone(); } start.advance(); } } var startLocation = this.locationFromCursor(start); var endLocation = this.locationFromCursor(this); var fullStartLocation = fullStart !== start ? this.locationFromCursor(fullStart) : startLocation; return new ParseSourceSpan(startLocation, endLocation, fullStartLocation); }; PlainCharacterCursor.prototype.getChars = function (start) { return this.input.substring(start.state.offset, this.state.offset); }; PlainCharacterCursor.prototype.charAt = function (pos) { return this.input.charCodeAt(pos); }; PlainCharacterCursor.prototype.advanceState = function (state) { if (state.offset >= this.end) { this.state = state; throw new CursorError('Unexpected character "EOF"', this); } var currentChar = this.charAt(state.offset); if (currentChar === $LF) { state.line++; state.column = 0; } else if (!isNewLine(currentChar)) { state.column++; } state.offset++; this.updatePeek(state); }; PlainCharacterCursor.prototype.updatePeek = function (state) { state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset); }; PlainCharacterCursor.prototype.locationFromCursor = function (cursor) { return new ParseLocation(cursor.file, cursor.state.offset, cursor.state.line, cursor.state.column); }; return PlainCharacterCursor; }()); var EscapedCharacterCursor = /** @class */ (function (_super) { __extends(EscapedCharacterCursor, _super); function EscapedCharacterCursor(fileOrCursor, range) { var _this = this; if (fileOrCursor instanceof EscapedCharacterCursor) { _this = _super.call(this, fileOrCursor) || this; _this.internalState = Object.assign({}, fileOrCursor.internalState); } else { _this = _super.call(this, fileOrCursor, range) || this; _this.internalState = _this.state; } return _this; } EscapedCharacterCursor.prototype.advance = function () { this.state = this.internalState; _super.prototype.advance.call(this); this.processEscapeSequence(); }; EscapedCharacterCursor.prototype.init = function () { _super.prototype.init.call(this); this.processEscapeSequence(); }; EscapedCharacterCursor.prototype.clone = function () { return new EscapedCharacterCursor(this); }; EscapedCharacterCursor.prototype.getChars = function (start) { var cursor = start.clone(); var chars = ''; while (cursor.internalState.offset < this.internalState.offset) { chars += String.fromCodePoint(cursor.peek()); cursor.advance(); } return chars; }; /** * Process the escape sequence that starts at the current position in the text. * * This method is called to ensure that `peek` has the unescaped value of escape sequences. */ EscapedCharacterCursor.prototype.processEscapeSequence = function () { var _this = this; var peek = function () { return _this.internalState.peek; }; if (peek() === $BACKSLASH) { // We have hit an escape sequence so we need the internal state to become independent // of the external state. this.internalState = Object.assign({}, this.state); // Move past the backslash this.advanceState(this.internalState); // First check for standard control char sequences if (peek() === $n) { this.state.peek = $LF; } else if (peek() === $r) { this.state.peek = $CR; } else if (peek() === $v) { this.state.peek = $VTAB; } else if (peek() === $t) { this.state.peek = $TAB; } else if (peek() === $b) { this.state.peek = $BSPACE; } else if (peek() === $f) { this.state.peek = $FF; } // Now consider more complex sequences else if (peek() === $u) { // Unicode code-point sequence this.advanceState(this.internalState); // advance past the `u` char if (peek() === $LBRACE) { // Variable length Unicode, e.g. `\x{123}` this.advanceState(this.internalState); // advance past the `{` char // Advance past the variable number of hex digits until we hit a `}` char var digitStart = this.clone(); var length = 0; while (peek() !== $RBRACE) { this.advanceState(this.internalState); length++; } this.state.peek = this.decodeHexDigits(digitStart, length); } else { // Fixed length Unicode, e.g. `\u1234` var digitStart = this.clone(); this.advanceState(this.internalState); this.advanceState(this.internalState); this.advanceState(this.internalState); this.state.peek = this.decodeHexDigits(digitStart, 4); } } else if (peek() === $x) { // Hex char code, e.g. `\x2F` this.advanceState(this.internalState); // advance past the `x` char var digitStart = this.clone(); this.advanceState(this.internalState); this.state.peek = this.decodeHexDigits(digitStart, 2); } else if (isOctalDigit(peek())) { // Octal char code, e.g. `\012`, var octal = ''; var length = 0; var previous = this.clone(); while (isOctalDigit(peek()) && length < 3) { previous = this.clone(); octal += String.fromCodePoint(peek()); this.advanceState(this.internalState); length++; } this.state.peek = parseInt(octal, 8); // Backup one char this.internalState = previous.internalState; } else if (isNewLine(this.internalState.peek)) { // Line continuation `\` followed by a new line this.advanceState(this.internalState); // advance over the newline this.state = this.internalState; } else { // If none of the `if` blocks were executed then we just have an escaped normal character. // In that case we just, effectively, skip the backslash from the character. this.state.peek = this.internalState.peek; } } }; EscapedCharacterCursor.prototype.decodeHexDigits = function (start, length) { var hex = this.input.substr(start.internalState.offset, length); var charCode = parseInt(hex, 16); if (!isNaN(charCode)) { return charCode; } else { start.state = start.internalState; throw new CursorError('Invalid hexadecimal escape sequence', start); } }; return EscapedCharacterCursor; }(PlainCharacterCursor)); var CursorError = /** @class */ (function () { function CursorError(msg, cursor) { this.msg = msg; this.cursor = cursor; } return CursorError; }()); var TreeError = /** @class */ (function (_super) { __extends(TreeError, _super); function TreeError(elementName, span, msg) { var _this = _super.call(this, span, msg) || this; _this.elementName = elementName; return _this; } TreeError.create = function (elementName, span, msg) { return new TreeError(elementName, span, msg); }; return TreeError; }(ParseError)); var ParseTreeResult = /** @class */ (function () { function ParseTreeResult(rootNodes, errors) { this.rootNodes = rootNodes; this.errors = errors; } return ParseTreeResult; }()); var Parser = /** @class */ (function () { function Parser(getTagDefinition) { this.getTagDefinition = getTagDefinition; } Parser.prototype.parse = function (source, url, options) { var tokenizeResult = tokenize(source, url, this.getTagDefinition, options); var parser = new _TreeBuilder(tokenizeResult.tokens, this.getTagDefinition); parser.build(); return new ParseTreeResult(parser.rootNodes, tokenizeResult.errors.concat(parser.errors)); }; return Parser; }()); var _TreeBuilder = /** @class */ (function () { function _TreeBuilder(tokens, getTagDefinition) { this.tokens = tokens; this.getTagDefinition = getTagDefinition; this._index = -1; this._elementStack = []; this.rootNodes = []; this.errors = []; this._advance(); } _TreeBuilder.prototype.build = function () { while (this._peek.type !== TokenType.EOF) { if (this._peek.type === TokenType.TAG_OPEN_START || this._peek.type === TokenType.INCOMPLETE_TAG_OPEN) { this._consumeStartTag(this._advance()); } else if (this._peek.type === TokenType.TAG_CLOSE) { this._consumeEndTag(this._advance()); } else if (this._peek.type === TokenType.CDATA_START) { this._closeVoidElement(); this._consumeCdata(this._advance()); } else if (this._peek.type === TokenType.COMMENT_START) { this._closeVoidElement(); this._consumeComment(this._advance()); } else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT || this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) { this._closeVoidElement(); this._consumeText(this._advance()); } else if (this._peek.type === TokenType.EXPANSION_FORM_START) { this._consumeExpansion(this._advance()); } else { // Skip all other tokens... this._advance(); } } }; _TreeBuilder.prototype._advance = function () { var prev = this._peek; if (this._index < this.tokens.length - 1) { // Note: there is always an EOF token at the end this._index++; } this._peek = this.tokens[this._index]; return prev; }; _TreeBuilder.prototype._advanceIf = function (type) { if (this._peek.type === type) { return this._advance(); } return null; }; _TreeBuilder.prototype._consumeCdata = function (_startToken) { this._consumeText(this._advance()); this._advanceIf(TokenType.CDATA_END); }; _TreeBuilder.prototype._consumeComment = function (token) { var text = this._advanceIf(TokenType.RAW_TEXT); this._advanceIf(TokenType.COMMENT_END); var value = text != null ? text.parts[0].trim() : null; this._addToParent(new Comment$1(value, token.sourceSpan)); }; _TreeBuilder.prototype._consumeExpansion = function (token) { var switchValue = this._advance(); var type = this._advance(); var cases = []; // read = while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) { var expCase = this._parseExpansionCase(); if (!expCase) return; // error cases.push(expCase); } // read the final } if (this._peek.type !== TokenType.EXPANSION_FORM_END) { this.errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '}'.")); return; } var sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end, token.sourceSpan.fullStart); this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan)); this._advance(); }; _TreeBuilder.prototype._parseExpansionCase = function () { var value = this._advance(); // read { if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) { this.errors.push(TreeError.create(null, this._peek.sourceSpan, "Invalid ICU message. Missing '{'.")); return null; } // read until } var start = this._advance(); var exp = this._collectExpansionExpTokens(start); if (!exp) return null; var end = this._advance(); exp.push(new Token(TokenType.EOF, [], end.sourceSpan)); // parse everything in between { and } var expansionCaseParser = new _TreeBuilder(exp, this.getTagDefinition); expansionCaseParser.build(); if (expansionCaseParser.errors.length > 0) { this.errors = this.errors.concat(expansionCaseParser.errors); return null; } var sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end, value.sourceSpan.fullStart); var expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end, start.sourceSpan.fullStart); return new ExpansionCase(value.parts[0], expansionCaseParser.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan); }; _TreeBuilder.prototype._collectExpansionExpTokens = function (start) { var exp = []; var expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START]; while (true) { if (this._peek.type === TokenType.EXPANSION_FORM_START || this._peek.type === TokenType.EXPANSION_CASE_EXP_START) { expansionFormStack.push(this._peek.type); } if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) { if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) { expansionFormStack.pop(); if (expansionFormStack.length == 0) return exp; } else { this.errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'.")); return null; } } if (this._peek.type === TokenType.EXPANSION_FORM_END) { if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) { expansionFormStack.pop(); } else { this.errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'.")); return null; } } if (this._peek.type === TokenType.EOF) { this.errors.push(TreeError.create(null, start.sourceSpan, "Invalid ICU message. Missing '}'.")); return null; } exp.push(this._advance()); } }; _TreeBuilder.prototype._consumeText = function (token) { var text = token.parts[0]; if (text.length > 0 && text[0] == '\n') { var parent = this._getParentElement(); if (parent != null && parent.children.length == 0 && this.getTagDefinition(parent.name).ignoreFirstLf) { text = text.substring(1); } } if (text.length > 0) { this._addToParent(new Text$3(text, token.sourceSpan)); } }; _TreeBuilder.prototype._closeVoidElement = function () { var el = this._getParentElement(); if (el && this.getTagDefinition(el.name).isVoid) { this._elementStack.pop(); } }; _TreeBuilder.prototype._consumeStartTag = function (startTagToken) { var _a = __read(startTagToken.parts, 2), prefix = _a[0], name = _a[1]; var attrs = []; while (this._peek.type === TokenType.ATTR_NAME) { attrs.push(this._consumeAttr(this._advance())); } var fullName = this._getElementFullName(prefix, name, this._getParentElement()); var selfClosing = false; // Note: There could have been a tokenizer error // so that we don't get a token for the end tag... if (this._peek.type === TokenType.TAG_OPEN_END_VOID) { this._advance(); selfClosing = true; var tagDef = this.getTagDefinition(fullName); if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) { this.errors.push(TreeError.create(fullName, startTagToken.sourceSpan, "Only void and foreign elements can be self closed \"" + startTagToken.parts[1] + "\"")); } } else if (this._peek.type === TokenType.TAG_OPEN_END) { this._advance(); selfClosing = false; } var end = this._peek.sourceSpan.fullStart; var span = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart); // Create a separate `startSpan` because `span` will be modified when there is an `end` span. var startSpan = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart); var el = new Element$1(fullName, attrs, [], span, startSpan, undefined); this._pushElement(el); if (selfClosing) { // Elements that are self-closed have their `endSourceSpan` set to the full span, as the // element start tag also represents the end tag. this._popElement(fullName, span); } else if (startTagToken.type === TokenType.INCOMPLETE_TAG_OPEN) { // We already know the opening tag is not complete, so it is unlikely it has a corresponding // close tag. Let's optimistically parse it as a full element and emit an error. this._popElement(fullName, null); this.errors.push(TreeError.create(fullName, span, "Opening tag \"" + fullName + "\" not terminated.")); } }; _TreeBuilder.prototype._pushElement = function (el) { var parentEl = this._getParentElement(); if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) { this._elementStack.pop(); } this._addToParent(el); this._elementStack.push(el); }; _TreeBuilder.prototype._consumeEndTag = function (endTagToken) { var fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement()); if (this.getTagDefinition(fullName).isVoid) { this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, "Void elements do not have end tags \"" + endTagToken.parts[1] + "\"")); } else if (!this._popElement(fullName, endTagToken.sourceSpan)) { var errMsg = "Unexpected closing tag \"" + fullName + "\". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags"; this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg)); } }; /** * Closes the nearest element with the tag name `fullName` in the parse tree. * `endSourceSpan` is the span of the closing tag, or null if the element does * not have a closing tag (for example, this happens when an incomplete * opening tag is recovered). */ _TreeBuilder.prototype._popElement = function (fullName, endSourceSpan) { var unexpectedCloseTagDetected = false; for (var stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) { var el = this._elementStack[stackIndex]; if (el.name == fullName) { // Record the parse span with the element that is being closed. Any elements that are // removed from the element stack at this point are closed implicitly, so they won't get // an end source span (as there is no explicit closing element). el.endSourceSpan = endSourceSpan; el.sourceSpan.end = endSourceSpan !== null ? endSourceSpan.end : el.sourceSpan.end; this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex); return !unexpectedCloseTagDetected; } if (!this.getTagDefinition(el.name).closedByParent) { // Note that we encountered an unexpected close tag but continue processing the element // stack so we can assign an `endSourceSpan` if there is a corresponding start tag for this // end tag in the stack. unexpectedCloseTagDetected = true; } } return false; }; _TreeBuilder.prototype._consumeAttr = function (attrName) { var fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]); var end = attrName.sourceSpan.end; var value = ''; var valueSpan = undefined; if (this._peek.type === TokenType.ATTR_QUOTE) { this._advance(); } if (this._peek.type === TokenType.ATTR_VALUE) { var valueToken = this._advance(); value = valueToken.parts[0]; end = valueToken.sourceSpan.end; valueSpan = valueToken.sourceSpan; } if (this._peek.type === TokenType.ATTR_QUOTE) { var quoteToken = this._advance(); end = quoteToken.sourceSpan.end; } var keySpan = new ParseSourceSpan(attrName.sourceSpan.start, attrName.sourceSpan.end); return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end, attrName.sourceSpan.fullStart), keySpan, valueSpan); }; _TreeBuilder.prototype._getParentElement = function () { return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null; }; _TreeBuilder.prototype._addToParent = function (node) { var parent = this._getParentElement(); if (parent != null) { parent.children.push(node); } else { this.rootNodes.push(node); } }; _TreeBuilder.prototype._getElementFullName = function (prefix, localName, parentElement) { if (prefix === '') { prefix = this.getTagDefinition(localName).implicitNamespacePrefix || ''; if (prefix === '' && parentElement != null) { var parentTagName = splitNsName(parentElement.name)[1]; var parentTagDefinition = this.getTagDefinition(parentTagName); if (!parentTagDefinition.preventNamespaceInheritance) { prefix = getNsPrefix(parentElement.name); } } } return mergeNsAndName(prefix, localName); }; return _TreeBuilder; }()); function lastOnStack(stack, element) { return stack.length > 0 && stack[stack.length - 1] === element; } var HtmlParser = /** @class */ (function (_super) { __extends(HtmlParser, _super); function HtmlParser() { return _super.call(this, getHtmlTagDefinition) || this; } HtmlParser.prototype.parse = function (source, url, options) { return _super.prototype.parse.call(this, source, url, options); }; return HtmlParser; }(Parser)); /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces'; var SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']); // Equivalent to \s with \u00a0 (non-breaking space) excluded. // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp var WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff'; var NO_WS_REGEXP = new RegExp("[^" + WS_CHARS + "]"); var WS_REPLACE_REGEXP = new RegExp("[" + WS_CHARS + "]{2,}", 'g'); function hasPreserveWhitespacesAttr(attrs) { return attrs.some(function (attr) { return attr.name === PRESERVE_WS_ATTR_NAME; }); } /** * Angular Dart introduced &ngsp; as a placeholder for non-removable space, see: * https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32 * In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character * and later on replaced by a space. We are re-implementing the same idea here. */ function replaceNgsp(value) { // lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' '); } /** * This visitor can walk HTML parse tree and remove / trim text nodes using the following rules: * - consider spaces, tabs and new lines as whitespace characters; * - drop text nodes consisting of whitespace characters only; * - for all other text nodes replace consecutive whitespace characters with one space; * - convert &ngsp; pseudo-entity to a single space; * * Removal and trimming of whitespaces have positive performance impact (less code to generate * while compiling templates, faster view creation). At the same time it can be "destructive" * in some cases (whitespaces can influence layout). Because of the potential of breaking layout * this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for * whitespace removal. The default option for whitespace removal will be revisited in Angular 6 * and might be changed to "on" by default. */ var WhitespaceVisitor = /** @class */ (function () { function WhitespaceVisitor() { } WhitespaceVisitor.prototype.visitElement = function (element, context) { if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) { // don't descent into elements where we need to preserve whitespaces // but still visit all attributes to eliminate one used as a market to preserve WS return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n); } return new Element$1(element.name, element.attrs, visitAllWithSiblings(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n); }; WhitespaceVisitor.prototype.visitAttribute = function (attribute, context) { return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null; }; WhitespaceVisitor.prototype.visitText = function (text, context) { var isNotBlank = text.value.match(NO_WS_REGEXP); var hasExpansionSibling = context && (context.prev instanceof Expansion || context.next instanceof Expansion); if (isNotBlank || hasExpansionSibling) { return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n); } return null; }; WhitespaceVisitor.prototype.visitComment = function (comment, context) { return comment; }; WhitespaceVisitor.prototype.visitExpansion = function (expansion, context) { return expansion; }; WhitespaceVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return expansionCase; }; return WhitespaceVisitor; }()); function removeWhitespaces(htmlAstWithErrors) { return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors); } function visitAllWithSiblings(visitor, nodes) { var result = []; nodes.forEach(function (ast, i) { var context = { prev: nodes[i - 1], next: nodes[i + 1] }; var astResult = ast.visit(visitor, context); if (astResult) { result.push(astResult); } }); return result; } // http://cldr.unicode.org/index/cldr-spec/plural-rules var PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other']; /** * Expands special forms into elements. * * For example, * * ``` * { messages.length, plural, * =0 {zero} * =1 {one} * other {more than one} * } * ``` * * will be expanded into * * ``` * * zero * one * more than one * * ``` */ function expandNodes(nodes) { var expander = new _Expander(); return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors); } var ExpansionResult = /** @class */ (function () { function ExpansionResult(nodes, expanded, errors) { this.nodes = nodes; this.expanded = expanded; this.errors = errors; } return ExpansionResult; }()); var ExpansionError = /** @class */ (function (_super) { __extends(ExpansionError, _super); function ExpansionError(span, errorMsg) { return _super.call(this, span, errorMsg) || this; } return ExpansionError; }(ParseError)); /** * Expand expansion forms (plural, select) to directives * * @internal */ var _Expander = /** @class */ (function () { function _Expander() { this.isExpanded = false; this.errors = []; } _Expander.prototype.visitElement = function (element, context) { return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan); }; _Expander.prototype.visitAttribute = function (attribute, context) { return attribute; }; _Expander.prototype.visitText = function (text, context) { return text; }; _Expander.prototype.visitComment = function (comment, context) { return comment; }; _Expander.prototype.visitExpansion = function (icu, context) { this.isExpanded = true; return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) : _expandDefaultForm(icu, this.errors); }; _Expander.prototype.visitExpansionCase = function (icuCase, context) { throw new Error('Should not be reached'); }; return _Expander; }()); // Plural forms are expanded to `NgPlural` and `NgPluralCase`s function _expandPluralForm(ast, errors) { var children = ast.cases.map(function (c) { if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) { errors.push(new ExpansionError(c.valueSourceSpan, "Plural cases should be \"=\" or one of " + PLURAL_CASES.join(', '))); } var expansionResult = expandNodes(c.expression); errors.push.apply(errors, __spreadArray([], __read(expansionResult.errors))); return new Element$1("ng-template", [new Attribute('ngPluralCase', "" + c.value, c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); }); var switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */); return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan); } // ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s function _expandDefaultForm(ast, errors) { var children = ast.cases.map(function (c) { var expansionResult = expandNodes(c.expression); errors.push.apply(errors, __spreadArray([], __read(expansionResult.errors))); if (c.value === 'other') { // other is the default case when no values match return new Element$1("ng-template", [new Attribute('ngSwitchDefault', '', c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); } return new Element$1("ng-template", [new Attribute('ngSwitchCase', "" + c.value, c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan); }); var switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */); return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan); } var _a; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A segment of text within the template. */ var TextAst = /** @class */ (function () { function TextAst(value, ngContentIndex, sourceSpan) { this.value = value; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } TextAst.prototype.visit = function (visitor, context) { return visitor.visitText(this, context); }; return TextAst; }()); /** * A bound expression within the text of a template. */ var BoundTextAst = /** @class */ (function () { function BoundTextAst(value, ngContentIndex, sourceSpan) { this.value = value; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } BoundTextAst.prototype.visit = function (visitor, context) { return visitor.visitBoundText(this, context); }; return BoundTextAst; }()); /** * A plain attribute on an element. */ var AttrAst = /** @class */ (function () { function AttrAst(name, value, sourceSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; } AttrAst.prototype.visit = function (visitor, context) { return visitor.visitAttr(this, context); }; return AttrAst; }()); var BoundPropertyMapping = (_a = {}, _a[4 /* Animation */] = 4 /* Animation */, _a[1 /* Attribute */] = 1 /* Attribute */, _a[2 /* Class */] = 2 /* Class */, _a[0 /* Property */] = 0 /* Property */, _a[3 /* Style */] = 3 /* Style */, _a); /** * A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g. * `[@trigger]="stateExp"`) */ var BoundElementPropertyAst = /** @class */ (function () { function BoundElementPropertyAst(name, type, securityContext, value, unit, sourceSpan) { this.name = name; this.type = type; this.securityContext = securityContext; this.value = value; this.unit = unit; this.sourceSpan = sourceSpan; this.isAnimation = this.type === 4 /* Animation */; } BoundElementPropertyAst.fromBoundProperty = function (prop) { var type = BoundPropertyMapping[prop.type]; return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan); }; BoundElementPropertyAst.prototype.visit = function (visitor, context) { return visitor.visitElementProperty(this, context); }; return BoundElementPropertyAst; }()); /** * A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g. * `(@trigger.phase)="callback($event)"`). */ var BoundEventAst = /** @class */ (function () { function BoundEventAst(name, target, phase, handler, sourceSpan, handlerSpan) { this.name = name; this.target = target; this.phase = phase; this.handler = handler; this.sourceSpan = sourceSpan; this.handlerSpan = handlerSpan; this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase); this.isAnimation = !!this.phase; } BoundEventAst.calcFullName = function (name, target, phase) { if (target) { return target + ":" + name; } if (phase) { return "@" + name + "." + phase; } return name; }; BoundEventAst.fromParsedEvent = function (event) { var target = event.type === 0 /* Regular */ ? event.targetOrPhase : null; var phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null; return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan); }; BoundEventAst.prototype.visit = function (visitor, context) { return visitor.visitEvent(this, context); }; return BoundEventAst; }()); /** * A reference declaration on an element (e.g. `let someName="expression"`). */ var ReferenceAst = /** @class */ (function () { function ReferenceAst(name, value, originalValue, sourceSpan) { this.name = name; this.value = value; this.originalValue = originalValue; this.sourceSpan = sourceSpan; } ReferenceAst.prototype.visit = function (visitor, context) { return visitor.visitReference(this, context); }; return ReferenceAst; }()); /** * A variable declaration on a (e.g. `var-someName="someLocalName"`). */ var VariableAst = /** @class */ (function () { function VariableAst(name, value, sourceSpan, valueSpan) { this.name = name; this.value = value; this.sourceSpan = sourceSpan; this.valueSpan = valueSpan; } VariableAst.fromParsedVariable = function (v) { return new VariableAst(v.name, v.value, v.sourceSpan, v.valueSpan); }; VariableAst.prototype.visit = function (visitor, context) { return visitor.visitVariable(this, context); }; return VariableAst; }()); /** * An element declaration in a template. */ var ElementAst = /** @class */ (function () { function ElementAst(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) { this.name = name; this.attrs = attrs; this.inputs = inputs; this.outputs = outputs; this.references = references; this.directives = directives; this.providers = providers; this.hasViewContainer = hasViewContainer; this.queryMatches = queryMatches; this.children = children; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; this.endSourceSpan = endSourceSpan; } ElementAst.prototype.visit = function (visitor, context) { return visitor.visitElement(this, context); }; return ElementAst; }()); /** * A `` element included in an Angular template. */ var EmbeddedTemplateAst = /** @class */ (function () { function EmbeddedTemplateAst(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) { this.attrs = attrs; this.outputs = outputs; this.references = references; this.variables = variables; this.directives = directives; this.providers = providers; this.hasViewContainer = hasViewContainer; this.queryMatches = queryMatches; this.children = children; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } EmbeddedTemplateAst.prototype.visit = function (visitor, context) { return visitor.visitEmbeddedTemplate(this, context); }; return EmbeddedTemplateAst; }()); /** * A directive property with a bound value (e.g. `*ngIf="condition"). */ var BoundDirectivePropertyAst = /** @class */ (function () { function BoundDirectivePropertyAst(directiveName, templateName, value, sourceSpan) { this.directiveName = directiveName; this.templateName = templateName; this.value = value; this.sourceSpan = sourceSpan; } BoundDirectivePropertyAst.prototype.visit = function (visitor, context) { return visitor.visitDirectiveProperty(this, context); }; return BoundDirectivePropertyAst; }()); /** * A directive declared on an element. */ var DirectiveAst = /** @class */ (function () { function DirectiveAst(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) { this.directive = directive; this.inputs = inputs; this.hostProperties = hostProperties; this.hostEvents = hostEvents; this.contentQueryStartId = contentQueryStartId; this.sourceSpan = sourceSpan; } DirectiveAst.prototype.visit = function (visitor, context) { return visitor.visitDirective(this, context); }; return DirectiveAst; }()); /** * A provider declared on an element */ var ProviderAst = /** @class */ (function () { function ProviderAst(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) { this.token = token; this.multiProvider = multiProvider; this.eager = eager; this.providers = providers; this.providerType = providerType; this.lifecycleHooks = lifecycleHooks; this.sourceSpan = sourceSpan; this.isModule = isModule; } ProviderAst.prototype.visit = function (visitor, context) { // No visit method in the visitor for now... return null; }; return ProviderAst; }()); (function (ProviderAstType) { ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService"; ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService"; ProviderAstType[ProviderAstType["Component"] = 2] = "Component"; ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive"; ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin"; })(exports.ProviderAstType || (exports.ProviderAstType = {})); /** * Position where content is to be projected (instance of `` in a template). */ var NgContentAst = /** @class */ (function () { function NgContentAst(index, ngContentIndex, sourceSpan) { this.index = index; this.ngContentIndex = ngContentIndex; this.sourceSpan = sourceSpan; } NgContentAst.prototype.visit = function (visitor, context) { return visitor.visitNgContent(this, context); }; return NgContentAst; }()); /** * A visitor that accepts each node but doesn't do anything. It is intended to be used * as the base class for a visitor that is only interested in a subset of the node types. */ var NullTemplateVisitor = /** @class */ (function () { function NullTemplateVisitor() { } NullTemplateVisitor.prototype.visitNgContent = function (ast, context) { }; NullTemplateVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { }; NullTemplateVisitor.prototype.visitElement = function (ast, context) { }; NullTemplateVisitor.prototype.visitReference = function (ast, context) { }; NullTemplateVisitor.prototype.visitVariable = function (ast, context) { }; NullTemplateVisitor.prototype.visitEvent = function (ast, context) { }; NullTemplateVisitor.prototype.visitElementProperty = function (ast, context) { }; NullTemplateVisitor.prototype.visitAttr = function (ast, context) { }; NullTemplateVisitor.prototype.visitBoundText = function (ast, context) { }; NullTemplateVisitor.prototype.visitText = function (ast, context) { }; NullTemplateVisitor.prototype.visitDirective = function (ast, context) { }; NullTemplateVisitor.prototype.visitDirectiveProperty = function (ast, context) { }; return NullTemplateVisitor; }()); /** * Base class that can be used to build a visitor that visits each node * in an template ast recursively. */ var RecursiveTemplateAstVisitor = /** @class */ (function (_super) { __extends(RecursiveTemplateAstVisitor, _super); function RecursiveTemplateAstVisitor() { return _super.call(this) || this; } // Nodes with children RecursiveTemplateAstVisitor.prototype.visitEmbeddedTemplate = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.attrs); visit(ast.references); visit(ast.variables); visit(ast.directives); visit(ast.providers); visit(ast.children); }); }; RecursiveTemplateAstVisitor.prototype.visitElement = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.attrs); visit(ast.inputs); visit(ast.outputs); visit(ast.references); visit(ast.directives); visit(ast.providers); visit(ast.children); }); }; RecursiveTemplateAstVisitor.prototype.visitDirective = function (ast, context) { return this.visitChildren(context, function (visit) { visit(ast.inputs); visit(ast.hostProperties); visit(ast.hostEvents); }); }; RecursiveTemplateAstVisitor.prototype.visitChildren = function (context, cb) { var results = []; var t = this; function visit(children) { if (children && children.length) results.push(templateVisitAll(t, children, context)); } cb(visit); return Array.prototype.concat.apply([], results); }; return RecursiveTemplateAstVisitor; }(NullTemplateVisitor)); /** * Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}. */ function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var result = []; var visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; } var ProviderError = /** @class */ (function (_super) { __extends(ProviderError, _super); function ProviderError(message, span) { return _super.call(this, span, message) || this; } return ProviderError; }(ParseError)); var ProviderViewContext = /** @class */ (function () { function ProviderViewContext(reflector, component) { var _this = this; this.reflector = reflector; this.component = component; this.errors = []; this.viewQueries = _getViewQueries(component); this.viewProviders = new Map(); component.viewProviders.forEach(function (provider) { if (_this.viewProviders.get(tokenReference(provider.token)) == null) { _this.viewProviders.set(tokenReference(provider.token), true); } }); } return ProviderViewContext; }()); var ProviderElementContext = /** @class */ (function () { function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) { var _this = this; this.viewContext = viewContext; this._parent = _parent; this._isViewRoot = _isViewRoot; this._directiveAsts = _directiveAsts; this._sourceSpan = _sourceSpan; this._transformedProviders = new Map(); this._seenProviders = new Map(); this._queriedTokens = new Map(); this.transformedHasViewContainer = false; this._attrs = {}; attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; }); var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; }); this._allProviders = _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors); this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta); Array.from(this._allProviders.values()).forEach(function (provider) { _this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens); }); if (isTemplate) { var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers$1.TemplateRef); this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens); } refs.forEach(function (refAst) { var defaultQueryValue = refAst.value || createTokenForExternalReference(_this.viewContext.reflector, Identifiers$1.ElementRef); _this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens); }); if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers$1.ViewContainerRef))) { this.transformedHasViewContainer = true; } // create the providers that we know are eager first Array.from(this._allProviders.values()).forEach(function (provider) { var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token)); if (eager) { _this._getOrCreateLocalProvider(provider.providerType, provider.token, true); } }); } ProviderElementContext.prototype.afterElement = function () { var _this = this; // collect lazy providers Array.from(this._allProviders.values()).forEach(function (provider) { _this._getOrCreateLocalProvider(provider.providerType, provider.token, false); }); }; Object.defineProperty(ProviderElementContext.prototype, "transformProviders", { get: function () { // Note: Maps keep their insertion order. var lazyProviders = []; var eagerProviders = []; this._transformedProviders.forEach(function (provider) { if (provider.eager) { eagerProviders.push(provider); } else { lazyProviders.push(provider); } }); return lazyProviders.concat(eagerProviders); }, enumerable: false, configurable: true }); Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", { get: function () { var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; }); var sortedDirectives = this._directiveAsts.slice(); sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) - sortedProviderTypes.indexOf(dir2.directive.type); }); return sortedDirectives; }, enumerable: false, configurable: true }); Object.defineProperty(ProviderElementContext.prototype, "queryMatches", { get: function () { var allMatches = []; this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, __spreadArray([], __read(matches))); }); return allMatches; }, enumerable: false, configurable: true }); ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) { this._getQueriesFor(token).forEach(function (query) { var queryValue = query.meta.read || defaultValue; var tokenRef = tokenReference(queryValue); var queryMatches = queryReadTokens.get(tokenRef); if (!queryMatches) { queryMatches = []; queryReadTokens.set(tokenRef, queryMatches); } queryMatches.push({ queryId: query.queryId, value: queryValue }); }); }; ProviderElementContext.prototype._getQueriesFor = function (token) { var result = []; var currentEl = this; var distance = 0; var queries; while (currentEl !== null) { queries = currentEl._contentQueries.get(tokenReference(token)); if (queries) { result.push.apply(result, __spreadArray([], __read(queries.filter(function (query) { return query.meta.descendants || distance <= 1; })))); } if (currentEl._directiveAsts.length > 0) { distance++; } currentEl = currentEl._parent; } queries = this.viewContext.viewQueries.get(tokenReference(token)); if (queries) { result.push.apply(result, __spreadArray([], __read(queries))); } return result; }; ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) { var _this = this; var resolvedProvider = this._allProviders.get(tokenReference(token)); if (!resolvedProvider || ((requestingProviderType === exports.ProviderAstType.Directive || requestingProviderType === exports.ProviderAstType.PublicService) && resolvedProvider.providerType === exports.ProviderAstType.PrivateService) || ((requestingProviderType === exports.ProviderAstType.PrivateService || requestingProviderType === exports.ProviderAstType.PublicService) && resolvedProvider.providerType === exports.ProviderAstType.Builtin)) { return null; } var transformedProviderAst = this._transformedProviders.get(tokenReference(token)); if (transformedProviderAst) { return transformedProviderAst; } if (this._seenProviders.get(tokenReference(token)) != null) { this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan)); return null; } this._seenProviders.set(tokenReference(token), true); var transformedProviders = resolvedProvider.providers.map(function (provider) { var transformedUseValue = provider.useValue; var transformedUseExisting = provider.useExisting; var transformedDeps = undefined; if (provider.useExisting != null) { var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager); if (existingDiDep.token != null) { transformedUseExisting = existingDiDep.token; } else { transformedUseExisting = null; transformedUseValue = existingDiDep.value; } } else if (provider.useFactory) { var deps = provider.deps || provider.useFactory.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); }); } else if (provider.useClass) { var deps = provider.deps || provider.useClass.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); }); } return _transformProvider(provider, { useExisting: transformedUseExisting, useValue: transformedUseValue, deps: transformedDeps }); }); transformedProviderAst = _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders }); this._transformedProviders.set(tokenReference(token), transformedProviderAst); return transformedProviderAst; }; ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) { if (eager === void 0) { eager = false; } if (dep.isAttribute) { var attrValue = this._attrs[dep.token.value]; return { isValue: true, value: attrValue == null ? null : attrValue }; } if (dep.token != null) { // access builtints if ((requestingProviderType === exports.ProviderAstType.Directive || requestingProviderType === exports.ProviderAstType.Component)) { if (tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers$1.Renderer) || tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers$1.ElementRef) || tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers$1.ChangeDetectorRef) || tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers$1.TemplateRef)) { return dep; } if (tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers$1.ViewContainerRef)) { this.transformedHasViewContainer = true; } } // access the injector if (tokenReference(dep.token) === this.viewContext.reflector.resolveExternalReference(Identifiers$1.Injector)) { return dep; } // access providers if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) { return dep; } } return null; }; ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) { if (eager === void 0) { eager = false; } var currElement = this; var currEager = eager; var result = null; if (!dep.isSkipSelf) { result = this._getLocalDependency(requestingProviderType, dep, eager); } if (dep.isSelf) { if (!result && dep.isOptional) { result = { isValue: true, value: null }; } } else { // check parent elements while (!result && currElement._parent) { var prevElement = currElement; currElement = currElement._parent; if (prevElement._isViewRoot) { currEager = false; } result = currElement._getLocalDependency(exports.ProviderAstType.PublicService, dep, currEager); } // check @Host restriction if (!result) { if (!dep.isHost || this.viewContext.component.isHost || this.viewContext.component.type.reference === tokenReference(dep.token) || this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) { result = dep; } else { result = dep.isOptional ? { isValue: true, value: null } : null; } } } if (!result) { this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan)); } return result; }; return ProviderElementContext; }()); var NgModuleProviderAnalyzer = /** @class */ (function () { function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) { var _this = this; this.reflector = reflector; this._transformedProviders = new Map(); this._seenProviders = new Map(); this._errors = []; this._allProviders = new Map(); ngModule.transitiveModule.modules.forEach(function (ngModuleType) { var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType }; _resolveProviders([ngModuleProvider], exports.ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true); }); _resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), exports.ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders, /* isModule */ false); } NgModuleProviderAnalyzer.prototype.parse = function () { var _this = this; Array.from(this._allProviders.values()).forEach(function (provider) { _this._getOrCreateLocalProvider(provider.token, provider.eager); }); if (this._errors.length > 0) { var errorString = this._errors.join('\n'); throw new Error("Provider parse errors:\n" + errorString); } // Note: Maps keep their insertion order. var lazyProviders = []; var eagerProviders = []; this._transformedProviders.forEach(function (provider) { if (provider.eager) { eagerProviders.push(provider); } else { lazyProviders.push(provider); } }); return lazyProviders.concat(eagerProviders); }; NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) { var _this = this; var resolvedProvider = this._allProviders.get(tokenReference(token)); if (!resolvedProvider) { return null; } var transformedProviderAst = this._transformedProviders.get(tokenReference(token)); if (transformedProviderAst) { return transformedProviderAst; } if (this._seenProviders.get(tokenReference(token)) != null) { this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan)); return null; } this._seenProviders.set(tokenReference(token), true); var transformedProviders = resolvedProvider.providers.map(function (provider) { var transformedUseValue = provider.useValue; var transformedUseExisting = provider.useExisting; var transformedDeps = undefined; if (provider.useExisting != null) { var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan); if (existingDiDep.token != null) { transformedUseExisting = existingDiDep.token; } else { transformedUseExisting = null; transformedUseValue = existingDiDep.value; } } else if (provider.useFactory) { var deps = provider.deps || provider.useFactory.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); }); } else if (provider.useClass) { var deps = provider.deps || provider.useClass.diDeps; transformedDeps = deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); }); } return _transformProvider(provider, { useExisting: transformedUseExisting, useValue: transformedUseValue, deps: transformedDeps }); }); transformedProviderAst = _transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders }); this._transformedProviders.set(tokenReference(token), transformedProviderAst); return transformedProviderAst; }; NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) { if (eager === void 0) { eager = false; } var foundLocal = false; if (!dep.isSkipSelf && dep.token != null) { // access the injector if (tokenReference(dep.token) === this.reflector.resolveExternalReference(Identifiers$1.Injector) || tokenReference(dep.token) === this.reflector.resolveExternalReference(Identifiers$1.ComponentFactoryResolver)) { foundLocal = true; // access providers } else if (this._getOrCreateLocalProvider(dep.token, eager) != null) { foundLocal = true; } } return dep; }; return NgModuleProviderAnalyzer; }()); function _transformProvider(provider, _a) { var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps; return { token: provider.token, useClass: provider.useClass, useExisting: useExisting, useFactory: provider.useFactory, useValue: useValue, deps: deps, multi: provider.multi }; } function _transformProviderAst(provider, _a) { var eager = _a.eager, providers = _a.providers; return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule); } function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) { var providersByToken = new Map(); directives.forEach(function (directive) { var dirProvider = { token: { identifier: directive.type }, useClass: directive.type }; _resolveProviders([dirProvider], directive.isComponent ? exports.ProviderAstType.Component : exports.ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false); }); // Note: directives need to be able to overwrite providers of a component! var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; })); directivesWithComponentFirst.forEach(function (directive) { _resolveProviders(directive.providers, exports.ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false); _resolveProviders(directive.viewProviders, exports.ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false); }); return providersByToken; } function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) { providers.forEach(function (provider) { var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token)); if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) { targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan)); } if (!resolvedProvider) { var lifecycleHooks = provider.token.identifier && provider.token.identifier.lifecycleHooks ? provider.token.identifier.lifecycleHooks : []; var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory); resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule); targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider); } else { if (!provider.multi) { resolvedProvider.providers.length = 0; } resolvedProvider.providers.push(provider); } }); } function _getViewQueries(component) { // Note: queries start with id 1 so we can use the number in a Bloom filter! var viewQueryId = 1; var viewQueries = new Map(); if (component.viewQueries) { component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); }); } return viewQueries; } function _getContentQueries(contentQueryStartId, directives) { var contentQueryId = contentQueryStartId; var contentQueries = new Map(); directives.forEach(function (directive, directiveIndex) { if (directive.queries) { directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); }); } }); return contentQueries; } function _addQueryToTokenMap(map, query) { query.meta.selectors.forEach(function (token) { var entry = map.get(tokenReference(token)); if (!entry) { entry = []; map.set(tokenReference(token), entry); } entry.push(query); }); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var StyleWithImports = /** @class */ (function () { function StyleWithImports(style, styleUrls) { this.style = style; this.styleUrls = styleUrls; } return StyleWithImports; }()); function isStyleUrlResolvable(url) { if (url == null || url.length === 0 || url[0] == '/') return false; var schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP); return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset'; } /** * Rewrites stylesheets by resolving and removing the @import urls that * are either relative or don't have a `package:` scheme */ function extractStyleUrls(resolver, baseUrl, cssText) { var foundUrls = []; var modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '') .replace(CSS_IMPORT_REGEXP, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i] = arguments[_i]; } var url = m[1] || m[2]; if (!isStyleUrlResolvable(url)) { // Do not attempt to resolve non-package absolute URLs with URI // scheme return m[0]; } foundUrls.push(resolver.resolve(baseUrl, url)); return ''; }); return new StyleWithImports(modifiedCssText, foundUrls); } var CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g; var CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g; var URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/; var PROPERTY_PARTS_SEPARATOR = '.'; var ATTRIBUTE_PREFIX = 'attr'; var CLASS_PREFIX = 'class'; var STYLE_PREFIX = 'style'; var TEMPLATE_ATTR_PREFIX = '*'; var ANIMATE_PROP_PREFIX = 'animate-'; /** * Parses bindings in templates and in the directive host area. */ var BindingParser = /** @class */ (function () { function BindingParser(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) { this._exprParser = _exprParser; this._interpolationConfig = _interpolationConfig; this._schemaRegistry = _schemaRegistry; this.errors = errors; this.pipesByName = null; this._usedPipes = new Map(); // When the `pipes` parameter is `null`, do not check for used pipes // This is used in IVY when we might not know the available pipes at compile time if (pipes) { var pipesByName_1 = new Map(); pipes.forEach(function (pipe) { return pipesByName_1.set(pipe.name, pipe); }); this.pipesByName = pipesByName_1; } } Object.defineProperty(BindingParser.prototype, "interpolationConfig", { get: function () { return this._interpolationConfig; }, enumerable: false, configurable: true }); BindingParser.prototype.getUsedPipes = function () { return Array.from(this._usedPipes.values()); }; BindingParser.prototype.createBoundHostProperties = function (dirMeta, sourceSpan) { var _this = this; if (dirMeta.hostProperties) { var boundProps_1 = []; Object.keys(dirMeta.hostProperties).forEach(function (propName) { var expression = dirMeta.hostProperties[propName]; if (typeof expression === 'string') { _this.parsePropertyBinding(propName, expression, true, sourceSpan, sourceSpan.start.offset, undefined, [], // Use the `sourceSpan` for `keySpan`. This isn't really accurate, but neither is the // sourceSpan, as it represents the sourceSpan of the host itself rather than the // source of the host binding (which doesn't exist in the template). Regardless, // neither of these values are used in Ivy but are only here to satisfy the function // signature. This should likely be refactored in the future so that `sourceSpan` // isn't being used inaccurately. boundProps_1, sourceSpan); } else { _this._reportError("Value of the host property binding \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan); } }); return boundProps_1; } return null; }; BindingParser.prototype.createDirectiveHostPropertyAsts = function (dirMeta, elementSelector, sourceSpan) { var _this = this; var boundProps = this.createBoundHostProperties(dirMeta, sourceSpan); return boundProps && boundProps.map(function (prop) { return _this.createBoundElementProperty(elementSelector, prop); }); }; BindingParser.prototype.createDirectiveHostEventAsts = function (dirMeta, sourceSpan) { var _this = this; if (dirMeta.hostListeners) { var targetEvents_1 = []; Object.keys(dirMeta.hostListeners).forEach(function (propName) { var expression = dirMeta.hostListeners[propName]; if (typeof expression === 'string') { // Use the `sourceSpan` for `keySpan` and `handlerSpan`. This isn't really accurate, but // neither is the `sourceSpan`, as it represents the `sourceSpan` of the host itself // rather than the source of the host binding (which doesn't exist in the template). // Regardless, neither of these values are used in Ivy but are only here to satisfy the // function signature. This should likely be refactored in the future so that `sourceSpan` // isn't being used inaccurately. _this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents_1, sourceSpan); } else { _this._reportError("Value of the host listener \"" + propName + "\" needs to be a string representing an expression but got \"" + expression + "\" (" + typeof expression + ")", sourceSpan); } }); return targetEvents_1; } return null; }; BindingParser.prototype.parseInterpolation = function (value, sourceSpan) { var sourceInfo = sourceSpan.start.toString(); var absoluteOffset = sourceSpan.fullStart.offset; try { var ast = this._exprParser.parseInterpolation(value, sourceInfo, absoluteOffset, this._interpolationConfig); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }; /** * Similar to `parseInterpolation`, but treats the provided string as a single expression * element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`). * This is used for parsing the switch expression in ICUs. */ BindingParser.prototype.parseInterpolationExpression = function (expression, sourceSpan) { var sourceInfo = sourceSpan.start.toString(); var absoluteOffset = sourceSpan.start.offset; try { var ast = this._exprParser.parseInterpolationExpression(expression, sourceInfo, absoluteOffset); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }; /** * Parses the bindings in a microsyntax expression, and converts them to * `ParsedProperty` or `ParsedVariable`. * * @param tplKey template binding name * @param tplValue template binding value * @param sourceSpan span of template binding relative to entire the template * @param absoluteValueOffset start of the tplValue relative to the entire template * @param targetMatchableAttrs potential attributes to match in the template * @param targetProps target property bindings in the template * @param targetVars target variables in the template */ BindingParser.prototype.parseInlineTemplateBinding = function (tplKey, tplValue, sourceSpan, absoluteValueOffset, targetMatchableAttrs, targetProps, targetVars, isIvyAst) { var e_1, _a; var absoluteKeyOffset = sourceSpan.start.offset + TEMPLATE_ATTR_PREFIX.length; var bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset); try { for (var bindings_1 = __values(bindings), bindings_1_1 = bindings_1.next(); !bindings_1_1.done; bindings_1_1 = bindings_1.next()) { var binding = bindings_1_1.value; // sourceSpan is for the entire HTML attribute. bindingSpan is for a particular // binding within the microsyntax expression so it's more narrow than sourceSpan. var bindingSpan = moveParseSourceSpan(sourceSpan, binding.sourceSpan); var key = binding.key.source; var keySpan = moveParseSourceSpan(sourceSpan, binding.key.span); if (binding instanceof VariableBinding) { var value = binding.value ? binding.value.source : '$implicit'; var valueSpan = binding.value ? moveParseSourceSpan(sourceSpan, binding.value.span) : undefined; targetVars.push(new ParsedVariable(key, value, bindingSpan, keySpan, valueSpan)); } else if (binding.value) { var srcSpan = isIvyAst ? bindingSpan : sourceSpan; var valueSpan = moveParseSourceSpan(sourceSpan, binding.value.ast.sourceSpan); this._parsePropertyAst(key, binding.value, srcSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps); } else { targetMatchableAttrs.push([key, '' /* value */]); // Since this is a literal attribute with no RHS, source span should be // just the key span. this.parseLiteralAttr(key, null /* value */, keySpan, absoluteValueOffset, undefined /* valueSpan */, targetMatchableAttrs, targetProps, keySpan); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (bindings_1_1 && !bindings_1_1.done && (_a = bindings_1.return)) _a.call(bindings_1); } finally { if (e_1) throw e_1.error; } } }; /** * Parses the bindings in a microsyntax expression, e.g. * ``` * * ``` * * @param tplKey template binding name * @param tplValue template binding value * @param sourceSpan span of template binding relative to entire the template * @param absoluteKeyOffset start of the `tplKey` * @param absoluteValueOffset start of the `tplValue` */ BindingParser.prototype._parseTemplateBindings = function (tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset) { var _this = this; var sourceInfo = sourceSpan.start.toString(); try { var bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo, absoluteKeyOffset, absoluteValueOffset); this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan); bindingsResult.templateBindings.forEach(function (binding) { if (binding.value instanceof ASTWithSource) { _this._checkPipes(binding.value, sourceSpan); } }); bindingsResult.warnings.forEach(function (warning) { _this._reportError(warning, sourceSpan, exports.ParseErrorLevel.WARNING); }); return bindingsResult.templateBindings; } catch (e) { this._reportError("" + e, sourceSpan); return []; } }; BindingParser.prototype.parseLiteralAttr = function (name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs, // TODO(atscott): keySpan is only optional here so VE template parser implementation does not // have to change This should be required when VE is removed. targetProps, keySpan) { if (isAnimationLabel(name)) { name = name.substring(1); if (keySpan !== undefined) { keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset)); } if (value) { this._reportError("Assigning animation triggers via @prop=\"exp\" attributes with an expression is invalid." + " Use property bindings (e.g. [@prop]=\"exp\") or use an attribute without a value (e.g. @prop) instead.", sourceSpan, exports.ParseErrorLevel.ERROR); } this._parseAnimation(name, value, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps); } else { targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, '', absoluteOffset), exports.ParsedPropertyType.LITERAL_ATTR, sourceSpan, keySpan, valueSpan)); } }; BindingParser.prototype.parsePropertyBinding = function (name, expression, isHost, sourceSpan, absoluteOffset, valueSpan, // TODO(atscott): keySpan is only optional here so VE template parser implementation does not // have to change This should be required when VE is removed. targetMatchableAttrs, targetProps, keySpan) { if (name.length === 0) { this._reportError("Property name is missing in binding", sourceSpan); } var isAnimationProp = false; if (name.startsWith(ANIMATE_PROP_PREFIX)) { isAnimationProp = true; name = name.substring(ANIMATE_PROP_PREFIX.length); if (keySpan !== undefined) { keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + ANIMATE_PROP_PREFIX.length, keySpan.end.offset)); } } else if (isAnimationLabel(name)) { isAnimationProp = true; name = name.substring(1); if (keySpan !== undefined) { keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset)); } } if (isAnimationProp) { this._parseAnimation(name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps); } else { this._parsePropertyAst(name, this._parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps); } }; BindingParser.prototype.parsePropertyInterpolation = function (name, value, sourceSpan, valueSpan, targetMatchableAttrs, // TODO(atscott): keySpan is only optional here so VE template parser implementation does not // have to change This should be required when VE is removed. targetProps, keySpan) { var expr = this.parseInterpolation(value, valueSpan || sourceSpan); if (expr) { this._parsePropertyAst(name, expr, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps); return true; } return false; }; BindingParser.prototype._parsePropertyAst = function (name, ast, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps) { targetMatchableAttrs.push([name, ast.source]); targetProps.push(new ParsedProperty(name, ast, exports.ParsedPropertyType.DEFAULT, sourceSpan, keySpan, valueSpan)); }; BindingParser.prototype._parseAnimation = function (name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps) { if (name.length === 0) { this._reportError('Animation trigger is missing', sourceSpan); } // This will occur when a @trigger is not paired with an expression. // For animations it is valid to not have an expression since */void // states will be applied by angular when the element is attached/detached var ast = this._parseBinding(expression || 'undefined', false, valueSpan || sourceSpan, absoluteOffset); targetMatchableAttrs.push([name, ast.source]); targetProps.push(new ParsedProperty(name, ast, exports.ParsedPropertyType.ANIMATION, sourceSpan, keySpan, valueSpan)); }; BindingParser.prototype._parseBinding = function (value, isHostBinding, sourceSpan, absoluteOffset) { var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString(); try { var ast = isHostBinding ? this._exprParser.parseSimpleBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig) : this._exprParser.parseBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig); if (ast) this._reportExpressionParserErrors(ast.errors, sourceSpan); this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }; BindingParser.prototype.createBoundElementProperty = function (elementSelector, boundProp, skipValidation, mapPropertyName) { if (skipValidation === void 0) { skipValidation = false; } if (mapPropertyName === void 0) { mapPropertyName = true; } if (boundProp.isAnimation) { return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan); } var unit = null; var bindingType = undefined; var boundPropertyName = null; var parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR); var securityContexts = undefined; // Check for special cases (prefix style, attr, class) if (parts.length > 1) { if (parts[0] == ATTRIBUTE_PREFIX) { boundPropertyName = parts.slice(1).join(PROPERTY_PARTS_SEPARATOR); if (!skipValidation) { this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true); } securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true); var nsSeparatorIdx = boundPropertyName.indexOf(':'); if (nsSeparatorIdx > -1) { var ns = boundPropertyName.substring(0, nsSeparatorIdx); var name = boundPropertyName.substring(nsSeparatorIdx + 1); boundPropertyName = mergeNsAndName(ns, name); } bindingType = 1 /* Attribute */; } else if (parts[0] == CLASS_PREFIX) { boundPropertyName = parts[1]; bindingType = 2 /* Class */; securityContexts = [SecurityContext.NONE]; } else if (parts[0] == STYLE_PREFIX) { unit = parts.length > 2 ? parts[2] : null; boundPropertyName = parts[1]; bindingType = 3 /* Style */; securityContexts = [SecurityContext.STYLE]; } } // If not a special case, use the full property name if (boundPropertyName === null) { var mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name); boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name; securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false); bindingType = 0 /* Property */; if (!skipValidation) { this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false); } } return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan); }; // TODO: keySpan should be required but was made optional to avoid changing VE parser. BindingParser.prototype.parseEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) { if (name.length === 0) { this._reportError("Event name is missing in binding", sourceSpan); } if (isAnimationLabel(name)) { name = name.substr(1); if (keySpan !== undefined) { keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset)); } this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan); } else { this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan); } }; BindingParser.prototype.calcPossibleSecurityContexts = function (selector, propName, isAttribute) { var prop = this._schemaRegistry.getMappedPropName(propName); return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute); }; BindingParser.prototype._parseAnimationEvent = function (name, expression, sourceSpan, handlerSpan, targetEvents, keySpan) { var matches = splitAtPeriod(name, [name, '']); var eventName = matches[0]; var phase = matches[1].toLowerCase(); var ast = this._parseAction(expression, handlerSpan); targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan, keySpan)); if (eventName.length === 0) { this._reportError("Animation event name is missing in binding", sourceSpan); } if (phase) { if (phase !== 'start' && phase !== 'done') { this._reportError("The provided animation output phase value \"" + phase + "\" for \"@" + eventName + "\" is not supported (use start or done)", sourceSpan); } } else { this._reportError("The animation trigger output event (@" + eventName + ") is missing its phase value name (start or done are currently supported)", sourceSpan); } }; BindingParser.prototype._parseRegularEvent = function (name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) { // long format: 'target: eventName' var _a = __read(splitAtColon(name, [null, name]), 2), target = _a[0], eventName = _a[1]; var ast = this._parseAction(expression, handlerSpan); targetMatchableAttrs.push([name, ast.source]); targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan, keySpan)); // Don't detect directives for event names for now, // so don't add the event name to the matchableAttrs }; BindingParser.prototype._parseAction = function (value, sourceSpan) { var sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString(); var absoluteOffset = (sourceSpan && sourceSpan.start) ? sourceSpan.start.offset : 0; try { var ast = this._exprParser.parseAction(value, sourceInfo, absoluteOffset, this._interpolationConfig); if (ast) { this._reportExpressionParserErrors(ast.errors, sourceSpan); } if (!ast || ast.ast instanceof EmptyExpr) { this._reportError("Empty expressions are not allowed", sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } this._checkPipes(ast, sourceSpan); return ast; } catch (e) { this._reportError("" + e, sourceSpan); return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset); } }; BindingParser.prototype._reportError = function (message, sourceSpan, level) { if (level === void 0) { level = exports.ParseErrorLevel.ERROR; } this.errors.push(new ParseError(sourceSpan, message, level)); }; BindingParser.prototype._reportExpressionParserErrors = function (errors, sourceSpan) { var e_2, _a; try { for (var errors_1 = __values(errors), errors_1_1 = errors_1.next(); !errors_1_1.done; errors_1_1 = errors_1.next()) { var error = errors_1_1.value; this._reportError(error.message, sourceSpan); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (errors_1_1 && !errors_1_1.done && (_a = errors_1.return)) _a.call(errors_1); } finally { if (e_2) throw e_2.error; } } }; // Make sure all the used pipes are known in `this.pipesByName` BindingParser.prototype._checkPipes = function (ast, sourceSpan) { var _this = this; if (ast && this.pipesByName) { var collector = new PipeCollector(); ast.visit(collector); collector.pipes.forEach(function (ast, pipeName) { var pipeMeta = _this.pipesByName.get(pipeName); if (!pipeMeta) { _this._reportError("The pipe '" + pipeName + "' could not be found", new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end))); } else { _this._usedPipes.set(pipeName, pipeMeta); } }); } }; /** * @param propName the name of the property / attribute * @param sourceSpan * @param isAttr true when binding to an attribute */ BindingParser.prototype._validatePropertyOrAttributeName = function (propName, sourceSpan, isAttr) { var report = isAttr ? this._schemaRegistry.validateAttribute(propName) : this._schemaRegistry.validateProperty(propName); if (report.error) { this._reportError(report.msg, sourceSpan, exports.ParseErrorLevel.ERROR); } }; return BindingParser; }()); var PipeCollector = /** @class */ (function (_super) { __extends(PipeCollector, _super); function PipeCollector() { var _this = _super.apply(this, __spreadArray([], __read(arguments))) || this; _this.pipes = new Map(); return _this; } PipeCollector.prototype.visitPipe = function (ast, context) { this.pipes.set(ast.name, ast); ast.exp.visit(this); this.visitAll(ast.args, context); return null; }; return PipeCollector; }(RecursiveAstVisitor$1)); function isAnimationLabel(name) { return name[0] == '@'; } function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) { var ctxs = []; CssSelector.parse(selector).forEach(function (selector) { var elementNames = selector.element ? [selector.element] : registry.allKnownElementNames(); var notElementNames = new Set(selector.notSelectors.filter(function (selector) { return selector.isElementSelector(); }) .map(function (selector) { return selector.element; })); var possibleElementNames = elementNames.filter(function (elementName) { return !notElementNames.has(elementName); }); ctxs.push.apply(ctxs, __spreadArray([], __read(possibleElementNames.map(function (elementName) { return registry.securityContext(elementName, propName, isAttribute); })))); }); return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort(); } /** * Compute a new ParseSourceSpan based off an original `sourceSpan` by using * absolute offsets from the specified `absoluteSpan`. * * @param sourceSpan original source span * @param absoluteSpan absolute source span to move to */ function moveParseSourceSpan(sourceSpan, absoluteSpan) { // The difference of two absolute offsets provide the relative offset var startDiff = absoluteSpan.start - sourceSpan.start.offset; var endDiff = absoluteSpan.end - sourceSpan.end.offset; return new ParseSourceSpan(sourceSpan.start.moveBy(startDiff), sourceSpan.end.moveBy(endDiff), sourceSpan.fullStart.moveBy(startDiff), sourceSpan.details); } /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var NG_CONTENT_SELECT_ATTR = 'select'; var LINK_ELEMENT = 'link'; var LINK_STYLE_REL_ATTR = 'rel'; var LINK_STYLE_HREF_ATTR = 'href'; var LINK_STYLE_REL_VALUE = 'stylesheet'; var STYLE_ELEMENT = 'style'; var SCRIPT_ELEMENT = 'script'; var NG_NON_BINDABLE_ATTR = 'ngNonBindable'; var NG_PROJECT_AS = 'ngProjectAs'; function preparseElement(ast) { var selectAttr = null; var hrefAttr = null; var relAttr = null; var nonBindable = false; var projectAs = ''; ast.attrs.forEach(function (attr) { var lcAttrName = attr.name.toLowerCase(); if (lcAttrName == NG_CONTENT_SELECT_ATTR) { selectAttr = attr.value; } else if (lcAttrName == LINK_STYLE_HREF_ATTR) { hrefAttr = attr.value; } else if (lcAttrName == LINK_STYLE_REL_ATTR) { relAttr = attr.value; } else if (attr.name == NG_NON_BINDABLE_ATTR) { nonBindable = true; } else if (attr.name == NG_PROJECT_AS) { if (attr.value.length > 0) { projectAs = attr.value; } } }); selectAttr = normalizeNgContentSelect(selectAttr); var nodeName = ast.name.toLowerCase(); var type = PreparsedElementType.OTHER; if (isNgContent(nodeName)) { type = PreparsedElementType.NG_CONTENT; } else if (nodeName == STYLE_ELEMENT) { type = PreparsedElementType.STYLE; } else if (nodeName == SCRIPT_ELEMENT) { type = PreparsedElementType.SCRIPT; } else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) { type = PreparsedElementType.STYLESHEET; } return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs); } var PreparsedElementType; (function (PreparsedElementType) { PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT"; PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE"; PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET"; PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT"; PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER"; })(PreparsedElementType || (PreparsedElementType = {})); var PreparsedElement = /** @class */ (function () { function PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs) { this.type = type; this.selectAttr = selectAttr; this.hrefAttr = hrefAttr; this.nonBindable = nonBindable; this.projectAs = projectAs; } return PreparsedElement; }()); function normalizeNgContentSelect(selectAttr) { if (selectAttr === null || selectAttr.length === 0) { return '*'; } return selectAttr; } var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/; // Group 1 = "bind-" var KW_BIND_IDX = 1; // Group 2 = "let-" var KW_LET_IDX = 2; // Group 3 = "ref-/#" var KW_REF_IDX = 3; // Group 4 = "on-" var KW_ON_IDX = 4; // Group 5 = "bindon-" var KW_BINDON_IDX = 5; // Group 6 = "@" var KW_AT_IDX = 6; // Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@" var IDENT_KW_IDX = 7; // Group 8 = identifier inside [()] var IDENT_BANANA_BOX_IDX = 8; // Group 9 = identifier inside [] var IDENT_PROPERTY_IDX = 9; // Group 10 = identifier inside () var IDENT_EVENT_IDX = 10; var TEMPLATE_ATTR_PREFIX$1 = '*'; var CLASS_ATTR = 'class'; var _TEXT_CSS_SELECTOR; function TEXT_CSS_SELECTOR() { if (!_TEXT_CSS_SELECTOR) { _TEXT_CSS_SELECTOR = CssSelector.parse('*')[0]; } return _TEXT_CSS_SELECTOR; } var TemplateParseError = /** @class */ (function (_super) { __extends(TemplateParseError, _super); function TemplateParseError(message, span, level) { return _super.call(this, span, message, level) || this; } return TemplateParseError; }(ParseError)); var TemplateParseResult = /** @class */ (function () { function TemplateParseResult(templateAst, usedPipes, errors) { this.templateAst = templateAst; this.usedPipes = usedPipes; this.errors = errors; } return TemplateParseResult; }()); var TemplateParser = /** @class */ (function () { function TemplateParser(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) { this._config = _config; this._reflector = _reflector; this._exprParser = _exprParser; this._schemaRegistry = _schemaRegistry; this._htmlParser = _htmlParser; this._console = _console; this.transforms = transforms; } Object.defineProperty(TemplateParser.prototype, "expressionParser", { get: function () { return this._exprParser; }, enumerable: false, configurable: true }); TemplateParser.prototype.parse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) { var _a; var result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces); var warnings = result.errors.filter(function (error) { return error.level === exports.ParseErrorLevel.WARNING; }); var errors = result.errors.filter(function (error) { return error.level === exports.ParseErrorLevel.ERROR; }); if (warnings.length > 0) { (_a = this._console) === null || _a === void 0 ? void 0 : _a.warn("Template parse warnings:\n" + warnings.join('\n')); } if (errors.length > 0) { var errorString = errors.join('\n'); throw syntaxError("Template parse errors:\n" + errorString, errors); } return { template: result.templateAst, pipes: result.usedPipes }; }; TemplateParser.prototype.tryParse = function (component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) { var htmlParseResult = typeof template === 'string' ? this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig: this.getInterpolationConfig(component) }) : template; if (!preserveWhitespaces) { htmlParseResult = removeWhitespaces(htmlParseResult); } return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas); }; TemplateParser.prototype.tryParseHtml = function (htmlAstWithErrors, component, directives, pipes, schemas) { var result; var errors = htmlAstWithErrors.errors; var usedPipes = []; if (htmlAstWithErrors.rootNodes.length > 0) { var uniqDirectives = removeSummaryDuplicates(directives); var uniqPipes = removeSummaryDuplicates(pipes); var providerViewContext = new ProviderViewContext(this._reflector, component); var interpolationConfig = undefined; if (component.template && component.template.interpolation) { interpolationConfig = { start: component.template.interpolation[0], end: component.template.interpolation[1] }; } var bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors); var parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors); result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT); errors.push.apply(errors, __spreadArray([], __read(providerViewContext.errors))); usedPipes.push.apply(usedPipes, __spreadArray([], __read(bindingParser.getUsedPipes()))); } else { result = []; } this._assertNoReferenceDuplicationOnTemplate(result, errors); if (errors.length > 0) { return new TemplateParseResult(result, usedPipes, errors); } if (this.transforms) { this.transforms.forEach(function (transform) { result = templateVisitAll(transform, result); }); } return new TemplateParseResult(result, usedPipes, errors); }; TemplateParser.prototype.expandHtml = function (htmlAstWithErrors, forced) { if (forced === void 0) { forced = false; } var errors = htmlAstWithErrors.errors; if (errors.length == 0 || forced) { // Transform ICU messages to angular directives var expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes); errors.push.apply(errors, __spreadArray([], __read(expandedHtmlAst.errors))); htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors); } return htmlAstWithErrors; }; TemplateParser.prototype.getInterpolationConfig = function (component) { if (component.template) { return InterpolationConfig.fromArray(component.template.interpolation); } return undefined; }; /** @internal */ TemplateParser.prototype._assertNoReferenceDuplicationOnTemplate = function (result, errors) { var existingReferences = []; result.filter(function (element) { return !!element.references; }) .forEach(function (element) { return element.references.forEach(function (reference) { var name = reference.name; if (existingReferences.indexOf(name) < 0) { existingReferences.push(name); } else { var error = new TemplateParseError("Reference \"#" + name + "\" is defined several times", reference.sourceSpan, exports.ParseErrorLevel.ERROR); errors.push(error); } }); }); }; return TemplateParser; }()); var TemplateParseVisitor = /** @class */ (function () { function TemplateParseVisitor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) { var _this = this; this.reflector = reflector; this.config = config; this.providerViewContext = providerViewContext; this._bindingParser = _bindingParser; this._schemaRegistry = _schemaRegistry; this._schemas = _schemas; this._targetErrors = _targetErrors; this.selectorMatcher = new SelectorMatcher(); this.directivesIndex = new Map(); this.ngContentCount = 0; // Note: queries start with id 1 so we can use the number in a Bloom filter! this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1; directives.forEach(function (directive, index) { var selector = CssSelector.parse(directive.selector); _this.selectorMatcher.addSelectables(selector, directive); _this.directivesIndex.set(directive, index); }); } TemplateParseVisitor.prototype.visitExpansion = function (expansion, context) { return null; }; TemplateParseVisitor.prototype.visitExpansionCase = function (expansionCase, context) { return null; }; TemplateParseVisitor.prototype.visitText = function (text, parent) { var ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR()); var valueNoNgsp = replaceNgsp(text.value); var expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan); return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) : new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan); }; TemplateParseVisitor.prototype.visitAttribute = function (attribute, context) { return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan); }; TemplateParseVisitor.prototype.visitComment = function (comment, context) { return null; }; TemplateParseVisitor.prototype.visitElement = function (element, parent) { var _this = this; var queryStartIndex = this.contentQueryStartId; var elName = element.name; var preparsedElement = preparseElement(element); if (preparsedElement.type === PreparsedElementType.SCRIPT || preparsedElement.type === PreparsedElementType.STYLE) { // Skipping