diff --git a/.github/.htaccess b/.github/.htaccess new file mode 100644 index 0000000000000..707c26b075e16 --- /dev/null +++ b/.github/.htaccess @@ -0,0 +1,8 @@ + + order allow,deny + deny from all + += 2.4> + Require all denied + + diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000..4e82725a7fb08 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at engcom@magento.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/.github/CONTRIBUTING.md similarity index 100% rename from CONTRIBUTING.md rename to .github/CONTRIBUTING.md diff --git a/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md similarity index 100% rename from ISSUE_TEMPLATE.md rename to .github/ISSUE_TEMPLATE.md diff --git a/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md similarity index 100% rename from PULL_REQUEST_TEMPLATE.md rename to .github/PULL_REQUEST_TEMPLATE.md diff --git a/.htaccess b/.htaccess index 90b9c16a5a8c0..4298b10d9ca7a 100644 --- a/.htaccess +++ b/.htaccess @@ -36,7 +36,7 @@ ############################################ ## adjust memory limit - php_value memory_limit 768M + php_value memory_limit 756M php_value max_execution_time 18000 ############################################ @@ -59,7 +59,7 @@ ############################################ ## adjust memory limit - php_value memory_limit 768M + php_value memory_limit 756M php_value max_execution_time 18000 ############################################ @@ -203,76 +203,166 @@ RedirectMatch 403 /\.git - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all - - - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + + + + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + # For 404s and 403s that aren't handled by the application, show plain 404 response diff --git a/.htaccess.sample b/.htaccess.sample index 3b61bb672ec8a..a521a347232f5 100644 --- a/.htaccess.sample +++ b/.htaccess.sample @@ -35,7 +35,7 @@ ############################################ ## adjust memory limit - php_value memory_limit 768M + php_value memory_limit 756M php_value max_execution_time 18000 ############################################ @@ -111,7 +111,8 @@ ############################################ ## enable rewrites - Options +FollowSymLinks + # The following line has better security but add some performance overhead - see https://httpd.apache.org/docs/2.4/en/misc/perf-tuning.html + Options -FollowSymLinks +SymLinksIfOwnerMatch RewriteEngine on ############################################ @@ -179,76 +180,166 @@ RedirectMatch 403 /\.git - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all - - - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + + + + + order allow,deny + deny from all + + = 2.4> + Require all denied + - order allow,deny - deny from all + + order allow,deny + deny from all + + = 2.4> + Require all denied + # For 404s and 403s that aren't handled by the application, show plain 404 response diff --git a/.php_cs.dist b/.php_cs.dist index 0f254c63283bd..87483d5b33a15 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -4,10 +4,6 @@ * See COPYING.txt for license details. */ -/** - * Pre-commit hook installation: - * vendor/bin/static-review.php hook:install dev/tools/Magento/Tools/StaticReview/pre-commit .git/hooks/pre-commit - */ $finder = PhpCsFixer\Finder::create() ->name('*.phtml') ->exclude('dev/tests/functional/generated') diff --git a/.user.ini b/.user.ini index 8c0b765e0551c..bfc3a86d88e20 100644 --- a/.user.ini +++ b/.user.ini @@ -1,4 +1,4 @@ -memory_limit = 768M +memory_limit = 756M max_execution_time = 18000 session.auto_start = off suhosin.session.cryptua = off \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ef841ec0337f2..a5e94e46f89d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,919 @@ +2.2.2 +============= +* GitHub issues: + * [#9968](https://github.com/magento/magento2/issues/9968) -- Canceled invoice can be canceled again (fixed in [#11261](https://github.com/magento/magento2/pull/11261)) + * [#11310](https://github.com/magento/magento2/issues/11310) -- Method "getChildren" sort ordering (fixed in [#11342](https://github.com/magento/magento2/pull/11342)) + * [#11332](https://github.com/magento/magento2/issues/11332) -- How to Fix the wrong input format of Customer date of birth (fixed in [#11351](https://github.com/magento/magento2/pull/11351)) + * [#11207](https://github.com/magento/magento2/issues/11207) -- Shipment API won't append comment to email (fixed in [#11383](https://github.com/magento/magento2/pull/11383)) + * [#10795](https://github.com/magento/magento2/issues/10795) -- Shipping method radios have duplicate IDs on cart page (fixed in [#11406](https://github.com/magento/magento2/pull/11406)) + * [#10941](https://github.com/magento/magento2/issues/10941) -- Responsive Design Issue on Mobile with Magento 2.1.9 (fixed in [#11430](https://github.com/magento/magento2/pull/11430)) + * [#10007](https://github.com/magento/magento2/issues/10007) -- ProductAlert: Product alerts not showing in admin side product edit page (fixed in [#11445](https://github.com/magento/magento2/pull/11445)) + * [#10231](https://github.com/magento/magento2/issues/10231) -- Custom URL Rewrite Not working (fixed in [#11470](https://github.com/magento/magento2/pull/11470)) + * [#11176](https://github.com/magento/magento2/issues/11176) -- Configured table prefix is not recognized in CLI admin:user:create (fixed in [#11199](https://github.com/magento/magento2/pull/11199)) + * [#11275](https://github.com/magento/magento2/issues/11275) -- Call to a member function addCrumb() (fixed in [#11299](https://github.com/magento/magento2/pull/11299)) + * [#10441](https://github.com/magento/magento2/issues/10441) -- State/Province Not displayed after edit Billing Address on Sales Orders - Backend Admin. (fixed in [#11381](https://github.com/magento/magento2/pull/11381)) + * [#11140](https://github.com/magento/magento2/issues/11140) -- Going to '/admin' while using storecodes in url and a different adminhtml url will throw exception (fixed in [#11460](https://github.com/magento/magento2/pull/11460)) + * [#10765](https://github.com/magento/magento2/issues/10765) -- Export data from grid not adding custom rendered data magento2 (fixed in [#11437](https://github.com/magento/magento2/pull/11437)) + * [#7678](https://github.com/magento/magento2/issues/7678) -- StockItemCriteria::setProductsFilter doesn't work with array of ids (fixed in [#11500](https://github.com/magento/magento2/pull/11500)) + * [#9783](https://github.com/magento/magento2/issues/9783) -- Multiple parameters in widget.xml not allowed (fixed in [#11495](https://github.com/magento/magento2/pull/11495)) + * [#10824](https://github.com/magento/magento2/issues/10824) -- Cannot add new columns to item grid in admin sales_order_view layout (fixed in [#11235](https://github.com/magento/magento2/pull/11235)) + * [#9919](https://github.com/magento/magento2/issues/9919) -- Pattern Validation via UI Component Fails to Interpret String as RegEx Pattern (fixed in [#11565](https://github.com/magento/magento2/pull/11565)) + * [#5439](https://github.com/magento/magento2/issues/5439) -- Newsletter subscription (fixed in [#11317](https://github.com/magento/magento2/pull/11317)) + * [#10856](https://github.com/magento/magento2/issues/10856) -- Sync billing with shipping address on Admin Reorder and Admin Customer Create Order page does not work for Existing address selected (fixed in [#11385](https://github.com/magento/magento2/pull/11385)) + * [#10025](https://github.com/magento/magento2/issues/10025) -- Integration tests don't reset the database (fixed in [#11499](https://github.com/magento/magento2/pull/11499)) + * [#10301](https://github.com/magento/magento2/issues/10301) -- Customer review report search Bug in 2.1.x, 2.2 (fixed in [#11522](https://github.com/magento/magento2/pull/11522)) + * [#11540](https://github.com/magento/magento2/issues/11540) -- Magento sets iso invalid language code in html header (fixed in [#11561](https://github.com/magento/magento2/pull/11561)) + * [#11586](https://github.com/magento/magento2/issues/11586) -- Cron install / remove via command messes up stderr 2>&1 entries (fixed in [#11591](https://github.com/magento/magento2/pull/11591)) + * [#6350](https://github.com/magento/magento2/issues/6350) -- Frontend: Datepicker/calendar control does not use the store locale (fixed in [#11057](https://github.com/magento/magento2/pull/11057)) + * [#11328](https://github.com/magento/magento2/issues/11328) -- app:config:dump adds extra space every time in multiline array value (fixed in [#11439](https://github.com/magento/magento2/pull/11439)) + * [#7591](https://github.com/magento/magento2/issues/7591) -- PayPal module, "didgit" misspelling (fixed in [#11673](https://github.com/magento/magento2/pull/11673)) + * [#7767](https://github.com/magento/magento2/issues/7767) -- in system.xml translate phrase not work (fixed in [#11675](https://github.com/magento/magento2/pull/11675)) + * [#7915](https://github.com/magento/magento2/issues/7915) -- customer objects are equal to eachother after observing event customer_save_after_data_object (fixed in [#11676](https://github.com/magento/magento2/pull/11676)) + * [#10275](https://github.com/magento/magento2/issues/10275) -- Admin global search - submit by enter doesn't work (fixed in [#11250](https://github.com/magento/magento2/pull/11250)) + * [#11022](https://github.com/magento/magento2/issues/11022) -- GET v1/products/attribute-sets/sets/list inconsistent return result (fixed in [#11421](https://github.com/magento/magento2/pull/11421)) + * [#5956](https://github.com/magento/magento2/issues/5956) -- Untranslatable string "Please enter the same value again." (fixed in [#11440](https://github.com/magento/magento2/pull/11440)) + * [#9944](https://github.com/magento/magento2/issues/9944) -- Name attribute shows empty when creating custom fields on product creation form (fixed in [#11637](https://github.com/magento/magento2/pull/11637)) + * [#10168](https://github.com/magento/magento2/issues/10168) -- Coupon codes not showing in invoice (fixed in [#11635](https://github.com/magento/magento2/pull/11635)) + * [#9763](https://github.com/magento/magento2/issues/9763) -- When go checkout,Cart Price Rules 25%test coupon code can go wrong (fixed in [#11710](https://github.com/magento/magento2/pull/11710)) + * [#11157](https://github.com/magento/magento2/issues/11157) -- nginx.sample.conf missing heath_check.php? (fixed in [#11690](https://github.com/magento/magento2/pull/11690)) + * [#11322](https://github.com/magento/magento2/issues/11322) -- User.ini files specify 768M - Docs recommend at least 1G (fixed in [#11734](https://github.com/magento/magento2/pull/11734)) + * [#7927](https://github.com/magento/magento2/issues/7927) -- Dashboard graph has broken y-axis range (fixed in [#11751](https://github.com/magento/magento2/pull/11751)) + * [#7099](https://github.com/magento/magento2/issues/7099) -- Admin: field labels wrapping poorly (fixed in [#11745](https://github.com/magento/magento2/pull/11745)) + * [#9869](https://github.com/magento/magento2/issues/9869) -- datetime type product attribute showing current date (fixed in [#11749](https://github.com/magento/magento2/pull/11749)) + * [#11365](https://github.com/magento/magento2/issues/11365) -- "Ignore this notification" isn't working (fixed in [#11410](https://github.com/magento/magento2/pull/11410)) + * [#6891](https://github.com/magento/magento2/issues/6891) -- Add-to-cart checkbox still visible when $canItemsAddToCart = false (fixed in [#11610](https://github.com/magento/magento2/pull/11610)) + * [#11729](https://github.com/magento/magento2/issues/11729) -- Exported Excel with negative number can't be opened by MS Office (fixed in [#11757](https://github.com/magento/magento2/pull/11757)) + * [#6924](https://github.com/magento/magento2/issues/6924) -- Magento 2.1.0 - "General system exception happened" on Import .csv (fixed in [#11363](https://github.com/magento/magento2/pull/11363)) + * [#7640](https://github.com/magento/magento2/issues/7640) -- X-Magento-Tags header containing whitespaces causes exception (fixed in [#11767](https://github.com/magento/magento2/pull/11767)) + * [#4711](https://github.com/magento/magento2/issues/4711) -- Improve error reporting for products images import (fixed in [#11779](https://github.com/magento/magento2/pull/11779)) + * [#4696](https://github.com/magento/magento2/issues/4696) -- Admin product search - Pressing enter does not submit (fixed in [#11827](https://github.com/magento/magento2/pull/11827)) + * [#11581](https://github.com/magento/magento2/issues/11581) -- Reference to wrong / non-existing class (fixed in [#11830](https://github.com/magento/magento2/pull/11830)) + * [#10908](https://github.com/magento/magento2/issues/10908) -- [2.2.0-rc3.0] Language switcher is broken when using multiple times (fixed in [#11337](https://github.com/magento/magento2/pull/11337)) + * [#11211](https://github.com/magento/magento2/issues/11211) -- Store View switcher not working on front-end and it throws an error (fixed in [#11337](https://github.com/magento/magento2/pull/11337)) + * [#2991](https://github.com/magento/magento2/issues/2991) -- Products added to cart with REST API give total prices equal to zero (fixed in [#11458](https://github.com/magento/magento2/pull/11458)) + * [#10032](https://github.com/magento/magento2/issues/10032) -- Download back-up .tgz always takes the latest that's created (fixed in [#11595](https://github.com/magento/magento2/pull/11595)) + * [#11534](https://github.com/magento/magento2/issues/11534) -- Values of Visual Swatch Attribute drop down is not work correct (fixed in [#11747](https://github.com/magento/magento2/pull/11747)) + * [#10291](https://github.com/magento/magento2/issues/10291) -- Magento 2 Loading custom option dropdown issue (fixed in [#11824](https://github.com/magento/magento2/pull/11824)) + * [#11095](https://github.com/magento/magento2/issues/11095) -- Magento_Tax "postcode is a required field" when upgrading from 2.1.9 to 2.2 (fixed in [#11651](https://github.com/magento/magento2/pull/11651)) + * [#8236](https://github.com/magento/magento2/issues/8236) -- CMS blocks are not validated against having same store and identifier (fixed in [#11802](https://github.com/magento/magento2/pull/11802)) + * [#4808](https://github.com/magento/magento2/issues/4808) -- The price of product custom option can't be set to 0. (fixed in [#11843](https://github.com/magento/magento2/pull/11843)) + * [#9566](https://github.com/magento/magento2/issues/9566) -- Status label is wrong in admin (fixed in [#11397](https://github.com/magento/magento2/pull/11397)) + * [#5015](https://github.com/magento/magento2/issues/5015) -- Report error csv doesn't work when trying to import a csv file with semicolon delimiter (fixed in [#11732](https://github.com/magento/magento2/pull/11732)) + * [#10682](https://github.com/magento/magento2/issues/10682) -- Meta description and keywords transform to html entities for non latin/cyrilic characters in category and product pages (fixed in [#11829](https://github.com/magento/magento2/pull/11829)) + * [#10185](https://github.com/magento/magento2/issues/10185) -- New Orders are not in Order grid after data migration from M 1.7.0.2 to M 2.1.7 (fixed in [#11911](https://github.com/magento/magento2/pull/11911)) + * [#8970](https://github.com/magento/magento2/issues/8970) -- Cannot assign products to categories not under tree root (fixed in [#11817](https://github.com/magento/magento2/pull/11817)) + * [#9028](https://github.com/magento/magento2/issues/9028) -- You cannot set a 303 redirect response using a result factory (fixed in [#11405](https://github.com/magento/magento2/pull/11405)) + * [#11697](https://github.com/magento/magento2/issues/11697) -- Theme: Added html node to page xml root, cause validation error (fixed in [#11858](https://github.com/magento/magento2/pull/11858)) + * [#8954](https://github.com/magento/magento2/issues/8954) -- Error While Trying To Load Quote Item Collection Using Magento\Quote\Model\ResourceModel\QuoteItem\Collection::getItems() (fixed in [#11869](https://github.com/magento/magento2/pull/11869)) + * [#8799](https://github.com/magento/magento2/issues/8799) -- Image brackground (fixed in [#11889](https://github.com/magento/magento2/pull/11889)) + * [#11868](https://github.com/magento/magento2/issues/11868) -- "Add Products" button has been duplicated after the customer group was changed (fixed in [#11949](https://github.com/magento/magento2/pull/11949)) + * [#11898](https://github.com/magento/magento2/issues/11898) -- Zip code Netherlands should allow zipcode without space (fixed in [#11959](https://github.com/magento/magento2/pull/11959)) + * [#11996](https://github.com/magento/magento2/issues/11996) -- Magento 2 Store Code validation regex: doesn't support uppercase letters in store code (fixed in [#12011](https://github.com/magento/magento2/pull/12011)) + * [#7995](https://github.com/magento/magento2/issues/7995) -- If you leave as default, shipping lines disappear (fixed in [#12013](https://github.com/magento/magento2/pull/12013)) + * [#8846](https://github.com/magento/magento2/issues/8846) -- Attribute option value uniqueness is not checked if created via REST Api (fixed in [#11785](https://github.com/magento/magento2/pull/11785)) + * [#11700](https://github.com/magento/magento2/issues/11700) -- "Something Went Wrong" error for limited access admin user (fixed in [#11993](https://github.com/magento/magento2/pull/11993)) + * [#12017](https://github.com/magento/magento2/issues/12017) -- Cross-sell product placeholder image size issue (fixed in [#12018](https://github.com/magento/magento2/pull/12018)) + * [#10583](https://github.com/magento/magento2/issues/10583) -- Checkout place order exception when using a new address (fixed in [#11556](https://github.com/magento/magento2/pull/11556)) + * [#4004](https://github.com/magento/magento2/issues/4004) -- Newsletter Subscriber create-date not set, and change_status_at broken (fixed in [#11879](https://github.com/magento/magento2/pull/11879)) + * [#7225](https://github.com/magento/magento2/issues/7225) -- [BUG] [Magento 2.1.2] Programmatically creating an empty dropdown attribute, "apply_to" is set to NULL (from "simple") after adding options through store admin (fixed in [#11588](https://github.com/magento/magento2/pull/11588)) + * [#11197](https://github.com/magento/magento2/issues/11197) -- Blank page at the checkout 'shipping' step (fixed in [#11958](https://github.com/magento/magento2/pull/11958)) + * [#11880](https://github.com/magento/magento2/issues/11880) -- Magento 2.1.9 Configurable::getUsedProducts returns a different array after product collections is cached (fixed in [#12107](https://github.com/magento/magento2/pull/12107)) + * [#10811](https://github.com/magento/magento2/issues/10811) -- Replace FollowSymLinks with SymLinksIfOwnerMatch (fixed in [#11461](https://github.com/magento/magento2/pull/11461)) + * [#10920](https://github.com/magento/magento2/issues/10920) -- Sku => Entity_id relations are fetched inefficiently when inserting attributes values during product import (fixed in [#11719](https://github.com/magento/magento2/pull/11719)) + * [#6802](https://github.com/magento/magento2/issues/6802) -- Magento\Search\Helper\getSuggestUrl() not used in search template (fixed in [#11722](https://github.com/magento/magento2/pull/11722)) + * [#9151](https://github.com/magento/magento2/issues/9151) -- Sitemap.xml: lastmod timestamp can contain invalid dates (fixed in [#11902](https://github.com/magento/magento2/pull/11902)) + * [#10195](https://github.com/magento/magento2/issues/10195) -- Order relation child is not set during edit operation. (fixed in [#11988](https://github.com/magento/magento2/pull/11988)) + * [#11793](https://github.com/magento/magento2/issues/11793) -- Magento2.1.5 admin shipping report shows wrong currency code (fixed in [#11962](https://github.com/magento/magento2/pull/11962)) + * [#6661](https://github.com/magento/magento2/issues/6661) -- XHTML templates Don't Use Schema URNs (fixed in [#12031](https://github.com/magento/magento2/pull/12031)) + * [#12079](https://github.com/magento/magento2/issues/12079) -- Products in cart report error when we have grouped or bundle product (fixed in [#12082](https://github.com/magento/magento2/pull/12082)) + * [#9768](https://github.com/magento/magento2/issues/9768) -- Admin dashboard Most Viewed Products Tab only gives default attribute set's products (fixed in [#12139](https://github.com/magento/magento2/pull/12139)) + * [#6238](https://github.com/magento/magento2/issues/6238) -- Meta description allows too many characters (fixed in [#11914](https://github.com/magento/magento2/pull/11914)) + * [#11230](https://github.com/magento/magento2/issues/11230) -- Unit test fails after fresh installation (fixed in [#12144](https://github.com/magento/magento2/pull/12144)) + * [#10810](https://github.com/magento/magento2/issues/10810) -- Add support of apache2.4 commands in htaccess (fixed in [#11459](https://github.com/magento/magento2/pull/11459)) + * [#10834](https://github.com/magento/magento2/issues/10834) -- signing in after selecting checkout button, will not end up to checkout page! (fixed in [#11876](https://github.com/magento/magento2/pull/11876)) + * [#10477](https://github.com/magento/magento2/issues/10477) -- Cart price rule has failed if use dropdown attribute (fixed in [#11274](https://github.com/magento/magento2/pull/11274)) + * [#11832](https://github.com/magento/magento2/issues/11832) -- Create order (on Customer edit page) - not working from admin environment (fixed in [#11952](https://github.com/magento/magento2/pull/11952)) + * [#10014](https://github.com/magento/magento2/issues/10014) -- Newsletter subscriptions status not isolated between multi stores (fixed in [#12035](https://github.com/magento/magento2/pull/12035)) + * [#11532](https://github.com/magento/magento2/issues/11532) -- Duplicate Simple Product Throws Error: Undefined offset: 0 in SaveHandler.php on line 122 (fixed in [#12001](https://github.com/magento/magento2/pull/12001)) + * [#10628](https://github.com/magento/magento2/issues/10628) -- Color attribute swatches are not visible if sorting is enabled (fixed in [#12077](https://github.com/magento/magento2/pull/12077)) + * [#8022](https://github.com/magento/magento2/issues/8022) -- Uncaught Error: Call to a member function addItem() on array in app/code/Magento/Sales/Model/Order/Shipment.php (fixed in [#12173](https://github.com/magento/magento2/pull/12173)) +* GitHub pull requests: + * [#11240](https://github.com/magento/magento2/pull/11240) -- Virtual Theme load: Check for null to actually reach the code that handles this case to t… (by @leptoquark1) + * [#11261](https://github.com/magento/magento2/pull/11261) -- Prevent invoice cancelation multiple times 2.2-develop [Backport] (by @osrecio) + * [#11342](https://github.com/magento/magento2/pull/11342) -- ADDED $sortByPostion flag to getChildren() (by @denisristic) + * [#11351](https://github.com/magento/magento2/pull/11351) -- Fix the wrong input format of Customer date of birth (by @manuelson) + * [#11359](https://github.com/magento/magento2/pull/11359) -- [Backport 2.2-develop] Unable to manage (install/uninstall) cron via bin/magento cron:install / cron:remove with multiple installations against same crontab (by @adrian-martinez-interactiv4) + * [#11383](https://github.com/magento/magento2/pull/11383) -- Append shipment comment to shipment if appendComment is true (by @JeroenVanLeusden) + * [#11406](https://github.com/magento/magento2/pull/11406) -- Added carrier code to ID to distinguish shipping methods (by @peterjaap) + * [#11430](https://github.com/magento/magento2/pull/11430) -- Fix toolbar-amount placing in mobile device (by @slackerzz) + * [#11445](https://github.com/magento/magento2/pull/11445) -- Show product alerts in admin product detail [backport 2.2] (by @raumatbel) + * [#11470](https://github.com/magento/magento2/pull/11470) -- FR#10231_22 Custom URL Rewrite Not working [backport 2.2] (by @mrodespin) + * [#11493](https://github.com/magento/magento2/pull/11493) -- Add "optional" translation in checkout password field (by @JeroenVanLeusden) + * [#11199](https://github.com/magento/magento2/pull/11199) -- Add db-prefix from env conf when command admin:user:create is executed (by @osrecio) + * [#11299](https://github.com/magento/magento2/pull/11299) -- Update Guest.php (by @lano-vargas) + * [#11381](https://github.com/magento/magento2/pull/11381) -- Save region correctly to save sales address from admin (by @raumatbel) + * [#11460](https://github.com/magento/magento2/pull/11460) -- [ISSUE-11140][BUGFIX] Skip store code admin from being detected in ca… (by @diglin) + * [#11505](https://github.com/magento/magento2/pull/11505) -- [Backport-2.2] Retain additional cron history by default (by @mpchadwick) + * [#11437](https://github.com/magento/magento2/pull/11437) -- Add `confirmation` and `lock_expires ` to customer export csv - Fix issue 10765 (by @convenient) + * [#11486](https://github.com/magento/magento2/pull/11486) -- [Backport 2.2]Add VAT number to email source variables (by @JeroenVanLeusden) + * [#11495](https://github.com/magento/magento2/pull/11495) -- MAGETWO-75743: Fix for #9783 Multiple parameters in widget.… (by @diazwatson) + * [#11500](https://github.com/magento/magento2/pull/11500) -- MAGETWO-81245: Handling all setProductsFilter items in array as arguments (by @kirmorozov) + * [#11555](https://github.com/magento/magento2/pull/11555) -- Travis CI functional tests maintenance for 2.2-develop (by @ishakhsuvarov) + * [#11235](https://github.com/magento/magento2/pull/11235) -- [2.2-develop] Add static test to detect blocks without name attribute (by @ihor-sviziev) + * [#11569](https://github.com/magento/magento2/pull/11569) -- Fixed double space typo (by @dverkade) + * [#11565](https://github.com/magento/magento2/pull/11565) -- Fix "pattern" UI Component validation (by @bap14) + * [#11317](https://github.com/magento/magento2/pull/11317) -- [Backport 2.2-develop] Send email to subscribers only when are new (by @osrecio) + * [#11385](https://github.com/magento/magento2/pull/11385) -- Fix #10856: Sync billing with shipping address on Admin Order Page (by @joni-jones) + * [#11499](https://github.com/magento/magento2/pull/11499) -- Ensure database is cleared/Magento reinstalled when TESTS_CLEANUP is enabled (by @joshuaswarren) + * [#11510](https://github.com/magento/magento2/pull/11510) -- Add interaction to admin:user:create command (by @cmuench) + * [#11522](https://github.com/magento/magento2/pull/11522) -- [Backport 2.2-develop] Fix Filter Customer Report Review (by @osrecio) + * [#11553](https://github.com/magento/magento2/pull/11553) -- [2.2 Backport] ProductRepository sku cache is corrupted when cacheLimit is reached (by @heldchen) + * [#11561](https://github.com/magento/magento2/pull/11561) -- Magento sets ISO invalid language code (by @crissanclick) + * [#11591](https://github.com/magento/magento2/pull/11591) -- [Backport 2.2-develop] #11586 Fix duplicated crontab 2>&1 expression (by @adrian-martinez-interactiv4) + * [#11439](https://github.com/magento/magento2/pull/11439) -- [Backport 2.2-develop] #11328 : app:config:dump adds extra space every time in multiline array value (by @adrian-martinez-interactiv4) + * [#11675](https://github.com/magento/magento2/pull/11675) -- MAGETWO-77672: in system.xml translate phrase not work, if comment starts from new line. (by @nmalevanec) + * [#11673](https://github.com/magento/magento2/pull/11673) -- [BACKPORT 2.2] [TASK] Removed Typo in Paypal TestCase didgit => digit (by @lewisvoncken) + * [#11704](https://github.com/magento/magento2/pull/11704) -- [Backport 2.2-develop] Travis: surround variable TRAVIS_BRANCH with double-quotes instead of single-quotes (by @adrian-martinez-interactiv4) + * [#11677](https://github.com/magento/magento2/pull/11677) -- [BACKPORT 2.2] [TASK] Moved Customer Groups Menu Item from Other sett… (by @lewisvoncken) + * [#11676](https://github.com/magento/magento2/pull/11676) -- #7915: customer objects are equal to eachother after observing event customer_save_after_data_object (by @RomaKis) + * [#11250](https://github.com/magento/magento2/pull/11250) -- Fixing #10275 keyboard submit of adminhtml suggest form. (by @romainruaud) + * [#11421](https://github.com/magento/magento2/pull/11421) -- FIX #11022 in 2.2-develop: Filter Groups of search criteria parameter have not been included for further processing (by @davidverholen) + * [#11440](https://github.com/magento/magento2/pull/11440) -- Add missing translations in Magento_UI (by @JeroenVanLeusden) + * [#11643](https://github.com/magento/magento2/pull/11643) -- Fixed ability to set field config from layout xml #11302 [backport 2.2] (by @vovayatsyuk) + * [#11637](https://github.com/magento/magento2/pull/11637) -- MAGETWO-81311: Check the length of the array before attempting to sli… (by @briscoda) + * [#11635](https://github.com/magento/magento2/pull/11635) -- Coupon codes not showing in invoice (by @crissanclick) + * [#11690](https://github.com/magento/magento2/pull/11690) -- Add a health check to the NGINX configuration sample (by @andrewhowdencom) + * [#11710](https://github.com/magento/magento2/pull/11710) -- Allow coupon code with special charater to be applied to order in checkout (by @gabrielqs-redstage) + * [#11720](https://github.com/magento/magento2/pull/11720) -- Fix Notice: freePackageValue is undefined (by @amenk) + * [#11734](https://github.com/magento/magento2/pull/11734) -- [TASK] Updated user.ini according to Magento DevDocs (by @lewisvoncken) + * [#11751](https://github.com/magento/magento2/pull/11751) -- [Backport 2.2-develop] Dashboard Fix Y Axis for range (by @osrecio) + * [#11749](https://github.com/magento/magento2/pull/11749) -- [Backport 2.2-develop] Fix datetime type product that show current date when is empty in grids (by @enriquei4) + * [#11745](https://github.com/magento/magento2/pull/11745) -- [Backport 2.2-develop] Fix label to avoid wrapping poorly,now break by word (by @enriquei4) + * [#11765](https://github.com/magento/magento2/pull/11765) -- Allows modules with underscores in name to add blocks to layout via XML (by @bentideswell) + * [#11410](https://github.com/magento/magento2/pull/11410) -- "Ignore this notification" isn't working (by @crissanclick) + * [#11607](https://github.com/magento/magento2/pull/11607) -- [Backport 2.2-develop] Fix AcountManagementTest unit test fail randomly (by @adrian-martinez-interactiv4) + * [#11610](https://github.com/magento/magento2/pull/11610) -- FR#6891_22 Add-to-cart checkbox still visible when = false (by @mrodespin) + * [#11757](https://github.com/magento/magento2/pull/11757) -- Fix #11729 - negative value in excel export [M2.2] (by @hauso) + * [#11363](https://github.com/magento/magento2/pull/11363) -- Issue #6924: Unmask exception message during product import (by @tim-bezhashvyly) + * [#11425](https://github.com/magento/magento2/pull/11425) -- Magento setup:install interactive shell (by @denisristic) + * [#11767](https://github.com/magento/magento2/pull/11767) -- 7640: X-Magento-Tags header containing whitespaces causes exception (by @nmalevanec) + * [#11779](https://github.com/magento/magento2/pull/11779) -- MAGETWO-4711: Improve error reporting for products images import. (by @p-bystritsky) + * [#11830](https://github.com/magento/magento2/pull/11830) -- Fix #11581: Reference to wrong / non-existing class (by @dverkade) + * [#11827](https://github.com/magento/magento2/pull/11827) -- Admin product search - Pressing enter does not submit #4696 (by @bohemiorulo) + * [#11337](https://github.com/magento/magento2/pull/11337) -- #11211 Fix Store View switcher (by @thiagolima-bm) + * [#11458](https://github.com/magento/magento2/pull/11458) -- Products added to cart with REST API give total prices equal to zero (by @peterjaap) + * [#11595](https://github.com/magento/magento2/pull/11595) -- Fix issue #10032 - Download back-up .tgz always takes the latest that's created (2.2-develop) (by @PieterCappelle) + * [#11747](https://github.com/magento/magento2/pull/11747) -- [Backport 2.2-develop] FIX show visual swatches in admin - product attribute (by @enriquei4) + * [#11824](https://github.com/magento/magento2/pull/11824) -- Magetwo 70954: Remove the component.clear from the custom options type. This causes the 'elem' array to become out of sync with the recordData (by @briscoda) + * [#11651](https://github.com/magento/magento2/pull/11651) -- [BUGFIX] Solved error while upgrading from 2.1 to 2.2 (by @lewisvoncken) + * [#11802](https://github.com/magento/magento2/pull/11802) -- #8236 FIX CMS blocks (by @thiagolima-bm) + * [#11843](https://github.com/magento/magento2/pull/11843) -- Save the price 0 as price in custom options [backport 2.2] (by @raumatbel) + * [#11854](https://github.com/magento/magento2/pull/11854) -- FilterBuilder Doc Block Update (by @ByteCreation) + * [#11397](https://github.com/magento/magento2/pull/11397) -- Fix for #9566: Show the correct label in the admin (by @michielgerritsen) + * [#11732](https://github.com/magento/magento2/pull/11732) -- MAGETWO-5015: Report error csv doesn't work when trying to import a csv file with semicolon delimiter. (by @p-bystritsky) + * [#11829](https://github.com/magento/magento2/pull/11829) -- Fix #10682: Meta description and keywords transform to html entities (by @dverkade) + * [#11933](https://github.com/magento/magento2/pull/11933) -- Changed constructor typo in Javascript class (by @dverkade) + * [#11911](https://github.com/magento/magento2/pull/11911) -- Order grid - Sort by Purchase Date Desc by default (by @ihor-sviziev) + * [#11817](https://github.com/magento/magento2/pull/11817) -- GITHUB-8970: Cannot assign products to categories not under tree root. (by @p-bystritsky) + * [#11405](https://github.com/magento/magento2/pull/11405) -- Allow setting of http response status code in a Redirection (by @gabrielqs-redstage) + * [#11858](https://github.com/magento/magento2/pull/11858) -- #11697 Theme: Added html node to page xml root, cause validation error (by @adrian-martinez-interactiv4) + * [#11869](https://github.com/magento/magento2/pull/11869) -- Resolve Error While Trying To Load Quote Item Collection Using Magent… (by @neeta-wagento) + * [#11889](https://github.com/magento/magento2/pull/11889) -- Save background color correctly in images. [backport 2.2] (by @raumatbel) + * [#11917](https://github.com/magento/magento2/pull/11917) -- [BACKPORT 2.2] [TASK] Add resetPassword call to the webapi (by @lewisvoncken) + * [#11949](https://github.com/magento/magento2/pull/11949) -- 11868: "Add Products" button has been duplicated after the customer group was changed. (by @nmalevanec) + * [#11959](https://github.com/magento/magento2/pull/11959) -- #11898 - Change NL PostCode Pattern (by @osrecio) + * [#11620](https://github.com/magento/magento2/pull/11620) -- Check attribute unique between same fields in magento commerce (by @raumatbel) + * [#11770](https://github.com/magento/magento2/pull/11770) -- Product attribute creation page handles Storefront tab visibility wrong (by @euronetzrt) + * [#11863](https://github.com/magento/magento2/pull/11863) -- Update wrong layout update xml handle installed in CMS Home Page by default (by @adrian-martinez-interactiv4) + * [#12011](https://github.com/magento/magento2/pull/12011) -- [backport 2.2] Magento 2 Store Code validation regex: doesn't support uppercase letters in store code (by @manuelson) + * [#12013](https://github.com/magento/magento2/pull/12013) -- Add validation for number of street lines (by @crissanclick) + * [#11785](https://github.com/magento/magento2/pull/11785) -- fix #8846: avoid duplicated attribute option values (by @gomencal) + * [#11993](https://github.com/magento/magento2/pull/11993) -- 11700: "Something Went Wrong" error for limited access admin user (by @RomaKis) + * [#12018](https://github.com/magento/magento2/pull/12018) -- Magento 2.2.0 Solution for Cross-sell product placeholder image size … (by @emiprotech) + * [#11556](https://github.com/magento/magento2/pull/11556) -- Fix #10583: Checkout place order exception when using a new address (by @joni-jones) + * [#11879](https://github.com/magento/magento2/pull/11879) -- #4004: Newsletter Subscriber create-date not set, and change_status_at broken (by @nemesis-back) + * [#11588](https://github.com/magento/magento2/pull/11588) -- Fix Issue #7225 - Remove hardcoding of apply_to when saving attributes (by @MartinPeverelli) + * [#11958](https://github.com/magento/magento2/pull/11958) -- 11197: Blank page at the checkout 'shipping' step[backport]. (by @nmalevanec) + * [#12091](https://github.com/magento/magento2/pull/12091) -- Fix "Undefined variable: responseAjax" notice when trying to save a shipment package (by @lazyguru) + * [#11461](https://github.com/magento/magento2/pull/11461) -- [ISSUE-10811][BUGFIX] Update .htaccess.sample to replace FollowSymLin… (by @diglin) + * [#11719](https://github.com/magento/magento2/pull/11719) -- 10920: Sku => Entity_id relations are fetched inefficiently when inserting attributes values during product import. (by @nmalevanec) + * [#11722](https://github.com/magento/magento2/pull/11722) -- 6802: Magento\Search\Helper\getSuggestUrl() not used in search template. (by @nmalevanec) + * [#11857](https://github.com/magento/magento2/pull/11857) -- CMS Page - CMS Page - Force validate layout update xml in production mode when saving CMS Page - Handle layout update xml validation exceptions (by @adrian-martinez-interactiv4) + * [#11902](https://github.com/magento/magento2/pull/11902) -- #9151: [Github] Sitemap.xml: lastmod timestamp can contain invalid dates (by @serhii-balko) + * [#11947](https://github.com/magento/magento2/pull/11947) -- Fix json encoded attribute backend type when attribute value is null (by @tkotosz) + * [#11962](https://github.com/magento/magento2/pull/11962) -- 11793: Magento2.1.5 admin shipping report shows wrong currency code (by @RomaKis) + * [#11988](https://github.com/magento/magento2/pull/11988) -- 10195: Order relation child is not set during edit operation(backport from 2.3 to 2.2) (by @RomaKis) + * [#12031](https://github.com/magento/magento2/pull/12031) -- Improve urn in xhtml (by @enriquei4) + * [#12082](https://github.com/magento/magento2/pull/12082) -- Products in cart report error when we have grouped or bundle product (by @mihaifaget) + * [#12131](https://github.com/magento/magento2/pull/12131) -- [Backport 2.2] Close PayPal popup window in case of rejected request #10820 (by @vovayatsyuk) + * [#12139](https://github.com/magento/magento2/pull/12139) -- 9768: Admin dashboard Most Viewed Products Tab only gives default attribute set's products(backport for 2.2) (by @RomaKis) + * [#11914](https://github.com/magento/magento2/pull/11914) -- [BACKPORT 2.2] [BUGFIX] All UI input fields should have maxlength of 255 because of V… (by @lewisvoncken) + * [#11944](https://github.com/magento/magento2/pull/11944) -- Report Handled Exceptions To New Relic (by @mpchadwick) + * [#12144](https://github.com/magento/magento2/pull/12144) -- Removed FileClassScannerTest dependency to "Magento_Catalog" (by @wexo-team) + * [#11459](https://github.com/magento/magento2/pull/11459) -- close #10810 Migrates Apache Access Syntax to 2.4 on Apache >= 2.4 (by @jonashrem) + * [#11968](https://github.com/magento/magento2/pull/11968) -- Fix bug: Customer import deletes exiting customer entity Fields (by @jalogut) + * [#12061](https://github.com/magento/magento2/pull/12061) -- Cleanup for object manager references and depricated method (by @atishgoswami) + * [#12136](https://github.com/magento/magento2/pull/12136) -- update button.phtml overcomplicated translation phrase. 2.2 (by @ChuckyK) + * [#11876](https://github.com/magento/magento2/pull/11876) -- After logging in customer is now not redirecting to Customer Dashboard by default (by @p-bystritsky) + * [#11274](https://github.com/magento/magento2/pull/11274) -- Fix #10477 Check cart rule subselect conditions against quote item children too (by @marinagociu) + * [#11952](https://github.com/magento/magento2/pull/11952) -- 11832: Create order (on Customer edit page) - not working from admin environment (by @RomaKis) + * [#12035](https://github.com/magento/magento2/pull/12035) -- Fix newsletter subscriptions between stores (by @sbaixauli) + * [#12001](https://github.com/magento/magento2/pull/12001) -- 11532: Duplicate Simple Product Throws Error: Undefined offset: 0 in SaveHandler.php on line 122 (by @RomaKis) + * [#12077](https://github.com/magento/magento2/pull/12077) -- 10628: Color attribute swatches are not visible if sorting is enabled (by @RomaKis) + * [#12130](https://github.com/magento/magento2/pull/12130) -- [Backport 2.2] MAGETWO-71697: Fix possible bug when saving address with empty street line #10582 (by @vovayatsyuk) + * [#12141](https://github.com/magento/magento2/pull/12141) -- Fix js error when disable/enable wysiwyg editor (by @vovayatsyuk) + * [#12173](https://github.com/magento/magento2/pull/12173) -- 8022: Uncaught Error: Call to a member function addItem() on array in app/code/Magento/Sales/Model/Order/Shipment.php(backport to 2.2) (by @RomaKis) + +2.2.1 +============= +* GitHub issues: + * [#4248](https://github.com/magento/magento2/issues/4248) -- Validations not working on customer registration on DOB field. (fixed in [#11067](https://github.com/magento/magento2/pull/11067)) + * [#6350](https://github.com/magento/magento2/issues/6350) -- Frontend: Datepicker/calendar control does not use the store locale (fixed in [#11067](https://github.com/magento/magento2/pull/11067)) + * [#6858](https://github.com/magento/magento2/issues/6858) -- DatePicker date format does not reflect user's locale (fixed in [#11067](https://github.com/magento/magento2/pull/11067)) + * [#6831](https://github.com/magento/magento2/issues/6831) -- Magento 2.1.1 Invalid input date format 'Invalid date' (fixed in [#11067](https://github.com/magento/magento2/pull/11067)) + * [#9743](https://github.com/magento/magento2/issues/9743) -- Invalid date when customer validate with French locale (fixed in [#11067](https://github.com/magento/magento2/pull/11067)) + * [#6712](https://github.com/magento/magento2/issues/6712) -- Footer Links Widget CSS Issue (fixed in [#11063](https://github.com/magento/magento2/pull/11063)) + * [#9008](https://github.com/magento/magento2/issues/9008) -- Error Message Is Confusing When Code Base Is Behind Database Module Version (fixed in [#11064](https://github.com/magento/magento2/pull/11064)) + * [#9981](https://github.com/magento/magento2/issues/9981) -- M2 suggests running setup:upgrade if version number of module is higher than expected (fixed in [#11064](https://github.com/magento/magento2/pull/11064)) + * [#10824](https://github.com/magento/magento2/issues/10824) -- Cannot add new columns to item grid in admin sales_order_view layout (fixed in [#11076](https://github.com/magento/magento2/pull/11076)) + * [#10417](https://github.com/magento/magento2/issues/10417) -- Wysywig editor shows broken image icons (fixed in [#11048](https://github.com/magento/magento2/pull/11048)) + * [#10697](https://github.com/magento/magento2/issues/10697) -- Product Import: Additional data: Invalid URL key (fixed in [#11049](https://github.com/magento/magento2/pull/11049)) + * [#10474](https://github.com/magento/magento2/issues/10474) -- Error message in product review form not being translated (fixed in [#11069](https://github.com/magento/magento2/pull/11069)) + * [#9877](https://github.com/magento/magento2/issues/9877) -- getCacheTags for price issue (fixed in [#11154](https://github.com/magento/magento2/pull/11154)) + * [#10738](https://github.com/magento/magento2/issues/10738) -- Empty attribute label is displayed on product page when other language used. (fixed in [#11168](https://github.com/magento/magento2/pull/11168)) + * [#9900](https://github.com/magento/magento2/issues/9900) -- Cms module collections missing event prefix (fixed in [#11223](https://github.com/magento/magento2/pull/11223)) + * [#11044](https://github.com/magento/magento2/issues/11044) -- magento setup:upgrade prompts to run compilation, even in developer mode (fixed in [#11050](https://github.com/magento/magento2/pull/11050)) + * [#10775](https://github.com/magento/magento2/issues/10775) -- 404 Forbidden sounds not right (fixed in [#11134](https://github.com/magento/magento2/pull/11134)) + * [#11231](https://github.com/magento/magento2/issues/11231) -- Can't close mobile search bar once typed (fixed in [#11246](https://github.com/magento/magento2/pull/11246)) + * [#10317](https://github.com/magento/magento2/issues/10317) -- Region is being overridden when changing from a required-state country to one that is not required (fixed in [#11254](https://github.com/magento/magento2/pull/11254)) + * [#11089](https://github.com/magento/magento2/issues/11089) -- setup:config:set --key append instead of replace (fixed in [#11155](https://github.com/magento/magento2/pull/11155)) + * [#7582](https://github.com/magento/magento2/issues/7582) -- Payment methods in payments title in wrong language (fixed in [#11165](https://github.com/magento/magento2/pull/11165)) + * [#5105](https://github.com/magento/magento2/issues/5105) -- Error While send Invoice with Grouped Products (fixed in [#11297](https://github.com/magento/magento2/pull/11297)) + * [#11163](https://github.com/magento/magento2/issues/11163) -- Magento 2.2.0 Pages showing error: Data key is missing: code-entity (fixed in [#11205](https://github.com/magento/magento2/pull/11205)) + * [#11329](https://github.com/magento/magento2/issues/11329) -- Unable to proceed massaction "Update attributes" with required multiple select attribute (fixed in [#11349](https://github.com/magento/magento2/pull/11349)) + * [#8958](https://github.com/magento/magento2/issues/8958) -- Hint mistake in english language (fixed in [#11390](https://github.com/magento/magento2/pull/11390)) +* GitHub pull requests: + * [#11067](https://github.com/magento/magento2/pull/11067) -- Fix dob date validation on custom locale (by @joachimVT) + * [#11054](https://github.com/magento/magento2/pull/11054) -- Add dev:tests:run parameter to pass arguments to phpunit (by @schmengler) + * [#11056](https://github.com/magento/magento2/pull/11056) -- Do not disable maintenance mode after running a backup. (by @stevenvdp) + * [#11058](https://github.com/magento/magento2/pull/11058) -- Escape html before replace new line with break (by @Quinten) + * [#11063](https://github.com/magento/magento2/pull/11063) -- 6712 Remove additional margin for footer links widget; prevents layou… (by @fragdochkarl) + * [#11064](https://github.com/magento/magento2/pull/11064) -- Show different message if DB module version is higher than code modul… (by @schmengler) + * [#11076](https://github.com/magento/magento2/pull/11076) -- Backport to 2.2 of #10824: add name for order items grid default renderer block (by @gsomoza) + * [#11048](https://github.com/magento/magento2/pull/11048) -- Fix #10417 (by @PieterCappelle) + * [#11049](https://github.com/magento/magento2/pull/11049) -- Vague error message for invalid url_key for category (by @avdb) + * [#11069](https://github.com/magento/magento2/pull/11069) -- Error message in product review form not being translated (by @Echron) + * [#11127](https://github.com/magento/magento2/pull/11127) -- Add missing return statements in setters (by @niccifor) + * [#11138](https://github.com/magento/magento2/pull/11138) -- Added template as argument to the store address renderer to allow custom formatting (by @jokeputs) + * [#11147](https://github.com/magento/magento2/pull/11147) -- Fix the correct removal of the images and the removal of all images in the catalog (by @raumatbel) + * [#11154](https://github.com/magento/magento2/pull/11154) -- Issue #9877: Backport of: getCacheTags for price issue #10930 (by @denysbabenko) + * [#11160](https://github.com/magento/magento2/pull/11160) -- Ported Down changes from PR#10919 (by @strell) + * [#11200](https://github.com/magento/magento2/pull/11200) -- Delete CallExit function for After plugin logic execution 2.2-develop [BackPort] (by @osrecio) + * [#11168](https://github.com/magento/magento2/pull/11168) -- Fixed issue #10738: Don't display attribute label if defined as "none" in layout (by @maksek) + * [#11223](https://github.com/magento/magento2/pull/11223) -- Cms page/block eventprefix fix issue 9900 (by @convenient) + * [#11229](https://github.com/magento/magento2/pull/11229) -- Disable secret key validation on admin noroute to fix redirect loop (by @convenient) + * [#11050](https://github.com/magento/magento2/pull/11050) -- Only prompt for deploy command in production mode (by @schmengler) + * [#11134](https://github.com/magento/magento2/pull/11134) -- Fix 404 status header (by @Zifius) + * [#11084](https://github.com/magento/magento2/pull/11084) -- Fix in stripped min length validation when value has special characters (by @rubenRP) + * [#11246](https://github.com/magento/magento2/pull/11246) -- Can't close mobile search bar (by @crissanclick) + * [#11254](https://github.com/magento/magento2/pull/11254) -- Fix for #10317 Disable region list when switching to a region optional country. (by @romainruaud) + * [#11155](https://github.com/magento/magento2/pull/11155) -- Refactor ConfigGenerator to replace/set crypt key instead of append (by @renttek) + * [#11291](https://github.com/magento/magento2/pull/11291) -- Fix #9243 - Upgrade ZF components. Zend_Service (by @dverkade) + * [#11165](https://github.com/magento/magento2/pull/11165) -- #7582: use setStoreId after custom load method to give storeId precedence (by @bka) + * [#11297](https://github.com/magento/magento2/pull/11297) -- Fix for issue #5105 - Error While send Invoice with Grouped Products (by @michielgerritsen) + * [#11327](https://github.com/magento/magento2/pull/11327) -- Fix #10812: htaccess Options override (by @dverkade) + * [#11081](https://github.com/magento/magento2/pull/11081) -- Text updated. (by @RakeshJesadiya) + * [#11183](https://github.com/magento/magento2/pull/11183) -- FIX for #11166 Index Handling Fatal Error (by @larsroettig) + * [#11205](https://github.com/magento/magento2/pull/11205) -- Fixes #11163 missing data key code-entity in CMS page edit form (by @Tomasz-Silpion) + * [#11219](https://github.com/magento/magento2/pull/11219) -- Fix typo in sessionStorage polyfill (by @mszydlo) + * [#11249](https://github.com/magento/magento2/pull/11249) -- Add a payload extender to the default shipping-save-processor (Backport to 2.2) (by @navarr) + * [#11345](https://github.com/magento/magento2/pull/11345) -- Use US English spelling for "Optimization". (by @davidangel) + * [#11349](https://github.com/magento/magento2/pull/11349) -- Bug fix update attributes (by @manuelson) + * [#11390](https://github.com/magento/magento2/pull/11390) -- Fix typo in design rule hint message (by @jahvi) + +2.2.0 +============= +* GitHub issues: + * [#8287](https://github.com/magento/magento2/issues/8287) -- InputException while updating cart with Minimum order amount enabled (fixed in [#8474](https://github.com/magento/magento2/pull/8474)) + * [#8315](https://github.com/magento/magento2/issues/8315) -- Error with StdoTest (fixed in [#8487](https://github.com/magento/magento2/pull/8487)) + * [#5808](https://github.com/magento/magento2/issues/5808) -- [2.1.0] Problem on mobile when catalog gallery allowfullscreen is false (fixed in [#8434](https://github.com/magento/magento2/pull/8434)) + * [#8392](https://github.com/magento/magento2/issues/8392) -- Initial loading of the related-products sorting fails in Edge-Mode (fixed in [#8467](https://github.com/magento/magento2/pull/8467)) + * [#8076](https://github.com/magento/magento2/issues/8076) -- Currency Setup in admin throws in_array error when a single value is selected (fixed in [#8077](https://github.com/magento/magento2/pull/8077)) + * [#8277](https://github.com/magento/magento2/issues/8277) -- CatalogImportExport uploader can't handle HTTPS images (fixed in [#8278](https://github.com/magento/magento2/pull/8278)) + * [#7353](https://github.com/magento/magento2/issues/7353) -- Crosssells are never shown when using product/list/items.phtml template (fixed in [#8602](https://github.com/magento/magento2/pull/8602)) + * [#8632](https://github.com/magento/magento2/issues/8632) -- Location of wishlist.js file is incorrect (fixed in [#8633](https://github.com/magento/magento2/pull/8633)) + * [#6634](https://github.com/magento/magento2/issues/6634) -- Yes/No attribute value is not shown on a product details page (fixed in [#8623](https://github.com/magento/magento2/pull/8623)) + * [#8566](https://github.com/magento/magento2/issues/8566) -- Setting 'show_out_of_stock' to 'No' has no effect (fixed in [#8736](https://github.com/magento/magento2/pull/8736)) + * [#6706](https://github.com/magento/magento2/issues/6706) -- Notice undefined index when changes swatch attribute (fixed in [#6707](https://github.com/magento/magento2/pull/6707)) + * [#6855](https://github.com/magento/magento2/issues/6855) -- Create order via backend doesn't work after using NL translation for order-header (fixed in [#6856](https://github.com/magento/magento2/pull/6856)) + * [#8515](https://github.com/magento/magento2/issues/8515) -- Downloadable product is available for download even if order state is set canceled. (fixed in [#8917](https://github.com/magento/magento2/pull/8917)) + * [#8871](https://github.com/magento/magento2/issues/8871) -- Typo in Pull Request Template (fixed in [#8908](https://github.com/magento/magento2/pull/8908)) + * [#3791](https://github.com/magento/magento2/issues/3791) -- Error review when customer is not logged (fixed in [#9001](https://github.com/magento/magento2/pull/9001)) + * [#9017](https://github.com/magento/magento2/issues/9017) -- Duplicate call to $this->getLinkField(); (fixed in [#9057](https://github.com/magento/magento2/pull/9057)) + * [#7498](https://github.com/magento/magento2/issues/7498) -- Grammar Mistake: You don't subscribe to our newsletter. (fixed in [#9080](https://github.com/magento/magento2/pull/9080)) + * [#9078](https://github.com/magento/magento2/issues/9078) -- Does not translate "Track All Shipments" in My Account, view order (fixed in [#9095](https://github.com/magento/magento2/pull/9095)) + * [#5731](https://github.com/magento/magento2/issues/5731) -- FPT label not translatable in the totals on the cart page. (fixed in [#9204](https://github.com/magento/magento2/pull/9204)) + * [#5040](https://github.com/magento/magento2/issues/5040) -- Change 'select' to 'query' in AbstractSearchResult (fixed in [#5043](https://github.com/magento/magento2/pull/5043)) + * [#8761](https://github.com/magento/magento2/issues/8761) -- Popup-Modal not closing on Safari/Windows (fixed in [#8824](https://github.com/magento/magento2/pull/8824)) + * [#7549](https://github.com/magento/magento2/issues/7549) -- Google API Tracking code missing single quote after account number (fixed in [#9084](https://github.com/magento/magento2/pull/9084)) + * [#1146](https://github.com/magento/magento2/issues/1146) -- A few issues when you use /pub as DocumentRoot (fixed in [#9094](https://github.com/magento/magento2/pull/9094)) + * [#2802](https://github.com/magento/magento2/issues/2802) -- Sitemap generation in wrong folder when vhost is connected to pub folder (fixed in [#9094](https://github.com/magento/magento2/pull/9094)) + * [#9200](https://github.com/magento/magento2/issues/9200) -- Create new CLI command: Enable DB logging (fixed in [#9264](https://github.com/magento/magento2/pull/9264)) + * [#9199](https://github.com/magento/magento2/issues/9199) -- Create New CLI command: Generate Varnish VCL file (fixed in [#9286](https://github.com/magento/magento2/pull/9286)) + * [#6822](https://github.com/magento/magento2/issues/6822) -- CSS Minify Option Breaks inline SVG XML (fixed in [#9027](https://github.com/magento/magento2/pull/9027)) + * [#8552](https://github.com/magento/magento2/issues/8552) -- CSS Minifying not compatible with CSS3 calc() function (fixed in [#9027](https://github.com/magento/magento2/pull/9027)) + * [#9236](https://github.com/magento/magento2/issues/9236) -- Upgrade ZF components. Zend_Json (fixed in [#9262](https://github.com/magento/magento2/pull/9262) and [#9261](https://github.com/magento/magento2/pull/9261) and [#9344](https://github.com/magento/magento2/pull/9344) and [#9753](https://github.com/magento/magento2/pull/9753) and [#9754](https://github.com/magento/magento2/pull/9754)) + * [#7523](https://github.com/magento/magento2/issues/7523) -- Zend_Db_Statement_Exception after refreshing browser with empty category (fixed in [#9400](https://github.com/magento/magento2/pull/9400)) + * [#9237](https://github.com/magento/magento2/issues/9237) -- Upgrade ZF components. Zend_Log (fixed in [#9285](https://github.com/magento/magento2/pull/9285)) + * [#9518](https://github.com/magento/magento2/issues/9518) -- Chrome version 58 causes problems with selections in the tinymce editor (fixed in [#9540](https://github.com/magento/magento2/pull/9540)) + * [#9241](https://github.com/magento/magento2/issues/9241) -- Upgrade ZF components. Zend_Wildfire (fixed in [#9622](https://github.com/magento/magento2/pull/9622)) + * [#9239](https://github.com/magento/magento2/issues/9239) -- Upgrade ZF components. Zend_Controller (fixed in [#9622](https://github.com/magento/magento2/pull/9622)) + * [#6455](https://github.com/magento/magento2/issues/6455) -- Cookie Restriction Mode Overlay is cached by Varnish (fixed in [#9711](https://github.com/magento/magento2/pull/9711)) + * [#5596](https://github.com/magento/magento2/issues/5596) -- Google Universal Analytics does not track when Cookie Restriction is enabled (fixed in [#9713](https://github.com/magento/magento2/pull/9713)) + * [#6441](https://github.com/magento/magento2/issues/6441) -- Google Analytics Tracking Code cached by Varnish if Cookie Restriction Settings are active (fixed in [#9713](https://github.com/magento/magento2/pull/9713)) + * [#9242](https://github.com/magento/magento2/issues/9242) -- Upgrade ZF components. Zend_Session (fixed in [#9348](https://github.com/magento/magento2/pull/9348)) + * [#7279](https://github.com/magento/magento2/issues/7279) -- Bill-to Name and Ship-to Name trancated to 20 characters in backend (fixed in [#9654](https://github.com/magento/magento2/pull/9654)) + * [#6151](https://github.com/magento/magento2/issues/6151) -- Can't delete last item in cart if Minimum Order is Enable (fixed in [#9714](https://github.com/magento/magento2/pull/9714)) + * [#4272](https://github.com/magento/magento2/issues/4272) -- v2.0.4 Credit memos with adjustment fees cannot be fully refunded with a second credit memo (fixed in [#9715](https://github.com/magento/magento2/pull/9715)) + * [#6207](https://github.com/magento/magento2/issues/6207) -- Checkbox IDs for Terms and Conditions should be unique in Checkout (fixed in [#9717](https://github.com/magento/magento2/pull/9717)) + * [#7844](https://github.com/magento/magento2/issues/7844) -- Customer with unique attribute can't be saved (fixed in [#9712](https://github.com/magento/magento2/pull/9712)) + * [#6244](https://github.com/magento/magento2/issues/6244) -- Promo code label not used (fixed in [#9721](https://github.com/magento/magento2/pull/9721)) + * [#9771](https://github.com/magento/magento2/issues/9771) -- XML instruction referenceBlock does not allow template= or does it? (fixed in [#9772](https://github.com/magento/magento2/pull/9772)) + * [#8221](https://github.com/magento/magento2/issues/8221) -- Javascript "mixins" doesn't works if 'urlArgs' is in requirejs-config.js (fixed in [#9665](https://github.com/magento/magento2/pull/9665)) + * [#9278](https://github.com/magento/magento2/issues/9278) -- Create new CLI command: Enable Template Hints (fixed in [#9778](https://github.com/magento/magento2/pull/9778)) + * [#9819](https://github.com/magento/magento2/issues/9819) -- Authentication_lock settings cannot be edited in the Backend (fixed in [#9820](https://github.com/magento/magento2/pull/9820)) + * [#9216](https://github.com/magento/magento2/issues/9216) -- Coupon codes not showing in invoice print out (fixed in [#9780](https://github.com/magento/magento2/pull/9780)) + * [#9679](https://github.com/magento/magento2/issues/9679) -- Translation for layered navigation attribute option not working (fixed in [#9873](https://github.com/magento/magento2/pull/9873)) + * [#3060](https://github.com/magento/magento2/issues/3060) -- setup:static-content:deploy, setup:di:compile and deploy:mode:set will not return a non-zero exit code if any error occurs (fixed in [#7780](https://github.com/magento/magento2/pull/7780)) + * [#9421](https://github.com/magento/magento2/issues/9421) -- Inconsistent Gift Options checkbox labels (fixed in [#9525](https://github.com/magento/magento2/pull/9525)) + * [#9805](https://github.com/magento/magento2/issues/9805) -- Static tests in Windows fail due to file path mismatches (fixed in [#9902](https://github.com/magento/magento2/pull/9902)) + * [#9924](https://github.com/magento/magento2/issues/9924) -- Prefix and suffix are not prefilled in the quote shipping address (fixed in [#9925](https://github.com/magento/magento2/pull/9925)) + * [#4237](https://github.com/magento/magento2/issues/4237) -- Cron times in the database have a double timezone correction (fixed in [#9943](https://github.com/magento/magento2/pull/9943)) + * [#9426](https://github.com/magento/magento2/issues/9426) -- Incorrect order date in Orders grid (fixed in [#9941](https://github.com/magento/magento2/pull/9941)) + * [#3380](https://github.com/magento/magento2/issues/3380) -- Remove scheduled jobs after changing cron settings (fixed in [#9957](https://github.com/magento/magento2/pull/9957)) + * [#7504](https://github.com/magento/magento2/issues/7504) -- sitemap image URLs do not match with those on product pages (fixed in [#9082](https://github.com/magento/magento2/pull/9082)) + * [#8732](https://github.com/magento/magento2/issues/8732) -- The country drop-down list display incorrect after upgrade to 2.1.4 in Admin (fixed in [#9429](https://github.com/magento/magento2/pull/9429)) + * [#9680](https://github.com/magento/magento2/issues/9680) -- Adding product configurations uses sku based name (fixed in [#9681](https://github.com/magento/magento2/pull/9681)) + * [#10017](https://github.com/magento/magento2/issues/10017) -- Customer Backend: Confirmation Flag is being overwritten by save of the Customer (fixed in [#9681](https://github.com/magento/magento2/pull/9681)) + * [#2266](https://github.com/magento/magento2/issues/2266) -- Action column menu does not stay over the action column (fixed in [#10082](https://github.com/magento/magento2/pull/10082)) + * [#5381](https://github.com/magento/magento2/issues/5381) -- Cannot create a `etc/view.xml` file with an `images` tag with an attribute `module` other than `Magento_Catalog` (fixed in [#10052](https://github.com/magento/magento2/pull/10052)) + * [#6337](https://github.com/magento/magento2/issues/6337) -- Not able to translate page layout head titles (fixed in [#9992](https://github.com/magento/magento2/pull/9992)) + * [#3872](https://github.com/magento/magento2/issues/3872) -- Slash as category URL suffix gives 404 error on all category pages (fixed in [#10043](https://github.com/magento/magento2/pull/10043)) + * [#4660](https://github.com/magento/magento2/issues/4660) -- Multiple URLs causes duplicated content (fixed in [#10043](https://github.com/magento/magento2/pull/10043)) + * [#4876](https://github.com/magento/magento2/issues/4876) -- Product URL Suffix "/" results in 404 error (fixed in [#10043](https://github.com/magento/magento2/pull/10043)) + * [#8264](https://github.com/magento/magento2/issues/8264) -- Custom URL Rewrite where the request path ends with a forward slash is not matched (fixed in [#10043](https://github.com/magento/magento2/pull/10043)) + * [#6396](https://github.com/magento/magento2/issues/6396) -- Cart Price Rules: Category selection UI for Conditions do not come up. (fixed in [#10094](https://github.com/magento/magento2/pull/10094)) + * [#10124](https://github.com/magento/magento2/issues/10124) -- Wrong order of "width" x "height" when uploading image to admin under Content>Design Config (fixed in [#10126](https://github.com/magento/magento2/pull/10126)) + * [#6594](https://github.com/magento/magento2/issues/6594) -- Magento 2.1 EE: simplexml_load_string() error in custom widget (fixed in [#10151](https://github.com/magento/magento2/pull/10151)) + * [#10148](https://github.com/magento/magento2/issues/10148) -- Developer ACL incorrect (fixed in [#10149](https://github.com/magento/magento2/pull/10149)) + * [#9445](https://github.com/magento/magento2/issues/9445) -- Cart 860 does not contain item 1204 (fixed in [#10059](https://github.com/magento/magento2/pull/10059)) +* GitHub pull requests: + * [#4078](https://github.com/magento/magento2/pull/4078) -- Add logo folder to list of allowed resources (by @thaiphan) + * [#4355](https://github.com/magento/magento2/pull/4355) -- Enforce password and password-confirm as strings (by @nevvermind) + * [#4175](https://github.com/magento/magento2/pull/4175) -- PHP 7 (by @rafaelstz) + * [#4669](https://github.com/magento/magento2/pull/4669) -- Php 5.5 support was removed (by @fooman) + * [#4766](https://github.com/magento/magento2/pull/4766) -- The time has come for splat operator (by @orlangur) + * [#4867](https://github.com/magento/magento2/pull/4867) -- Fix commandExecutor interface mismatch (by @wexo-team) + * [#3705](https://github.com/magento/magento2/pull/3705) -- fix issue #3704 regarding integer attribute values being cast to decimal (by @digitalpianism) + * [#3750](https://github.com/magento/magento2/pull/3750) -- Add ability to show custom error message on Authorizenet place order (by @ytorbyk) + * [#3859](https://github.com/magento/magento2/pull/3859) -- Fixes _toHtml method of Checkout/Block/Cart/Link class (by @ddonnini) + * [#4017](https://github.com/magento/magento2/pull/4017) -- Add the $t to translate the message (by @mamzellejuu) + * [#4239](https://github.com/magento/magento2/pull/4239) -- Attribute Model specifiable in Propertymapper (by @liolemaire) + * [#4583](https://github.com/magento/magento2/pull/4583) -- Fix desktop spelling in lib/web/css #4557 (by @BenSpace48) + * [#2735](https://github.com/magento/magento2/pull/2735) -- Add database port to Magento Setup Model Installer (by @tkn98) + * [#4275](https://github.com/magento/magento2/pull/4275) -- Database port missing in Magento\TestFramework\Db\Mysql #3529 (by @gordonknoppe) + * [#4372](https://github.com/magento/magento2/pull/4372) -- Remove unused property + use ::class (by @nevvermind) + * [#2274](https://github.com/magento/magento2/pull/2274) -- TypeError: this.trigger is not a function (by @daim2k5) + * [#3050](https://github.com/magento/magento2/pull/3050) -- Replace PrototypeJS (by @srenon) + * [#3436](https://github.com/magento/magento2/pull/3436) -- Fix stripped-min-length check (by @avoelkl) + * [#3638](https://github.com/magento/magento2/pull/3638) -- Fix #3637 Add missing catalogsearch layout for swatches. (by @romainruaud) + * [#3633](https://github.com/magento/magento2/pull/3633) -- #768 - fix Missing acl.xml for the Magento_Checkout module (by @tzyganu) + * [#3708](https://github.com/magento/magento2/pull/3708) -- Add 'yyyy' to nomalizedDate method map for adminhtml i18n (by @Amakata) + * [#3973](https://github.com/magento/magento2/pull/3973) -- fix bug on newsletter subscription action when user use an existing email already subscribed (by @manfrinm) + * [#3932](https://github.com/magento/magento2/pull/3932) -- Update Date.php (by @Maddesto) + * [#3907](https://github.com/magento/magento2/pull/3907) -- Update Layout.php (by @Maddesto) + * [#4051](https://github.com/magento/magento2/pull/4051) -- Fix "minimum-length" option of the "validate-length" JS validation (by @adragus-inviqa) + * [#4269](https://github.com/magento/magento2/pull/4269) -- ConfigurableProduct validator, first check if array item exists (by @BlackIkeEagle) + * [#4496](https://github.com/magento/magento2/pull/4496) -- Access element through jQuery (by @sikker) + * [#4631](https://github.com/magento/magento2/pull/4631) -- Previous is spelt incorrectly (by @BenSpace48) + * [#4882](https://github.com/magento/magento2/pull/4882) -- Fix handling is_region_required key as optional (by @komsitr) + * [#5028](https://github.com/magento/magento2/pull/5028) -- Load jquery using requirejs to print page (by @Bartlomiejsz) + * [#1957](https://github.com/magento/magento2/pull/1957) -- Add required interface implementation (by @udovicic) + * [#2492](https://github.com/magento/magento2/pull/2492) -- No translation from "Orders and Returns" footer links (by @mageho) + * [#3749](https://github.com/magento/magento2/pull/3749) -- Stop screen loader on payment error (by @ytorbyk) + * [#4901](https://github.com/magento/magento2/pull/4901) -- Fix XML validation value type of post-code to "boolean" (by @adragus-inviqa) + * [#5066](https://github.com/magento/magento2/pull/5066) -- Add underscore as dependency to quote.js (by @Bartlomiejsz) + * [#5116](https://github.com/magento/magento2/pull/5116) -- Fixes invalid json objects in the order email templates. (by @hostep) + * [#5095](https://github.com/magento/magento2/pull/5095) -- Fix integration test expectation to match count of countries in the database (by @Vinai) + * [#5200](https://github.com/magento/magento2/pull/5200) -- Adminhtml sales view - Escape remoteIp (by @convenient) + * [#4294](https://github.com/magento/magento2/pull/4294) -- Static deploy flags (by @denisristic) + * [#3137](https://github.com/magento/magento2/pull/3137) -- Update nginx.conf.sample (by @thaiphan) + * [#3746](https://github.com/magento/magento2/pull/3746) -- Add HttpInterface methods and add up-casts for type safety (by @Vinai) + * [#4354](https://github.com/magento/magento2/pull/4354) -- Adds test for getDataUsingMethod using digits (by @fooman) + * [#4396](https://github.com/magento/magento2/pull/4396) -- Don't hardcode the Magento_Backend::admin index (by @annybs) + * [#4491](https://github.com/magento/magento2/pull/4491) -- Correction: variable naming for user roles & role id (by @MagePsycho) + * [#4519](https://github.com/magento/magento2/pull/4519) -- Create auth.json.sample (by @rafaelstz) + * [#3688](https://github.com/magento/magento2/pull/3688) -- added partial fix for issue #2617. (by @whizkid79) + * [#3770](https://github.com/magento/magento2/pull/3770) -- Bugfix: Unable to activate search form on phone (by @vovayatsyuk) + * [#4011](https://github.com/magento/magento2/pull/4011) -- Fixed post var name for update attributes (by @Corefix) + * [#2791](https://github.com/magento/magento2/pull/2791) -- Update Template.php (by @liam-wiltshire) + * [#5496](https://github.com/magento/magento2/pull/5496) -- Fixes #5495 (Mobile navigation submenus need two clicks to open) (by @ajpevers) + * [#5725](https://github.com/magento/magento2/pull/5725) -- Fix/translation in validation files (by @dvynograd) + * [#5915](https://github.com/magento/magento2/pull/5915) -- Added missing translation to range grid filter (by @maqlec) + * [#5884](https://github.com/magento/magento2/pull/5884) -- Use alias already defined in requirejs-config.js (by @kassner) + * [#4388](https://github.com/magento/magento2/pull/4388) -- Fixed column description for "website_id" column (by @ikk0) + * [#1628](https://github.com/magento/magento2/pull/1628) -- Add cache of configuration files list (by @otakarmare) + * [#4791](https://github.com/magento/magento2/pull/4791) -- Replace fabpot/php-cs-fixer with friendsofphp/php-cs-fixer (by @GordonLesti) + * [#5983](https://github.com/magento/magento2/pull/5983) -- Fix 'Track your order' i18n. (by @peec) + * [#1988](https://github.com/magento/magento2/pull/1988) -- Use inline elements for inline links (by @chicgeek) + * [#6283](https://github.com/magento/magento2/pull/6283) -- Update elements.xsd (by @aholovan) + * [#1935](https://github.com/magento/magento2/pull/1935) -- Added 'target' attribute to the allowed attributes array for link block (by @fcapua-summa) + * [#4733](https://github.com/magento/magento2/pull/4733) -- Escape Js Quote for layout updates (by @bchatard) + * [#4565](https://github.com/magento/magento2/pull/4565) -- Update Container.php (by @Maddesto) + * [#4845](https://github.com/magento/magento2/pull/4845) -- Set return code for SetModeCommand (by @mc388) + * [#2037](https://github.com/magento/magento2/pull/2037) -- Correct the error message when creating wrong object for block (by @hiephm) + * [#3779](https://github.com/magento/magento2/pull/3779) -- Add dispatching of view_block_abstract_to_html_after event (by @aleron75) + * [#5741](https://github.com/magento/magento2/pull/5741) -- Update AbstractTemplate.php (by @vivek201) + * [#5145](https://github.com/magento/magento2/pull/5145) -- \Magento\CatalogInventory\Model\Stock\Status->getStockId() to return correct value (by @fe-lix-) + * [#6009](https://github.com/magento/magento2/pull/6009) -- Update README.md (by @fooman) + * [#6280](https://github.com/magento/magento2/pull/6280) -- Fixed layout for customer authentication popup (by @rogyar) + * [#6549](https://github.com/magento/magento2/pull/6549) -- Remove obsolete comment in catalog_category_view.xml (by @pdanzinger) + * [#6804](https://github.com/magento/magento2/pull/6804) -- Fix nav not working in mobile (by @slackerzz) + * [#6801](https://github.com/magento/magento2/pull/6801) -- Fixed unclosed span tag in Review module (by @PingusPepan) + * [#5045](https://github.com/magento/magento2/pull/5045) -- Fix runner for JsTestDriver based tests on OS X (by @Vinai) + * [#4958](https://github.com/magento/magento2/pull/4958) -- block newsletter title (by @slackerzz) + * [#5548](https://github.com/magento/magento2/pull/5548) -- Fix error with the WYSIWYG and Greek characters (by @sakisplus) + * [#7256](https://github.com/magento/magento2/pull/7256) -- Fix incorrect table name during catalog product indexing (by @nagno) + * [#6972](https://github.com/magento/magento2/pull/6972) -- Fix issue #6968 since checkout success title is not displayed (by @AngelVazquezArroyo) + * [#4121](https://github.com/magento/magento2/pull/4121) -- Ensure composer.json exists (by @dank00) + * [#4134](https://github.com/magento/magento2/pull/4134) -- Added call to action to compile command error (by @sammarcus) + * [#6974](https://github.com/magento/magento2/pull/6974) -- Fixed calling non exists order address->getCountry to getCountryId (by @magexo) + * [#4088](https://github.com/magento/magento2/pull/4088) -- Fix newsletter queue subscribers adding performance (by @DariuszMaciejewski) + * [#6952](https://github.com/magento/magento2/pull/6952) -- Update AccountLock.php (by @klict) + * [#5465](https://github.com/magento/magento2/pull/5465) -- Fix Magento\Review\Model\ResourceModel\Rating\Option not instantiable in setup scripts (by @adragus-inviqa) + * [#7799](https://github.com/magento/magento2/pull/7799) -- Remove duplicate code from template file. (by @dverkade) + * [#7919](https://github.com/magento/magento2/pull/7919) -- Using Dynamic Protocol Concatination (by @brobie) + * [#7921](https://github.com/magento/magento2/pull/7921) -- Removed un-used static version rewrite rule in nginx.conf.sample (by @careys7) + * [#8019](https://github.com/magento/magento2/pull/8019) -- added fr_CH to allowed locales list (by @annapivniak) + * [#8082](https://github.com/magento/magento2/pull/8082) -- issue 8080: Cron configuration loading from DB doesn't work (by @ytorbyk) + * [#8062](https://github.com/magento/magento2/pull/8062) -- Fix theme source model used in widget grid (by @Zefiryn) + * [#8232](https://github.com/magento/magento2/pull/8232) -- Fix notice during DI compilation (by @qrz-io) + * [#8306](https://github.com/magento/magento2/pull/8306) -- Remove warning from setup/src/Magento/Setup/Module/I18n/Dictionary/Writer/Csv.php (by @dmanners) + * [#8185](https://github.com/magento/magento2/pull/8185) -- Fix #7461 using the simplest approach for now (by @lazyguru) + * [#8183](https://github.com/magento/magento2/pull/8183) -- [BUGFIX] Fixed the credit memo guest email (by @nickgraz) + * [#8161](https://github.com/magento/magento2/pull/8161) -- Return focus to search input after closing autocomplete dropdown (by @evktalo) + * [#8155](https://github.com/magento/magento2/pull/8155) -- Correct php doc (by @angelomaragna) + * [#8341](https://github.com/magento/magento2/pull/8341) -- Use better function for 'Continue Shopping' url (by @dmatthew) + * [#8336](https://github.com/magento/magento2/pull/8336) -- fixing time format on admin sales order grid (by @magexo) + * [#8327](https://github.com/magento/magento2/pull/8327) -- Change order of parameters passed to LogicException in AbstractTemplate.php (by @bery) + * [#8307](https://github.com/magento/magento2/pull/8307) -- Allow digits in communication class type definition (by @cmuench) + * [#8354](https://github.com/magento/magento2/pull/8354) -- Display correctly "Add" button label for the block class \Magento\Con… (by @diglin) + * [#8246](https://github.com/magento/magento2/pull/8246) -- Fixes #7723 - saving multi select field in UI component form (by @Zefiryn) + * [#8353](https://github.com/magento/magento2/pull/8353) -- Replace into the layout adminhtml_order_shipment_new.xml block alias … (by @diglin) + * [#8395](https://github.com/magento/magento2/pull/8395) -- Added "editPost" action for customer sections.xml (by @rossluk) + * [#8383](https://github.com/magento/magento2/pull/8383) -- Issue/8382 (by @PascalBrouwers) + * [#8151](https://github.com/magento/magento2/pull/8151) -- Remove "<2.7" constraint on symfony/console (by @nicolas-grekas) + * [#8416](https://github.com/magento/magento2/pull/8416) -- Use configured product attributes in wishlist item collection (by @schmengler) + * [#8414](https://github.com/magento/magento2/pull/8414) -- Replace toGMTString with toUTCString (by @schmengler) + * [#8419](https://github.com/magento/magento2/pull/8419) -- Use page result instead of rendering layout directly in controllers (by @schmengler) + * [#8331](https://github.com/magento/magento2/pull/8331) -- Remove Zend1 Json from Magento Captcha module (by @dmanners) + * [#8252](https://github.com/magento/magento2/pull/8252) -- Customer account edit form: additional info block visible (by @Sylvco) + * [#8405](https://github.com/magento/magento2/pull/8405) -- Remove the unused Ajax/Serializer.php class (by @dmanners) + * [#8402](https://github.com/magento/magento2/pull/8402) -- Remove Zend1 db from captcha module (by @dmanners) + * [#8463](https://github.com/magento/magento2/pull/8463) -- Remove outdated comment (by @evktalo) + * [#8456](https://github.com/magento/magento2/pull/8456) -- Specifically ask for the Json Serializer object Mage Braintree (by @dmanners) + * [#8446](https://github.com/magento/magento2/pull/8446) -- Fix "each()" function call on potentially invalid data (by @giacmir) + * [#5928](https://github.com/magento/magento2/pull/5928) -- prevent double shipping method selection (by @danslo) + * [#8217](https://github.com/magento/magento2/pull/8217) -- Update DataProvider.php (by @redelschaap) + * [#8413](https://github.com/magento/magento2/pull/8413) -- Load translations for area, fixes #8412 (by @fooman) + * [#8356](https://github.com/magento/magento2/pull/8356) -- Remove Zend1 captcha from Magento2 Captcha module (by @dmanners) + * [#8474](https://github.com/magento/magento2/pull/8474) -- Fix for https://github.com/magento/magento2/issues/8287 (by @ericrisler) + * [#8487](https://github.com/magento/magento2/pull/8487) -- Mark the STDO test as skipped (by @dmanners) + * [#3155](https://github.com/magento/magento2/pull/3155) -- Remove unused variables in unit test (by @fooman) + * [#6049](https://github.com/magento/magento2/pull/6049) -- Added typo correction for table name comment (by @atishgoswami) + * [#4370](https://github.com/magento/magento2/pull/4370) -- update Catalog Helper (by @barbarich-p) + * [#4106](https://github.com/magento/magento2/pull/4106) -- Adds support for purging varnish cache based on an X-Pool header (by @davidalger) + * [#7982](https://github.com/magento/magento2/pull/7982) -- Add bin/magento commands to list store/website data (by @convenient) + * [#8434](https://github.com/magento/magento2/pull/8434) -- Problem on mobile when catalog gallery allowfullscreen is false #5808 (by @Crossmotion) + * [#8417](https://github.com/magento/magento2/pull/8417) -- add anonymize ip option for google analytics (by @thomas-villagers) + * [#8498](https://github.com/magento/magento2/pull/8498) -- Product->save() shouldn't be called directly (by @stansm) + * [#8581](https://github.com/magento/magento2/pull/8581) -- Fixed overly bold icons in Firefox Mac (by @TandyCorp) + * [#8481](https://github.com/magento/magento2/pull/8481) -- Remove zend json checkout (by @dmanners) + * [#8518](https://github.com/magento/magento2/pull/8518) -- Change link text from "Report Bugs" to "Report a Bug" (by @Zifius) + * [#8514](https://github.com/magento/magento2/pull/8514) -- Add missing name attributes to catalog_product_view layout xml (by @andrewnoble) + * [#8505](https://github.com/magento/magento2/pull/8505) -- Update the Adminhtml image tree JSON (by @dmanners) + * [#8467](https://github.com/magento/magento2/pull/8467) -- Fix for magento/magento2#8392 (by @kirashet666) + * [#8617](https://github.com/magento/magento2/pull/8617) -- Remove Zend_Json from Customer module (by @dmanners) + * [#8609](https://github.com/magento/magento2/pull/8609) -- [PHP 7.1 Compatibility] Void became a reserved word (by @orlangur) + * [#8611](https://github.com/magento/magento2/pull/8611) -- Fix #8308: test setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetCacheTest.php crashes in debug mode (by @orlangur) + * [#8610](https://github.com/magento/magento2/pull/8610) -- Fix #8315: test setup/src/Magento/Setup/Test/Unit/Module/I18n/Dictionary/Writer/Csv/StdoTest.php crashes in debug mode (by @orlangur) + * [#7339](https://github.com/magento/magento2/pull/7339) -- Fix/xml parser issue (by @dvynograd) + * [#7345](https://github.com/magento/magento2/pull/7345) -- Fix typo (by @mpchadwick) + * [#7406](https://github.com/magento/magento2/pull/7406) -- MAGETWO-60448 (by @vasilii-b) + * [#8000](https://github.com/magento/magento2/pull/8000) -- Set static html fragments as cacheable (by @paveq) + * [#8077](https://github.com/magento/magento2/pull/8077) -- Type cast (by @deriknel) + * [#8278](https://github.com/magento/magento2/pull/8278) -- bug #8277 fixing bug with https downloading. (by @clementbeudot) + * [#8420](https://github.com/magento/magento2/pull/8420) -- Refactor contact module (by @schmengler) + * [#8519](https://github.com/magento/magento2/pull/8519) -- Make "is_required" and "is_visible" properties of telephone, company and fax attributes of addresses configurable (by @avstudnitz) + * [#8537](https://github.com/magento/magento2/pull/8537) -- Fixed missing echo statement in checkout cart coupon template (by @FrankRuis) + * [#8602](https://github.com/magento/magento2/pull/8602) -- Fixed crosssells count always null (by @koenner01) + * [#8593](https://github.com/magento/magento2/pull/8593) -- Fix #7371 (by @rossluk) + * [#8642](https://github.com/magento/magento2/pull/8642) -- Update Save.php (by @josefbehr) + * [#8633](https://github.com/magento/magento2/pull/8633) -- Fix #8632 (by @koenner01) + * [#8513](https://github.com/magento/magento2/pull/8513) -- Replace ext name spaces with dashes (as composer does when storing) (by @AydinHassan) + * [#8668](https://github.com/magento/magento2/pull/8668) -- Add correct return type in order service (by @cmuench) + * [#8677](https://github.com/magento/magento2/pull/8677) -- Fixed Doc Block for the dispatch method of the Rest Controller (by @vrann) + * [#3585](https://github.com/magento/magento2/pull/3585) -- Remove duplicate switchIsFilterable (by @GordonLesti) + * [#8132](https://github.com/magento/magento2/pull/8132) -- Fix incorrect schema definition for price (by @unfunco) + * [#2275](https://github.com/magento/magento2/pull/2275) -- Updated links to point to http://devdocs.magento.com/guides/v2.0 (by @wjarka) + * [#8683](https://github.com/magento/magento2/pull/8683) -- Fixed return type of OrderRepository::getList (by @clementbeudot) + * [#8682](https://github.com/magento/magento2/pull/8682) -- Remove unused argument (by @mfdj) + * [#2185](https://github.com/magento/magento2/pull/2185) -- unused variable (by @barbarich-p) + * [#7894](https://github.com/magento/magento2/pull/7894) -- Fix #7893 (by @andreaspenz) + * [#8623](https://github.com/magento/magento2/pull/8623) -- Fix check for boolean product attributes (by @TKlement) + * [#8678](https://github.com/magento/magento2/pull/8678) -- Fixed Issue #8425 (by @DavidLambauer) + * [#8711](https://github.com/magento/magento2/pull/8711) -- Remove Zend_Json from the persistent module remember me status observer (by @dmanners) + * [#8706](https://github.com/magento/magento2/pull/8706) -- Remove Zend_Json from the unit test in the CustomerImportExport module (by @dmanners) + * [#8723](https://github.com/magento/magento2/pull/8723) -- Add active class to search form wrapper for more theming flexibility (by @andrewkett) + * [#8768](https://github.com/magento/magento2/pull/8768) -- Fix issue #8709 (by @renatocason) + * [#8762](https://github.com/magento/magento2/pull/8762) -- Fix issue #2558 (by @renatocason) + * [#8759](https://github.com/magento/magento2/pull/8759) -- magento/magento2#8618: Apply coupon code button issue on Checkout (by @mcspronko) + * [#8776](https://github.com/magento/magento2/pull/8776) -- Range filter doesn't works with 0 values in admin #7103 (by @giacmir) + * [#7611](https://github.com/magento/magento2/pull/7611) -- Update catalog_rule_form.xml edit labels (by @fernandofauth) + * [#7650](https://github.com/magento/magento2/pull/7650) -- Add host header to varnish cache purge request (by @m0zziter) + * [#7914](https://github.com/magento/magento2/pull/7914) -- FPC JS - Fix for CORS issue (by @OZZlE) + * [#8013](https://github.com/magento/magento2/pull/8013) -- Update resets.html (by @ryantfowler) + * [#8041](https://github.com/magento/magento2/pull/8041) -- Fix USPS Priority Mail to Canada (by @jaywilliams) + * [#8014](https://github.com/magento/magento2/pull/8014) -- Update _resets.less (by @ryantfowler) + * [#8053](https://github.com/magento/magento2/pull/8053) -- Strict checking types during di compilation (by @michalderlatka) + * [#8048](https://github.com/magento/magento2/pull/8048) -- Consistent HTML tags and breaks (by @chickenland) + * [#8056](https://github.com/magento/magento2/pull/8056) -- update allowed container tags (by @steros) + * [#8158](https://github.com/magento/magento2/pull/8158) -- Fix OAuth request helper to support Authorization header value parsing with non-leading OAuth key (by @careys7) + * [#8589](https://github.com/magento/magento2/pull/8589) -- Set correct primary keys for temporary tables in product flat indexer (by @jarnooravainen) + * [#8736](https://github.com/magento/magento2/pull/8736) -- Update Stock.php (by @Corefix) + * [#8119](https://github.com/magento/magento2/pull/8119) -- Throw exception for invalid (missing) template in dev mode (by @convenient) + * [#8690](https://github.com/magento/magento2/pull/8690) -- Fix SALES_ORDER_TAX_ITEM_TAX_ID_ITEM_ID duplicates (by @mimarcel) + * [#8743](https://github.com/magento/magento2/pull/8743) -- Validate PHP classnames in di.xml files via schema (by @ktomk) + * [#8714](https://github.com/magento/magento2/pull/8714) -- Quote values in IN() predicate to avoid cast issues (by @xi-ao) + * [#8835](https://github.com/magento/magento2/pull/8835) -- Replace Zend_Json from the Magento Review module (by @dmanners) + * [#8832](https://github.com/magento/magento2/pull/8832) -- Replace Zend_Json from the Magento Quote module (by @dmanners) + * [#8839](https://github.com/magento/magento2/pull/8839) -- Rename to DataObjectTest (by @mfdj) + * [#2199](https://github.com/magento/magento2/pull/2199) -- Rename admin sidebar Products to Catalog #2060 (by @markoshust) + * [#5620](https://github.com/magento/magento2/pull/5620) -- Remove superfluous method call. (by @maksim-grib) + * [#6767](https://github.com/magento/magento2/pull/6767) -- Removed setting routerlist twice. (by @dverkade) + * [#6257](https://github.com/magento/magento2/pull/6257) -- Fix "none" is not meant to be translated in catalog_product_view layout file (by @azanelli) + * [#7645](https://github.com/magento/magento2/pull/7645) -- Storecode in url changed from default to all (by @bartlubbersen) + * [#7864](https://github.com/magento/magento2/pull/7864) -- Bugfix: Fix for not respected alternative headers in maintenance mode (by @cmuench) + * [#7794](https://github.com/magento/magento2/pull/7794) -- Check return value for getProduct() in getPrice(). (by @pbaylies) + * [#8052](https://github.com/magento/magento2/pull/8052) -- Update PurgeCache.php (by @bery) + * [#8130](https://github.com/magento/magento2/pull/8130) -- Update Options.php (by @redelschaap) + * [#8079](https://github.com/magento/magento2/pull/8079) -- FIX Backend mass delete Sql error (by @asubit) + * [#7234](https://github.com/magento/magento2/pull/7234) -- Lossless images optimalization (by @Igloczek) + * [#8685](https://github.com/magento/magento2/pull/8685) -- [PSR-2 Compliance] Fix #8612: Hundreds of PHPCS-based static tests violations in mainline (by @orlangur) + * [#7568](https://github.com/magento/magento2/pull/7568) -- Minor Update Mysql.php (by @WJdeBaas) + * [#7598](https://github.com/magento/magento2/pull/7598) -- Bugfix for _getProductCollection on a product page (by @evgk) + * [#8886](https://github.com/magento/magento2/pull/8886) -- Fix typo in app/code/Magento/Email/Test/Unit/Model/TemplateTest.php (by @orlangur) + * [#5029](https://github.com/magento/magento2/pull/5029) -- Add default swatch_image placeholder (by @Bartlomiejsz) + * [#6838](https://github.com/magento/magento2/pull/6838) -- Removed preference from di.xml (by @dverkade) + * [#7578](https://github.com/magento/magento2/pull/7578) -- Don't skip attribute options with a value of 0 from the layered navigation (by @dcabrejas) + * [#7615](https://github.com/magento/magento2/pull/7615) -- Fixes duplicate messages shown when adding items to cart (by @comdiler) + * [#7590](https://github.com/magento/magento2/pull/7590) -- Reset skippedRows array in clear method (by @ccasciotti) + * [#7701](https://github.com/magento/magento2/pull/7701) -- Allows you to have 0 as a option (by @Corefix) + * [#7748](https://github.com/magento/magento2/pull/7748) -- Remove _required class from ZIP field (by @dmitryshkolnikov) + * [#7743](https://github.com/magento/magento2/pull/7743) -- MAGETWO-61828: Text swatch "zero" not shown (by @oroskodias) + * [#8883](https://github.com/magento/magento2/pull/8883) -- Fix a typo (by @evgk) + * [#7541](https://github.com/magento/magento2/pull/7541) -- Added "Add / update" comment. Update was missing. (by @gastondisacco) + * [#8808](https://github.com/magento/magento2/pull/8808) -- Change link text from "Report a Bug" to "Report an Issue" (by @Zifius) + * [#8907](https://github.com/magento/magento2/pull/8907) -- Removed unused dependencys (by @ikrs) + * [#8910](https://github.com/magento/magento2/pull/8910) -- Prevent overwriting grunt config (by @Igloczek) + * [#7562](https://github.com/magento/magento2/pull/7562) -- Update AbstractCart.php (by @Corefix) + * [#8766](https://github.com/magento/magento2/pull/8766) -- fix $childrenWrapClass never used (by @slackerzz) + * [#8822](https://github.com/magento/magento2/pull/8822) -- Upgrade PHP CS Fixer to v2 (by @keradus) + * [#8901](https://github.com/magento/magento2/pull/8901) -- Update design_config_form.xml (by @WaPoNe) + * [#8896](https://github.com/magento/magento2/pull/8896) -- Fix all words without " (by @rafaelstz) + * [#8912](https://github.com/magento/magento2/pull/8912) -- magento/magento2#8590: M2.1.4 : ArrayBackend cannot save and Added country regions for Croatia (by @nkajic) + * [#8909](https://github.com/magento/magento2/pull/8909) -- magento/magento2#8863: Malta zipcode validation incomplete (by @mmacinko) + * [#2829](https://github.com/magento/magento2/pull/2829) -- Update final_price.phtml (by @liam-wiltshire) + * [#3869](https://github.com/magento/magento2/pull/3869) -- Optional PHP7.0 Socket Path (by @digimix) + * [#4854](https://github.com/magento/magento2/pull/4854) -- Fix admin menu bug (by @NikolasSumrak) + * [#6400](https://github.com/magento/magento2/pull/6400) -- Fix for Product Attribute's Conditions (by @NikolasSumrak) + * [#6677](https://github.com/magento/magento2/pull/6677) -- Update addCategoriesFilter to return $this (by @maciekpaprocki) + * [#6894](https://github.com/magento/magento2/pull/6894) -- Fixed phpseclib\Net\SFTP constants used in write() method (by @federivo) + * [#7117](https://github.com/magento/magento2/pull/7117) -- Add de_LU and fr_LU languages for Luxembourg (by @ajpevers) + * [#8915](https://github.com/magento/magento2/pull/8915) -- magento/magetno2#8676: I can not translate title attribute in xml fil… (by @DanijelPotocki) + * [#5446](https://github.com/magento/magento2/pull/5446) -- Fix Rest Api - GET /V1/configurable-products/{sku}/children not giving ID in response (by @k-andrew) + * [#6321](https://github.com/magento/magento2/pull/6321) -- Add missing return in resolveShippingRates (by @GordonLesti) + * [#6707](https://github.com/magento/magento2/pull/6707) -- Issue/6706 (by @PascalBrouwers) + * [#6794](https://github.com/magento/magento2/pull/6794) -- Move cache to instance of price box widget (by @JamesonNetworks) + * [#6856](https://github.com/magento/magento2/pull/6856) -- Issue/6855 (by @PascalBrouwers) + * [#6837](https://github.com/magento/magento2/pull/6837) -- Removed argument from di.xml (by @dverkade) + * [#6878](https://github.com/magento/magento2/pull/6878) -- Media attribute folder to be ignored (by @rafaelstz) + * [#6914](https://github.com/magento/magento2/pull/6914) -- Put the contants in the same docblock together (by @dverkade) + * [#6913](https://github.com/magento/magento2/pull/6913) -- Removed commented out line for ignoring coding standards (by @dverkade) + * [#7142](https://github.com/magento/magento2/pull/7142) -- [Framework][Translate] Changed translation order to allow language (by @JSchlarb) + * [#7352](https://github.com/magento/magento2/pull/7352) -- Product export duplicate rows for product with html special chars in data. Bugfix for #7350 (by @comdiler) + * [#8445](https://github.com/magento/magento2/pull/8445) -- Changed name of dispatched object in delete event (by @clementbeudot) + * [#8959](https://github.com/magento/magento2/pull/8959) -- Fixes #2461 (by @ajpevers) + * [#8950](https://github.com/magento/magento2/pull/8950) -- Remove deadcode (by @jipjop) + * [#3469](https://github.com/magento/magento2/pull/3469) -- respect depends declaration in system.xml for form element (by @phoenix-bjoern) + * [#5362](https://github.com/magento/magento2/pull/5362) -- Make CMS directive filtering error be more generic (by @erikhansen) + * [#6354](https://github.com/magento/magento2/pull/6354) -- Newsletter Email fix (by @inettman) + * [#6744](https://github.com/magento/magento2/pull/6744) -- add-product-image-label-bug (by @markpol) + * [#6773](https://github.com/magento/magento2/pull/6773) -- Allow to insert Persian characters for attributes! (by @sIiiS) + * [#6779](https://github.com/magento/magento2/pull/6779) -- Changed documentation of the cache variable (by @dverkade) + * [#6775](https://github.com/magento/magento2/pull/6775) -- Changed constructor to use interface instead of direct classname (by @dverkade) + * [#6971](https://github.com/magento/magento2/pull/6971) -- fix #6961 (by @razbakov) + * [#7097](https://github.com/magento/magento2/pull/7097) -- You -> Your (by @avitex) + * [#7414](https://github.com/magento/magento2/pull/7414) -- Fix typo (by @convenient) + * [#8005](https://github.com/magento/magento2/pull/8005) -- Prevent cross origin iframe content reading (by @Igloczek) + * [#8753](https://github.com/magento/magento2/pull/8753) -- Added Translation for required Data-Attribute (by @DavidLambauer) + * [#8778](https://github.com/magento/magento2/pull/8778) -- magento/magento2: #8765 (by @cavalier79) + * [#8914](https://github.com/magento/magento2/pull/8914) -- magento/magetno2#8529:Typo in error message "Table is not exists" (by @bvrbanec) + * [#2448](https://github.com/magento/magento2/pull/2448) -- Fix Inconsistency (by @srenon) + * [#2093](https://github.com/magento/magento2/pull/2093) -- Remove call to load() in getChildrenCategories method (by @davidalger) + * [#4179](https://github.com/magento/magento2/pull/4179) -- fix typo in Magento_Catalog toolbar less source (by @gil--) + * [#5078](https://github.com/magento/magento2/pull/5078) -- Rename $websiteId to $scopeId (by @flancer64) + * [#5207](https://github.com/magento/magento2/pull/5207) -- Table name fix - rule_customer to salesrule_customer (by @Bartlomiejsz) + * [#5858](https://github.com/magento/magento2/pull/5858) -- Save shipping discount in $total (by @flancer64) + * [#6811](https://github.com/magento/magento2/pull/6811) -- Unable to save subscription checkbox on Admin customer save (by @rich1990) + * [#6839](https://github.com/magento/magento2/pull/6839) -- Changed constructor to use an interface (by @dverkade) + * [#6912](https://github.com/magento/magento2/pull/6912) -- Changed module readme text (by @dverkade) + * [#7262](https://github.com/magento/magento2/pull/7262) -- Replace boolean cast to be able to disable frame, aspect ratio, trans… (by @joost-florijn-kega) + * [#7762](https://github.com/magento/magento2/pull/7762) -- change getId() to getPaymentId() (by @HirokazuNishi) + * [#8769](https://github.com/magento/magento2/pull/8769) -- magento/magento2#7860: Invalid comment for the method __order in Mage… (by @mcspronko) + * [#8917](https://github.com/magento/magento2/pull/8917) -- imagento/magento2#8515: Downloadable product is available for downloa… (by @nazarpadalka) + * [#8908](https://github.com/magento/magento2/pull/8908) -- magento/magento2#8871: Typo in Pull Request Template (by @tomislavsantek) + * [#8989](https://github.com/magento/magento2/pull/8989) -- Remove redundant check in if-condition (by @FabianLauer) + * [#8953](https://github.com/magento/magento2/pull/8953) -- Log level for caught exception (by @flancer64) + * [#8994](https://github.com/magento/magento2/pull/8994) -- Syntax fix (by @rafaelstz) + * [#1895](https://github.com/magento/magento2/pull/1895) -- Fix relative template references in individual Magento modules (by @davidalger) + * [#4224](https://github.com/magento/magento2/pull/4224) -- Update get.php (by @thaiphan) + * [#6567](https://github.com/magento/magento2/pull/6567) -- Always skip hidden files (by @quickshiftin) + * [#6989](https://github.com/magento/magento2/pull/6989) -- Allow extending config variables (by @adragus-inviqa) + * [#7218](https://github.com/magento/magento2/pull/7218) -- Set store id on block only when empty (by @dank00) + * [#7161](https://github.com/magento/magento2/pull/7161) -- Fix a bug resulting in incorrect offsets with dynamic row drag-n-drop functionality (by @navarr) + * [#7664](https://github.com/magento/magento2/pull/7664) -- Fix for "Stock Status" field not disappearing in admin when "Manage Stock" = No (by @comdiler) + * [#8812](https://github.com/magento/magento2/pull/8812) -- Fix count SQL on products sold collection (by @jameshalsall) + * [#8991](https://github.com/magento/magento2/pull/8991) -- Update AbstractModel.php (by @redelschaap) + * [#9001](https://github.com/magento/magento2/pull/9001) -- Fix #3791 (by @quienti) + * [#8998](https://github.com/magento/magento2/pull/8998) -- Fixed empty submenu group in backend menu (by @vovayatsyuk) + * [#8928](https://github.com/magento/magento2/pull/8928) -- Stop $this->validColumnNames array from growing and growing (by @jalogut) + * [#4149](https://github.com/magento/magento2/pull/4149) -- Fix wording of downloadable Products (by @bh-ref) + * [#4674](https://github.com/magento/magento2/pull/4674) -- Refactor repeating logic (by @nevvermind) + * [#4501](https://github.com/magento/magento2/pull/4501) -- Add Crowdin badge - official translations (by @piotrekkaminski) + * [#6243](https://github.com/magento/magento2/pull/6243) -- Set getConnection() as public method (by @flancer64) + * [#6250](https://github.com/magento/magento2/pull/6250) -- Return the same data on exit (by @flancer64) + * [#4844](https://github.com/magento/magento2/pull/4844) -- Fix typo (by @orlangur) + * [#4874](https://github.com/magento/magento2/pull/4874) -- Make NL zipcode pattern less strict (by @tdgroot) + * [#5400](https://github.com/magento/magento2/pull/5400) -- Privacy Policy translation (fixes Issue #2951) (by @MindConflicts) + * [#5671](https://github.com/magento/magento2/pull/5671) -- Fix small typo (by @adragus-inviqa) + * [#6132](https://github.com/magento/magento2/pull/6132) -- Remove an extra space while clearing indexed stock items. (by @nntoan) + * [#6840](https://github.com/magento/magento2/pull/6840) -- Removed unused variable $routerId (by @dverkade) + * [#6834](https://github.com/magento/magento2/pull/6834) -- Removed default values for title, meta description, better labels. (by @paales) + * [#7124](https://github.com/magento/magento2/pull/7124) -- Code documentation corrections (by @evktalo) + * [#7294](https://github.com/magento/magento2/pull/7294) -- Let less continue compilation if file is empty (by @timo-schmid) + * [#8648](https://github.com/magento/magento2/pull/8648) -- Remove the copyright year from file headers (by @jameshalsall) + * [#4897](https://github.com/magento/magento2/pull/4897) -- Schedule generation was broken (by @ajpevers) + * [#5503](https://github.com/magento/magento2/pull/5503) -- ACL titles are swapped (by @yireo) + * [#7344](https://github.com/magento/magento2/pull/7344) -- Fix checking active carrier against store (by @torreytsui) + * [#7221](https://github.com/magento/magento2/pull/7221) -- Typo fix (by @gastondisacco) + * [#8982](https://github.com/magento/magento2/pull/8982) -- Move blank theme dependencies out of Magento_Theme requirejs-config (by @mikeoloughlin) + * [#8930](https://github.com/magento/magento2/pull/8930) -- Improved check when CategoryProcessor attempts to create a new category (by @ccasciotti) + * [#8923](https://github.com/magento/magento2/pull/8923) -- Check of null result value in swatch-renderer.js (by @aholovan) + * [#9013](https://github.com/magento/magento2/pull/9013) -- Added JS Jasmine tests to Travis CI (by @Igloczek) + * [#9039](https://github.com/magento/magento2/pull/9039) -- Translation in adminhtml Import form (by @Nolwennig) + * [#9034](https://github.com/magento/magento2/pull/9034) -- Invalidate and refresh customer data sections on HTTP DELETE requests (by @Vinai) + * [#6322](https://github.com/magento/magento2/pull/6322) -- Admin product edit block getHeader is not used (by @kassner) + * [#7045](https://github.com/magento/magento2/pull/7045) -- In case something wrong with underlying products (by @Will-I4M) + * [#8568](https://github.com/magento/magento2/pull/8568) -- Fix quote's outdated shipping address overwriting PayPal Express shipping address (by @torreytsui) + * [#9057](https://github.com/magento/magento2/pull/9057) -- remove duplicate method call (#9017) (by @will-b) + * [#9080](https://github.com/magento/magento2/pull/9080) -- Fix grammar mistakes with subscriptions - fixes #7498 (by @sambolek) + * [#9076](https://github.com/magento/magento2/pull/9076) -- Fix typo (by @PieterCappelle) + * [#9061](https://github.com/magento/magento2/pull/9061) -- Empty resolvedScopeCodes when config cache is cleaned (by @andreas-wickberg-vaimo) + * [#9044](https://github.com/magento/magento2/pull/9044) -- Remove superfluous character in class (by @tkn98) + * [#9095](https://github.com/magento/magento2/pull/9095) -- Added translation to label argument xml. (by @mrkhoa99) + * [#9108](https://github.com/magento/magento2/pull/9108) -- Redundant expression */1 in crontab.xml (by @giacmir) + * [#9170](https://github.com/magento/magento2/pull/9170) -- Corrected class name in documentation. (by @dfelton) + * [#6778](https://github.com/magento/magento2/pull/6778) -- Changed locator class name for ObjectManager (by @dverkade) + * [#7556](https://github.com/magento/magento2/pull/7556) -- Fix merging nested in view.xml (by @torreytsui) + * [#8903](https://github.com/magento/magento2/pull/8903) -- Include Reply-To name in contact form email header (by @josephmcdermott) + * [#9140](https://github.com/magento/magento2/pull/9140) -- remove duplicate calls to initObjectManager in bootstrap class (by @sivajik34) + * [#9133](https://github.com/magento/magento2/pull/9133) -- Favicon folder added on gitignore (by @rafaelstz) + * [#9204](https://github.com/magento/magento2/pull/9204) -- FPT label not translatable in the totals on the cart page. (by @okorshenko) + * [#5043](https://github.com/magento/magento2/pull/5043) -- Change 'select' to 'query' in props (by @flancer64) + * [#5367](https://github.com/magento/magento2/pull/5367) -- Change pub/.htaccess MAGE_MODE comment (by @erikhansen) + * [#5742](https://github.com/magento/magento2/pull/5742) -- Collection walk method bug fix when specific callback function (by @jalogut) + * [#6385](https://github.com/magento/magento2/pull/6385) -- Replace EE License Placeholder text with filename (by @navarr) + * [#6443](https://github.com/magento/magento2/pull/6443) -- Refactor Option ResourceModel to allow price supporting types to be intercepted (by @navarr) + * [#6772](https://github.com/magento/magento2/pull/6772) -- Changed constructor to use an interface (by @dverkade) + * [#6910](https://github.com/magento/magento2/pull/6910) -- Good practice, license in readme file (by @rafaelstz) + * [#7506](https://github.com/magento/magento2/pull/7506) -- Add configurations for change email templates (by @kassner) + * [#7464](https://github.com/magento/magento2/pull/7464) -- Is Allowed Guest Checkout (by @hungvt) + * [#7900](https://github.com/magento/magento2/pull/7900) -- Setting proper resource name (by @ddattee) + * [#8462](https://github.com/magento/magento2/pull/8462) -- Fix product option files not copying to order dir. (by @evktalo) + * [#8824](https://github.com/magento/magento2/pull/8824) -- Popup-Modal not closing on Safari/Windows (by @Hansschouten) + * [#9062](https://github.com/magento/magento2/pull/9062) -- Upgrade JS dependencies (by @Igloczek) + * [#9084](https://github.com/magento/magento2/pull/9084) -- Fix Google Analytics typo in printing Account Number, fixes #7549 (by @sambolek) + * [#9112](https://github.com/magento/magento2/pull/9112) -- Fix attribute label on product page at different store views (by @tufahu) + * [#9103](https://github.com/magento/magento2/pull/9103) -- Cli info di (by @springerin) + * [#9165](https://github.com/magento/magento2/pull/9165) -- Improved text of exception message in case of error in module's composer.json (by @vovayatsyuk) + * [#9131](https://github.com/magento/magento2/pull/9131) -- Fix to allow Zend_Db_Expr as column default (by @scottsb) + * [#9221](https://github.com/magento/magento2/pull/9221) -- Avoid: Undefined index: value in app/code/Magento/Catalog/Controller/Adminhtml/Product/Attribute/Validate.php on line 157 in Ajax return (by @mhauri) + * [#9215](https://github.com/magento/magento2/pull/9215) -- Remove unused and invalid method (by @adragus-inviqa) + * [#9210](https://github.com/magento/magento2/pull/9210) -- Do not di:compile tests/ folder (by @kassner) + * [#5325](https://github.com/magento/magento2/pull/5325) -- update url guide to v2.0 (by @sIiiS) + * [#6452](https://github.com/magento/magento2/pull/6452) -- Fix Login Popup broken on iPad portrait (by @ihor-sviziev) + * [#9234](https://github.com/magento/magento2/pull/9234) -- Fix indentation in pub/.htaccess file (by @erikhansen) + * [#6266](https://github.com/magento/magento2/pull/6266) -- Change commit to rollBack on fail (by @flancer64) + * [#6792](https://github.com/magento/magento2/pull/6792) -- Make a hardcoded value in Customizable Options interceptable (by @navarr) + * [#9094](https://github.com/magento/magento2/pull/9094) -- Issue #2802, #1146: Fixing sitemap generation folder (by @JosephMaxwell) + * [#9124](https://github.com/magento/magento2/pull/9124) -- Solve issues with API (by @paales) + * [#9247](https://github.com/magento/magento2/pull/9247) -- Fixed layout handle for cms page (by @simpleadm) + * [#9257](https://github.com/magento/magento2/pull/9257) -- Fixed coding standard violations in the Framework\Message namespace (by @dverkade) + * [#9254](https://github.com/magento/magento2/pull/9254) -- Fixed coding standard violations in the Framework\Encryption namespace (by @dverkade) + * [#9253](https://github.com/magento/magento2/pull/9253) -- Fixed coding standard violations in the Framework\Event namespace (by @dverkade) + * [#9250](https://github.com/magento/magento2/pull/9250) -- Fixed coding standard violations in the Framework\Archive namespace (by @dverkade) + * [#9264](https://github.com/magento/magento2/pull/9264) -- Enable/Disable DB query logging commands (by @federivo) + * [#9260](https://github.com/magento/magento2/pull/9260) -- Fixed coding standard violations in Framework\HTTP namespace: (by @dverkade) + * [#9258](https://github.com/magento/magento2/pull/9258) -- Fixed coding standard violations in the Framework\Filesystem namespace (by @dverkade) + * [#9286](https://github.com/magento/magento2/pull/9286) -- [WIP] Varnish Vcl generator command (by @piotrkwiecinski) + * [#9282](https://github.com/magento/magento2/pull/9282) -- Fixed coding standard violations in the Framework\Filter namespace (by @dverkade) + * [#9281](https://github.com/magento/magento2/pull/9281) -- Fixed coding standard violations in Framework\Image namespace (by @dverkade) + * [#9298](https://github.com/magento/magento2/pull/9298) -- Remove php-5.6 environment from travis.yml (by @4quaternion) + * [#4816](https://github.com/magento/magento2/pull/4816) -- Fixed issue with grouped product name column renderer. It (by @wbyrnetx) + * [#5147](https://github.com/magento/magento2/pull/5147) -- Change value-assignment to a setValue call (by @wexo-team) + * [#5411](https://github.com/magento/magento2/pull/5411) -- #5236 fixes "The configuration parameter "componentType" is a required for "advanced_pricing_button" component" (by @Protazy21) + * [#7148](https://github.com/magento/magento2/pull/7148) -- Fix issue 7075 (by @rmsundar1) + * [#9027](https://github.com/magento/magento2/pull/9027) -- Make CSS minifying compatible with calc() CSS function (by @sambolek) + * [#9262](https://github.com/magento/magento2/pull/9262) -- Remove zend json from theme (by @dmanners) + * [#9261](https://github.com/magento/magento2/pull/9261) -- Remove zend json from weee (by @dmanners) + * [#9302](https://github.com/magento/magento2/pull/9302) -- Fixed coding standard violations in the Framework\Module namespace (by @dverkade) + * [#9299](https://github.com/magento/magento2/pull/9299) -- Improved check for attribute codes in "additional_attributes" field (by @ccasciotti) + * [#9293](https://github.com/magento/magento2/pull/9293) -- Deprecate unused navigation-menu.js file in blank theme (by @mikeoloughlin) + * [#9308](https://github.com/magento/magento2/pull/9308) -- Remove unnecessary FQCN in ObserverInterface (by @jameshalsall) + * [#9304](https://github.com/magento/magento2/pull/9304) -- Fixed coding standard violations in all Factory classes located in app/code (by @dverkade) + * [#9303](https://github.com/magento/magento2/pull/9303) -- Fixed coding standard violations in the Framework namespace (by @dverkade) + * [#9318](https://github.com/magento/magento2/pull/9318) -- Fixed coding standard violations in the Framework\Backup namespace (by @dverkade) + * [#9321](https://github.com/magento/magento2/pull/9321) -- Fixed coding standard violations in the Framework\Autoload, Framework\Session & Framework\Webapi namespaces (by @dverkade) + * [#9320](https://github.com/magento/magento2/pull/9320) -- Fixed coding standard violations in the Framework\Cache namespace (by @dverkade) + * [#9319](https://github.com/magento/magento2/pull/9319) -- Fixed coding standard violations in the Framework\Api namespace (by @dverkade) + * [#9334](https://github.com/magento/magento2/pull/9334) -- Fixed coding standard violations in the Framework\Controller, Framework\CSS, Framework\Phrase and Framework\Pricing namespace (by @dverkade) + * [#9330](https://github.com/magento/magento2/pull/9330) -- Fixed coding standard violations in the Framework\Data namespace (by @dverkade) + * [#9329](https://github.com/magento/magento2/pull/9329) -- Fixed coding standard violations in the Framework\Stdlib namespace (by @dverkade) + * [#9328](https://github.com/magento/magento2/pull/9328) -- Fixed coding standard violations in the Framework\Config namespace (by @dverkade) + * [#5372](https://github.com/magento/magento2/pull/5372) -- Fix filesystem permission issues (by @BlackIkeEagle) + * [#9129](https://github.com/magento/magento2/pull/9129) -- Product Wizard: Use result type Layout instead of page layout (by @klein0r) + * [#9352](https://github.com/magento/magento2/pull/9352) -- Fixed coding standard violations in the Framework\File namespace (by @dverkade) + * [#9351](https://github.com/magento/magento2/pull/9351) -- Fixed coding standard violations in the Framework\Locale namespace (by @dverkade) + * [#9350](https://github.com/magento/magento2/pull/9350) -- Fixed coding standard violations in the Framework\App namespace (by @dverkade) + * [#9355](https://github.com/magento/magento2/pull/9355) -- Fixed coding standard violations in the Framework\Test namespace (by @dverkade) + * [#9354](https://github.com/magento/magento2/pull/9354) -- Fixed coding standard violations in the Framework\Translate namespace (by @dverkade) + * [#9353](https://github.com/magento/magento2/pull/9353) -- Fixed coding standard violations in the Framework\DB namespace (by @dverkade) + * [#8955](https://github.com/magento/magento2/pull/8955) -- Remove context aggregation validation (see Issue #6114) (by @Vinai) + * [#9343](https://github.com/magento/magento2/pull/9343) -- Add logging to contact us form (by @JamesonNetworks) + * [#9414](https://github.com/magento/magento2/pull/9414) -- Use loadPlayer requirejs mapping (by @ntoombs19) + * [#9400](https://github.com/magento/magento2/pull/9400) -- Fix addIdFilter method (by @adrian-martinez-interactiv4) + * [#9363](https://github.com/magento/magento2/pull/9363) -- Add ability to inject exception code in LocalizedException (by @adragus-inviqa) + * [#9446](https://github.com/magento/magento2/pull/9446) -- Fix data deletion using the multiple delete command (by @Kenboy) + * [#9539](https://github.com/magento/magento2/pull/9539) -- fix for "Class Magento\Framework\Console\CLI not found" in case sensitive scenarios (by @EObukhovsky) + * [#9514](https://github.com/magento/magento2/pull/9514) -- Fix breadcrumbs extra space (by @VincentMarmiesse) + * [#8409](https://github.com/magento/magento2/pull/8409) -- Allow X-Forwarded-For to have multiple values (by @kassner) + * [#9093](https://github.com/magento/magento2/pull/9093) -- JS Static tests added to CI (ESLint + JSCS) (by @Igloczek) + * [#9091](https://github.com/magento/magento2/pull/9091) -- ESLint errors fix (by @Igloczek) + * [#9285](https://github.com/magento/magento2/pull/9285) -- Replace Zend_Log with Psr\Log\LoggerInterface (by @tdgroot) + * [#9380](https://github.com/magento/magento2/pull/9380) -- Removed unnecessary code and namespaces from import validators (by @ccasciotti) + * [#9540](https://github.com/magento/magento2/pull/9540) -- Removed workaround for old Webkit bug in the TinyMCE editor for selec… (by @hostep) + * [#9549](https://github.com/magento/magento2/pull/9549) -- Selects correct stores value option (by @Corefix) + * [#9574](https://github.com/magento/magento2/pull/9574) -- no need to create customer once u got the quote object (by @sivajik34) + * [#9618](https://github.com/magento/magento2/pull/9618) -- Flip the property assignments for _logger and _fetchStrategy in __wakeup (by @cykirsch) + * [#9617](https://github.com/magento/magento2/pull/9617) -- Exclude unnecessarily duplicated Travis CI build jobs (by @Igloczek) + * [#9622](https://github.com/magento/magento2/pull/9622) -- Zend_Wildfire deprecated, Firephp outdated, magento/magento2#9239 and magento/magento2#9241 (by @SolsWebdesign) + * [#9625](https://github.com/magento/magento2/pull/9625) -- Remove unused plugin (by @elzekool) + * [#9637](https://github.com/magento/magento2/pull/9637) -- Change "wan't" to "want" (by @Leland) + * [#7020](https://github.com/magento/magento2/pull/7020) -- Fixes #7006, sales_order_status_label does not support version control (by @ajpevers) + * [#7456](https://github.com/magento/magento2/pull/7456) -- Remove unused entity_id foreign key (by @mattjbarlow) + * [#7755](https://github.com/magento/magento2/pull/7755) -- Remove redundant check and return early (by @AydinHassan) + * [#9657](https://github.com/magento/magento2/pull/9657) -- Fixes Typo (by @riconeitzel) + * [#4903](https://github.com/magento/magento2/pull/4903) -- Fix undefined offset notice when no order states are set (by @adragus-inviqa) + * [#6344](https://github.com/magento/magento2/pull/6344) -- Zend instead of regex in getGetterReturnType (by @flancer64) + * [#9686](https://github.com/magento/magento2/pull/9686) -- Update scripts.js (by @redelschaap) + * [#9701](https://github.com/magento/magento2/pull/9701) -- Add missing payment info template for PDF generation (by @cmuench) + * [#9697](https://github.com/magento/magento2/pull/9697) -- Configure Travis CI to run functional tests (by @okolesnyk) + * [#9711](https://github.com/magento/magento2/pull/9711) -- Cookie Restriction Mode Overlay should not be cached by Varnish #6455 (by @bka) + * [#9713](https://github.com/magento/magento2/pull/9713) -- stringify cookie value to fix Google Analyitcs Tracking and Cookie Overlay #5596 (by @bka) + * [#6503](https://github.com/magento/magento2/pull/6503) -- Remove breadcrumbs for multistore homepage (by @PingusPepan) + * [#7330](https://github.com/magento/magento2/pull/7330) -- Fix Framework\Data\Collection::each() method (by @Vinai) + * [#8484](https://github.com/magento/magento2/pull/8484) -- Fix swatch-renderer.js product id and isProductViewExist (by @mimarcel) + * [#9348](https://github.com/magento/magento2/pull/9348) -- Replace framework's Zend_Session interface usage with SessionHandlerInterface (by @tdgroot) + * [#9654](https://github.com/magento/magento2/pull/9654) -- magento/magento2#7279 bill-to name and ship-to name truncated to 20 chars (by @SolsWebdesign) + * [#9627](https://github.com/magento/magento2/pull/9627) -- Fix coding standard in Magento AdminNotification module (by @dverkade) + * [#9714](https://github.com/magento/magento2/pull/9714) -- Can't delete last item in cart if Minimum Order is Enable #6151 (by @storbahn) + * [#9717](https://github.com/magento/magento2/pull/9717) -- use payment method name to make checkbox of agreements more unique #6207 (by @bka) + * [#9715](https://github.com/magento/magento2/pull/9715) -- #4272: v2.0.4 Credit memos with adjustment fees cannot be fully refunded with a second credit memo (by @mcspronko) + * [#9344](https://github.com/magento/magento2/pull/9344) -- Explace the direct usage of Zend_Json with a call to the Json Help class (by @dmanners) + * [#9475](https://github.com/magento/magento2/pull/9475) -- Update select.js (by @redelschaap) + * [#9600](https://github.com/magento/magento2/pull/9600) -- Do not hardcode product link types (by @kassner) + * [#9712](https://github.com/magento/magento2/pull/9712) -- Customer with unique attribute can't be saved #7844 (by @storbahn) + * [#9723](https://github.com/magento/magento2/pull/9723) -- Patch to allow multiple filter_url_params to function (by @southerncomputer) + * [#9721](https://github.com/magento/magento2/pull/9721) -- [BUGFIX][6244] Fix Issue with code label display in cart checkout. (by @diglin) + * [#9753](https://github.com/magento/magento2/pull/9753) -- Replace Zend_Json in the configurable product block test (by @dmanners) + * [#9777](https://github.com/magento/magento2/pull/9777) -- Fix for #5897: getIdentities relies on uninitialized collection (by @kassner) + * [#9772](https://github.com/magento/magento2/pull/9772) -- Allow for referenceBlock to include template argument (by @jissereitsma) + * [#9797](https://github.com/magento/magento2/pull/9797) -- Adding logo in media folder (by @rafaelstz) + * [#9409](https://github.com/magento/magento2/pull/9409) -- Add a name to the Composite\Fieldset\Options block directive (by @navarr) + * [#9665](https://github.com/magento/magento2/pull/9665) -- Fix for javascript "mixins" when 'urlArgs' is set in requirejs - issue 8221 (by @thelettuce) + * [#9835](https://github.com/magento/magento2/pull/9835) -- Fixes Mage.Cookies poor performance (by @wujashek) + * [#9430](https://github.com/magento/magento2/pull/9430) -- Fix wrong store id filter (by @mimarcel) + * [#9670](https://github.com/magento/magento2/pull/9670) -- Allow injection of Magento\Catalog\Model\View\Asset\ImageFactory (by @rolftimmermans) + * [#9778](https://github.com/magento/magento2/pull/9778) -- new CLI command: Enable Template Hints (by @miguelbalparda) + * [#9820](https://github.com/magento/magento2/pull/9820) -- [oauth] Fixes #9819 (by @EliasKotlyar) + * [#9859](https://github.com/magento/magento2/pull/9859) -- Removed unused $_customerSession property (by @edenreich) + * [#4450](https://github.com/magento/magento2/pull/4450) -- Add ability to use tree-massactions ("sub-menus") on Sales > Orders grid (by @ikk0) + * [#9368](https://github.com/magento/magento2/pull/9368) -- Redis sess: fix path for persistent_identifier & compression_threshold (by @LukeHandle) + * [#9690](https://github.com/magento/magento2/pull/9690) -- Add froogaloop library as a dependency to load-player module (by @ntoombs19) + * [#9813](https://github.com/magento/magento2/pull/9813) -- Use static:: to support late static bindings in Invoice and Creditmemo (by @jokeputs) + * [#9780](https://github.com/magento/magento2/pull/9780) -- Coupon codes not showing in invoice print out #9216 (by @naouibelgacem) + * [#9872](https://github.com/magento/magento2/pull/9872) -- Fixed issue causing static test failure to report success on Travis (by @davidalger) + * [#9890](https://github.com/magento/magento2/pull/9890) -- Improved error logging when trying to save a product (by @woutersamaey) + * [#9892](https://github.com/magento/magento2/pull/9892) -- Added .DS_Store to .gitignore for Mac users (by @woutersamaey) + * [#9873](https://github.com/magento/magento2/pull/9873) -- Fixes layered navigation options being cached using the wrong store id. (by @hostep) + * [#7405](https://github.com/magento/magento2/pull/7405) -- Update Curl.php (by @redelschaap) + * [#7780](https://github.com/magento/magento2/pull/7780) -- setup:di:compile returns exit code 0 if errors are found (by @pivulic) + * [#9157](https://github.com/magento/magento2/pull/9157) -- Return array of blocks as items instead of array of arrays (by @tkotosz) + * [#9810](https://github.com/magento/magento2/pull/9810) -- Fix bug linked product position not updated if product link already exists (by @jalogut) + * [#9824](https://github.com/magento/magento2/pull/9824) -- Email to a Friend feature (by @WaPoNe) + * [#9823](https://github.com/magento/magento2/pull/9823) -- Return array of pages as items instead of array of arrays (by @tkotosz) + * [#9922](https://github.com/magento/magento2/pull/9922) -- Fixes small backwards incompatibility issue created in MAGETWO-69728 (by @hostep) + * [#4891](https://github.com/magento/magento2/pull/4891) -- Remove faulty index subscription (by @ajpevers) + * [#7758](https://github.com/magento/magento2/pull/7758) -- Throw exception when attribute doesn't exitst (by @AydinHassan) + * [#8879](https://github.com/magento/magento2/pull/8879) -- add middle name to checkout address html templates #8878 (by @ajpevers) + * [#9251](https://github.com/magento/magento2/pull/9251) -- Fixed coding standard violations in the Framework\Validator namespace (by @dverkade) + * [#9525](https://github.com/magento/magento2/pull/9525) -- Fixed the Inconsistent Gift Options checkbox labels #9421 (by @vpiyappan) + * [#9905](https://github.com/magento/magento2/pull/9905) -- Fix composer validation (by @barbazul) + * [#9932](https://github.com/magento/magento2/pull/9932) -- Fix typo in comment (by @avoelkl) + * [#9306](https://github.com/magento/magento2/pull/9306) -- Fix PaymentTokenFactory interface to have the "Interface" at the end of the name. (by @dverkade) + * [#9391](https://github.com/magento/magento2/pull/9391) -- Fix depends per group in system.xml (by @osrecio) + * [#9902](https://github.com/magento/magento2/pull/9902) -- Fix static integrity classes tests in Windows (by @barbazul) + * [#9915](https://github.com/magento/magento2/pull/9915) -- suggestion from #9338: add some command/option to the deploy command to refresh the version (by @ajpevers) + * [#9925](https://github.com/magento/magento2/pull/9925) -- Fix #9924, prefill prefix and suffix in checkout shipping address (by @ajpevers) + * [#9941](https://github.com/magento/magento2/pull/9941) -- By default, show times in admin grids in the store timezone. (by @ajpevers) + * [#9943](https://github.com/magento/magento2/pull/9943) -- Cron uses the wrong timestamp method (by @ajpevers) + * [#9964](https://github.com/magento/magento2/pull/9964) -- Add target attribute to Magento_Ui grid (by @thelettuce) + * [#9973](https://github.com/magento/magento2/pull/9973) -- Fixed coding standard violations in the Magento\Wishlist namespace (by @dverkade) + * [#9974](https://github.com/magento/magento2/pull/9974) -- Fixed coding standard violations in the Magento\Backend namespace (by @dverkade) + * [#9975](https://github.com/magento/magento2/pull/9975) -- Fixed coding standard violations in the Magento\Cms namespace (by @dverkade) + * [#9978](https://github.com/magento/magento2/pull/9978) -- Fixed coding standard violations in the Magento\Authorization Magento\Backup Magento\Captcha Magento\CurrencySymbol and Magento\Dhl namespace (by @dverkade) + * [#8965](https://github.com/magento/magento2/pull/8965) -- Reduce calls to SplFileInfo::realpath() in the Magento\Setup\Module\Di\Code\Reader\ClassesScanner class (by @kschroeder) + * [#9996](https://github.com/magento/magento2/pull/9996) -- Ubuntu Trusty 14.04 images update (by @miguelbalparda) + * [#8784](https://github.com/magento/magento2/pull/8784) -- magento/magento2: #8616 (by @cavalier79) + * [#9939](https://github.com/magento/magento2/pull/9939) -- Retrieve taxes from the correct object (by @fooman) + * [#9957](https://github.com/magento/magento2/pull/9957) -- Instantly apply configuration changes in the cron schedule (by @ajpevers) + * [#9994](https://github.com/magento/magento2/pull/9994) -- Fix mini-cart not emptied for logged out users checking out with PayPal Express (by @driskell) + * [#9082](https://github.com/magento/magento2/pull/9082) -- Get sitemap product images from image cache, if available (by @sambolek) + * [#9786](https://github.com/magento/magento2/pull/9786) -- [#7291] Change the default contact form email template to HTML (by @VincentMarmiesse) + * [#9361](https://github.com/magento/magento2/pull/9361) -- Fixed coding standard violations in the Framework\Model namespace (by @dverkade) + * [#9359](https://github.com/magento/magento2/pull/9359) -- Fixed coding standard violations in the Framework\Interception namespace (by @dverkade) + * [#9358](https://github.com/magento/magento2/pull/9358) -- Fixed coding standard violations in the Framework\Code namespace (by @dverkade) + * [#9429](https://github.com/magento/magento2/pull/9429) -- Fix not detecting current store using store code in url using $storeResolver->getCurrentStoreId() (by @mimarcel) + * [#9362](https://github.com/magento/magento2/pull/9362) -- Fixed coding standard violations in the Framework\ObjectManager namespace (by @dverkade) + * [#9970](https://github.com/magento/magento2/pull/9970) -- Added public methods to make Sitemap model plugin friendly (by @7ochem) + * [#7729](https://github.com/magento/magento2/pull/7729) -- Allow USPS Shipping Methods Without ExtraServices (by @jaywilliams) + * [#9314](https://github.com/magento/magento2/pull/9314) -- Support null value for custom attributes. (by @meng-tian) + * [#10033](https://github.com/magento/magento2/pull/10033) -- Fix for file category image uploader (by @Bartlomiejsz) + * [#10047](https://github.com/magento/magento2/pull/10047) -- Include attribute code in error message (by @lazyguru) + * [#10056](https://github.com/magento/magento2/pull/10056) -- Translate password field placeholder in Checkout (by @mimarcel) + * [#7139](https://github.com/magento/magento2/pull/7139) -- Stickyjs improvements (by @vovayatsyuk) + * [#9681](https://github.com/magento/magento2/pull/9681) -- Issue 9680: Use parent name for variations (by @PascalBrouwers) + * [#10031](https://github.com/magento/magento2/pull/10031) -- Allow option disabling for optgroup binding (by @Bart-art) + * [#10060](https://github.com/magento/magento2/pull/10060) -- Adding escapeHtml to Newsletter phtml (by @rafaelstz) + * [#10062](https://github.com/magento/magento2/pull/10062) -- Fix formatting for USPS Carrier (by @ihor-sviziev) + * [#9672](https://github.com/magento/magento2/pull/9672) -- Revert minimum stability to stable, tasks #4359 (by @ktomk) + * [#9986](https://github.com/magento/magento2/pull/9986) -- Improved type hints and declarations for \Magento\Quote\Model\Quote\Address\Total (by @schmengler) + * [#10082](https://github.com/magento/magento2/pull/10082) -- M2 2266 (by @tzyganu) + * [#10086](https://github.com/magento/magento2/pull/10086) -- Fix condition for autoloader function definitions (by @miromichalicka) + * [#9611](https://github.com/magento/magento2/pull/9611) -- Admin Grid Mass action Select / Unselect All issue #9610 (by @minesh0111) + * [#9726](https://github.com/magento/magento2/pull/9726) -- Remove wrong '_setup' replace when getting DB connection (2) (by @jalogut) + * [#9754](https://github.com/magento/magento2/pull/9754) -- Remove zend json from form elements (by @dmanners) + * [#9992](https://github.com/magento/magento2/pull/9992) -- Make page title in layout files translatable (by @ajpevers) + * [#10052](https://github.com/magento/magento2/pull/10052) -- M2 5381 (by @tzyganu) + * [#1563](https://github.com/magento/magento2/pull/1563) -- Convert long form tags with echo to use short-echo tags (by @davidalger) + * [#4147](https://github.com/magento/magento2/pull/4147) -- Add filename paramenter log (by @fcapua-summa) + * [#10043](https://github.com/magento/magento2/pull/10043) -- Fix trailing slash used in url rewrites (by @ihor-sviziev) + * [#10106](https://github.com/magento/magento2/pull/10106) -- Return URL in getThumbnailUrl instead of nothing (by @samgranger) + * [#3889](https://github.com/magento/magento2/pull/3889) -- Add missing dependencies of magento/framework (by @GordonLesti) + * [#10114](https://github.com/magento/magento2/pull/10114) -- Add missing dependencies of magento/framework (by @okorshenko) + * [#7174](https://github.com/magento/magento2/pull/7174) -- Type hint for \DateTimeInterface instead of \DateTime (by @jameshalsall) + * [#9189](https://github.com/magento/magento2/pull/9189) -- Avoid duplicate ltrim function on not complied mode. (by @sivajik34) + * [#10094](https://github.com/magento/magento2/pull/10094) -- Fix for isoneof condition in catalogrule (by @duckchip) + * [#10105](https://github.com/magento/magento2/pull/10105) -- Add referrerPolicy to Vimeo Video iframe to allow domain-restricted videos (by @davefarthing) + * [#10126](https://github.com/magento/magento2/pull/10126) -- Fix width & height mapping during image upload (by @ihor-sviziev) + * [#10140](https://github.com/magento/magento2/pull/10140) -- Update attribute vat_id frontend_label to make it translatable (by @JeroenVanLeusden) + * [#10149](https://github.com/magento/magento2/pull/10149) -- Fix wrong ACL for Developer Section (by @PascalBrouwers) + * [#10151](https://github.com/magento/magento2/pull/10151) -- Fix Widget saving non-XML entities to layout_update (by @tdgroot) + * [#9588](https://github.com/magento/magento2/pull/9588) -- Support controller src_type for head links (by @kassner) + * [#9904](https://github.com/magento/magento2/pull/9904) -- Fixed pointless exception in logs every time a category with image is saved (by @woutersamaey) + * [#10059](https://github.com/magento/magento2/pull/10059) -- Fix fetching quote item by id (by @mladenilic) + 2.1.0 ============= To get detailed information about changes in Magento 2.1.0, please visit [Magento Community Edition (CE) Release Notes](http://devdocs.magento.com/guides/v2.1/release-notes/ReleaseNotes2.1.0CE.html "Magento Community Edition (CE) Release Notes") diff --git a/COPYING.txt b/COPYING.txt index d2cbcd01539dd..040bdd5f3ce72 100644 --- a/COPYING.txt +++ b/COPYING.txt @@ -1,4 +1,4 @@ -Copyright © 2013-2017 Magento, Inc. +Copyright © 2013-present Magento, Inc. Each Magento source file included in this distribution is licensed under OSL 3.0 or the Magento Enterprise Edition (MEE) license diff --git a/README.md b/README.md index 9b1aa1b7b3e28..e90f6cfac8f8c 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,18 @@ -[![Build Status](https://travis-ci.org/magento/magento2.svg?branch=develop)](https://travis-ci.org/magento/magento2) +[![Build Status](https://travis-ci.org/magento/magento2.svg?branch=2.2-develop)](https://travis-ci.org/magento/magento2) +[![Open Source Helpers](https://www.codetriage.com/magento/magento2/badges/users.svg)](https://www.codetriage.com/magento/magento2) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/magento/magento2?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Crowdin](https://d322cqt584bo4o.cloudfront.net/magento-2/localized.png)](https://crowdin.com/project/magento-2)

Welcome

-Welcome to Magento 2 installation! We're glad you chose to install Magento 2, a cutting edge, feature-rich eCommerce solution that gets results. +Welcome to Magento 2 installation! We're glad you chose to install Magento 2, a cutting-edge, feature-rich eCommerce solution that gets results. ## Magento system requirements -[Magento system requirements](http://devdocs.magento.com/magento-system-requirements.html) +[Magento system requirements](http://devdocs.magento.com/guides/v2.2/install-gde/system-requirements2.html) ## Install Magento To install Magento, see either: * [Magento DevBox](https://magento.com/tech-resources/download), the easiest way to get started with Magento. -* [Installation guide](http://devdocs.magento.com/guides/v2.0/install-gde/bk-install-guide.html) +* [Installation guide](http://devdocs.magento.com/guides/v2.2/install-gde/bk-install-guide.html)

Contributing to the Magento 2 code base

Contributions can take the form of new components or features, changes to existing features, tests, documentation (such as developer guides, user guides, examples, or specifications), bug fixes, optimizations, or just good suggestions. @@ -22,8 +23,8 @@ To learn about issues, click [here][2]. To open an issue, click [here][3]. To suggest documentation improvements, click [here][4]. -[1]: -[2]: +[1]: +[2]: [3]: [4]: @@ -38,8 +39,10 @@ To suggest documentation improvements, click [here][4]. | ![reject](http://devdocs.magento.com/common/images/github_reject.png) | The pull request has been rejected and will not be merged into mainline code. Possible reasons can include but are not limited to: issue has already been fixed in another code contribution, or there is an issue with the code contribution. | | ![bug report](http://devdocs.magento.com/common/images/github_bug.png) | The Magento Team has confirmed that this issue contains the minimum required information to reproduce. | | ![acknowledged](http://devdocs.magento.com/common/images/gitHub_acknowledged.png) | The Magento Team has validated the issue and an internal ticket has been created. | -| ![acknowledged](http://devdocs.magento.com/common/images/github_inProgress.png) | The internal ticket is currently in progress, fix is scheduled to be delivered. | -| ![acknowledged](http://devdocs.magento.com/common/images/github_needsUpdate.png) | The Magento Team needs additional information from the reporter to properly prioritize and process the issue or pull request. | +| ![in progress](http://devdocs.magento.com/common/images/github_inProgress.png) | The internal ticket is currently in progress, fix is scheduled to be delivered. | +| ![needs update](http://devdocs.magento.com/common/images/github_needsUpdate.png) | The Magento Team needs additional information from the reporter to properly prioritize and process the issue or pull request. | + +To learn more about issue gate labels click [here](https://github.com/magento/magento2/wiki/Magento-Issue-Gates)

Reporting security issues

diff --git a/app/.htaccess b/app/.htaccess index 93169e4eb44ff..707c26b075e16 100644 --- a/app/.htaccess +++ b/app/.htaccess @@ -1,2 +1,8 @@ -Order deny,allow -Deny from all + + order allow,deny + deny from all + += 2.4> + Require all denied + + diff --git a/app/bootstrap.php b/app/bootstrap.php index 6701a9f4dd51e..e77c6d432c816 100644 --- a/app/bootstrap.php +++ b/app/bootstrap.php @@ -14,12 +14,12 @@ if (!defined('PHP_VERSION_ID') || !(PHP_VERSION_ID === 70002 || PHP_VERSION_ID === 70004 || PHP_VERSION_ID >= 70006)) { if (PHP_SAPI == 'cli') { echo 'Magento supports 7.0.2, 7.0.4, and 7.0.6 or later. ' . - 'Please read http://devdocs.magento.com/guides/v1.0/install-gde/system-requirements.html'; + 'Please read http://devdocs.magento.com/guides/v2.2/install-gde/system-requirements.html'; } else { echo <<

Magento supports PHP 7.0.2, 7.0.4, and 7.0.6 or later. Please read - + Magento System Requirements. HTML; @@ -49,12 +49,17 @@ unset($_SERVER['ORIG_PATH_INFO']); } -if (!empty($_SERVER['MAGE_PROFILER']) +if ( + (!empty($_SERVER['MAGE_PROFILER']) || file_exists(BP . '/var/profiler.flag')) && isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'text/html') !== false ) { + $profilerFlag = isset($_SERVER['MAGE_PROFILER']) && strlen($_SERVER['MAGE_PROFILER']) + ? $_SERVER['MAGE_PROFILER'] + : trim(file_get_contents(BP . '/var/profiler.flag')); + \Magento\Framework\Profiler::applyConfig( - $_SERVER['MAGE_PROFILER'], + $profilerFlag, BP, !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ); diff --git a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php index 6c0dfd1db7d16..94c7d955f592b 100644 --- a/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php +++ b/app/code/Magento/AdminNotification/Controller/Adminhtml/Notification/MassRemove.php @@ -39,6 +39,6 @@ public function execute() $this->messageManager->addException($e, __("We couldn't remove the messages because of an error.")); } } - $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl($this->getUrl('*'))); + $this->_redirect('adminhtml/*/'); } } diff --git a/app/code/Magento/AdminNotification/composer.json b/app/code/Magento/AdminNotification/composer.json index a3371c702c729..9f6951c477506 100644 --- a/app/code/Magento/AdminNotification/composer.json +++ b/app/code/Magento/AdminNotification/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-admin-notification", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-store": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-media-storage": "100.2.*", @@ -11,7 +11,7 @@ "lib-libxml": "*" }, "type": "magento2-module", - "version": "100.2.0", + "version": "100.2.1", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricing.php b/app/code/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricing.php index 23829d3725119..0e8acb37104e6 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricing.php +++ b/app/code/Magento/AdvancedPricingImportExport/Model/Import/AdvancedPricing.php @@ -394,7 +394,7 @@ protected function saveAndReplaceAdvancedPrices() ? $rowData[self::COL_TIER_PRICE] : 0, 'percentage_value' => $rowData[self::COL_TIER_PRICE_TYPE] === self::TIER_PRICE_TYPE_PERCENT ? $rowData[self::COL_TIER_PRICE] : null, - 'website_id' => $this->getWebsiteId($rowData[self::COL_TIER_PRICE_WEBSITE]) + 'website_id' => $this->getWebSiteId($rowData[self::COL_TIER_PRICE_WEBSITE]) ]; } } diff --git a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php index 5111b4932d7a8..9a380ff75da24 100644 --- a/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php +++ b/app/code/Magento/AdvancedPricingImportExport/Test/Unit/Model/Import/AdvancedPricing/Validator/WebsiteTest.php @@ -27,7 +27,7 @@ class WebsiteTest extends \PHPUnit\Framework\TestCase protected function setUp() { - $this->webSiteModel = $this->getMockBuilder(\Magento\Store\Model\WebSite::class) + $this->webSiteModel = $this->getMockBuilder(\Magento\Store\Model\Website::class) ->setMethods(['getBaseCurrency']) ->disableOriginalConstructor() ->getMock(); diff --git a/app/code/Magento/AdvancedPricingImportExport/composer.json b/app/code/Magento/AdvancedPricingImportExport/composer.json index ec54cfd1e5e62..4712cba1f6105 100644 --- a/app/code/Magento/AdvancedPricingImportExport/composer.json +++ b/app/code/Magento/AdvancedPricingImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-advanced-pricing-import-export", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-catalog": "102.0.*", "magento/module-catalog-inventory": "100.2.*", "magento/module-eav": "101.0.*", @@ -13,7 +13,7 @@ "magento/framework": "101.0.*" }, "type": "magento2-module", - "version": "100.2.0", + "version": "100.2.1", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Analytics/Api/Data/LinkInterface.php b/app/code/Magento/Analytics/Api/Data/LinkInterface.php new file mode 100644 index 0000000000000..6597dff868b9f --- /dev/null +++ b/app/code/Magento/Analytics/Api/Data/LinkInterface.php @@ -0,0 +1,24 @@ +' . $element->getLabel() . ''; + $html .= '

' . $element->getComment() . '
'; + return $this->decorateRowHtml($element, $html); + } + + /** + * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param string $html + * @return string + */ + private function decorateRowHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element, $html) + { + return sprintf( + '
%s
', + $element->getHtmlId(), + $html + ); + } +} diff --git a/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php new file mode 100644 index 0000000000000..34f2b7d53d9be --- /dev/null +++ b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/CollectionTimeLabel.php @@ -0,0 +1,53 @@ +localeResolver = $localeResolver ?: + ObjectManager::getInstance()->get(\Magento\Framework\Locale\ResolverInterface::class); + parent::__construct($context, $data); + } + + /** + * Add current time zone to comment, properly translated according to locale + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @return string + */ + public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) + { + $timeZoneCode = $this->_localeDate->getConfigTimezone(); + $locale = $this->localeResolver->getLocale(); + $getLongTimeZoneName = \IntlTimeZone::createTimeZone($timeZoneCode) + ->getDisplayName(false, \IntlTimeZone::DISPLAY_LONG, $locale); + $element->setData( + 'comment', + sprintf("%s (%s)", $getLongTimeZoneName, $timeZoneCode) + ); + return parent::render($element); + } +} diff --git a/app/code/Magento/Analytics/Block/Adminhtml/System/Config/SubscriptionStatusLabel.php b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/SubscriptionStatusLabel.php new file mode 100644 index 0000000000000..c09213c7f009d --- /dev/null +++ b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/SubscriptionStatusLabel.php @@ -0,0 +1,64 @@ +subscriptionStatusProvider = $labelStatusProvider; + } + + /** + * Add Subscription status to comment + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @return string + */ + public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) + { + $element->setData( + 'comment', + $this->prepareLabelValue() + ); + return parent::render($element); + } + + /** + * Prepare label for subscription status + * + * @return string + */ + private function prepareLabelValue() + { + return __('Subscription status') . ': ' . __($this->subscriptionStatusProvider->getStatus()); + } +} diff --git a/app/code/Magento/Analytics/Block/Adminhtml/System/Config/Vertical.php b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/Vertical.php new file mode 100644 index 0000000000000..99606e10f99d9 --- /dev/null +++ b/app/code/Magento/Analytics/Block/Adminhtml/System/Config/Vertical.php @@ -0,0 +1,41 @@ +' . $element->getHint() . ''; + $html .= '
' . $element->getComment() . '
'; + return $this->decorateRowHtml($element, $html); + } + + /** + * Decorates row HTML for custom element style + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param string $html + * @return string + */ + private function decorateRowHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element, $html) + { + $rowHtml = sprintf('%s', $html); + $rowHtml .= sprintf( + '%s%s', + $element->getHtmlId(), + $element->getLabelHtml($element->getHtmlId(), "[WEBSITE]"), + $element->getElementHtml() + ); + return $rowHtml; + } +} diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/BIEssentials/SignUp.php b/app/code/Magento/Analytics/Controller/Adminhtml/BIEssentials/SignUp.php new file mode 100644 index 0000000000000..a90a971cf41b4 --- /dev/null +++ b/app/code/Magento/Analytics/Controller/Adminhtml/BIEssentials/SignUp.php @@ -0,0 +1,64 @@ +config = $config; + parent::__construct($context); + } + + /** + * Check admin permissions for this controller + * + * @return boolean + */ + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Magento_Analytics::bi_essentials'); + } + + /** + * Provides link to BI Essentials signup + * + * @return \Magento\Framework\Controller\AbstractResult + */ + public function execute() + { + return $this->resultRedirectFactory->create()->setUrl( + $this->config->getValue($this->urlBIEssentialsConfigPath) + ); + } +} diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php b/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php new file mode 100644 index 0000000000000..1b0e5c92420de --- /dev/null +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php @@ -0,0 +1,75 @@ +reportUrlProvider = $reportUrlProvider; + parent::__construct($context); + } + + /** + * Check admin permissions for this controller. + * + * @return boolean + */ + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Magento_Analytics::analytics_settings'); + } + + /** + * Redirect to resource with reports. + * + * @return Redirect $resultRedirect + */ + public function execute() + { + /** @var Redirect $resultRedirect */ + $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + try { + $resultRedirect->setUrl($this->reportUrlProvider->getUrl()); + } catch (SubscriptionUpdateException $e) { + $this->getMessageManager()->addNoticeMessage($e->getMessage()); + $resultRedirect->setPath('adminhtml'); + } catch (LocalizedException $e) { + $this->getMessageManager()->addExceptionMessage($e, $e->getMessage()); + $resultRedirect->setPath('adminhtml'); + } catch (\Exception $e) { + $this->getMessageManager()->addExceptionMessage( + $e, + __('Sorry, there has been an error processing your request. Please try again later.') + ); + $resultRedirect->setPath('adminhtml'); + } + + return $resultRedirect; + } +} diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php new file mode 100644 index 0000000000000..122cf74123cc9 --- /dev/null +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php @@ -0,0 +1,73 @@ +subscriptionHandler = $subscriptionHandler; + parent::__construct($context); + } + + /** + * Check admin permissions for this controller + * + * @return boolean + */ + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Magento_Analytics::analytics_settings'); + } + + /** + * Retry process of subscription. + * + * @return Redirect + */ + public function execute() + { + /** @var Redirect $resultRedirect */ + $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); + try { + $resultRedirect->setPath('adminhtml'); + $this->subscriptionHandler->processEnabled(); + } catch (LocalizedException $e) { + $this->getMessageManager()->addExceptionMessage($e, $e->getMessage()); + } catch (\Exception $e) { + $this->getMessageManager()->addExceptionMessage( + $e, + __('Sorry, there has been an error processing your request. Please try again later.') + ); + } + + return $resultRedirect; + } +} diff --git a/app/code/Magento/Analytics/Cron/CollectData.php b/app/code/Magento/Analytics/Cron/CollectData.php new file mode 100644 index 0000000000000..ff0b3e4f67638 --- /dev/null +++ b/app/code/Magento/Analytics/Cron/CollectData.php @@ -0,0 +1,53 @@ +exportDataHandler = $exportDataHandler; + $this->subscriptionStatus = $subscriptionStatus; + } + + /** + * @return bool + */ + public function execute() + { + if ($this->subscriptionStatus->getStatus() === SubscriptionStatusProvider::ENABLED) { + $this->exportDataHandler->prepareExportData(); + } + + return true; + } +} diff --git a/app/code/Magento/Analytics/Cron/SignUp.php b/app/code/Magento/Analytics/Cron/SignUp.php new file mode 100644 index 0000000000000..c17b9b8c381c3 --- /dev/null +++ b/app/code/Magento/Analytics/Cron/SignUp.php @@ -0,0 +1,101 @@ +connector = $connector; + $this->configWriter = $configWriter; + $this->flagManager = $flagManager; + $this->reinitableConfig = $reinitableConfig; + } + + /** + * Execute scheduled subscription operation + * In case of failure writes message to notifications inbox + * + * @return bool + */ + public function execute() + { + $attemptsCount = $this->flagManager->getFlagData(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + + if (($attemptsCount === null) || ($attemptsCount <= 0)) { + $this->deleteAnalyticsCronExpr(); + $this->flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + return false; + } + + $attemptsCount -= 1; + $this->flagManager->saveFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, $attemptsCount); + $signUpResult = $this->connector->execute('signUp'); + if ($signUpResult === false) { + return false; + } + + $this->deleteAnalyticsCronExpr(); + $this->flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + return true; + } + + /** + * Delete cron schedule setting into config. + * + * Delete cron schedule setting for subscription handler into config and + * re-initialize config cache to avoid auto-generate new schedule items. + * + * @return bool + */ + private function deleteAnalyticsCronExpr() + { + $this->configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); + $this->reinitableConfig->reinit(); + return true; + } +} diff --git a/app/code/Magento/Analytics/Cron/Update.php b/app/code/Magento/Analytics/Cron/Update.php new file mode 100644 index 0000000000000..9062a7bac7551 --- /dev/null +++ b/app/code/Magento/Analytics/Cron/Update.php @@ -0,0 +1,92 @@ +connector = $connector; + $this->configWriter = $configWriter; + $this->reinitableConfig = $reinitableConfig; + $this->flagManager = $flagManager; + $this->analyticsToken = $analyticsToken; + } + + /** + * Execute scheduled update operation + * + * @return bool + */ + public function execute() + { + $result = false; + $attemptsCount = $this->flagManager + ->getFlagData(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE); + + if ($attemptsCount) { + $attemptsCount -= 1; + $result = $this->connector->execute('update'); + } + + if ($result || ($attemptsCount <= 0) || (!$this->analyticsToken->isTokenExist())) { + $this->flagManager + ->deleteFlag(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE); + $this->flagManager->deleteFlag(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE); + $this->configWriter->delete(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH); + $this->reinitableConfig->reinit(); + } + + return $result; + } +} diff --git a/app/code/Magento/Analytics/LICENSE.txt b/app/code/Magento/Analytics/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/app/code/Magento/Analytics/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For 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. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/Analytics/LICENSE_AFL.txt b/app/code/Magento/Analytics/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/Analytics/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For 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. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/Analytics/Model/AnalyticsToken.php b/app/code/Magento/Analytics/Model/AnalyticsToken.php new file mode 100644 index 0000000000000..ccec4d1bbe958 --- /dev/null +++ b/app/code/Magento/Analytics/Model/AnalyticsToken.php @@ -0,0 +1,92 @@ +reinitableConfig = $reinitableConfig; + $this->config = $config; + $this->configWriter = $configWriter; + } + + /** + * Get Magento BI token value. + * + * @return string|null + */ + public function getToken() + { + return $this->config->getValue($this->tokenPath); + } + + /** + * Stores Magento BI token value. + * + * @param string $value + * + * @return bool + */ + public function storeToken($value) + { + $this->configWriter->save($this->tokenPath, $value); + $this->reinitableConfig->reinit(); + + return true; + } + + /** + * Check Magento BI token value exist. + * + * @return bool + */ + public function isTokenExist() + { + return (bool)$this->getToken(); + } +} diff --git a/app/code/Magento/Analytics/Model/Config.php b/app/code/Magento/Analytics/Model/Config.php new file mode 100644 index 0000000000000..ba508187b4b9f --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config.php @@ -0,0 +1,40 @@ +data = $data; + } + + /** + * Get config value by key. + * + * @param string|null $key + * @param string|null $default + * @return array + */ + public function get($key = null, $default = null) + { + return $this->data->get($key, $default); + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Baseurl/SubscriptionUpdateHandler.php b/app/code/Magento/Analytics/Model/Config/Backend/Baseurl/SubscriptionUpdateHandler.php new file mode 100644 index 0000000000000..6e6f008d49f7e --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Backend/Baseurl/SubscriptionUpdateHandler.php @@ -0,0 +1,107 @@ +analyticsToken = $analyticsToken; + $this->flagManager = $flagManager; + $this->reinitableConfig = $reinitableConfig; + $this->configWriter = $configWriter; + } + + /** + * Activate process of subscription update handling. + * + * @param string $url + * @return bool + */ + public function processUrlUpdate(string $url) + { + if ($this->analyticsToken->isTokenExist()) { + if (!$this->flagManager->getFlagData(self::PREVIOUS_BASE_URL_FLAG_CODE)) { + $this->flagManager->saveFlag(self::PREVIOUS_BASE_URL_FLAG_CODE, $url); + } + + $this->flagManager + ->saveFlag(self::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE, $this->attemptsInitValue); + $this->configWriter->save(self::UPDATE_CRON_STRING_PATH, $this->cronExpression); + $this->reinitableConfig->reinit(); + } + + return true; + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Backend/CollectionTime.php b/app/code/Magento/Analytics/Model/Config/Backend/CollectionTime.php new file mode 100644 index 0000000000000..e26ad01fc74bf --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Backend/CollectionTime.php @@ -0,0 +1,91 @@ +configWriter = $configWriter; + parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); + } + + /** + * {@inheritdoc} + * + * {@inheritdoc}. Set schedule setting for cron. + * + * @return Value + */ + public function afterSave() + { + $result = preg_match('#(?\d{2}),(?\d{2}),(?\d{2})#', $this->getValue(), $time); + + if (!$result) { + throw new LocalizedException(__('Time value has an unsupported format')); + } + + $cronExprArray = [ + $time['min'], # Minute + $time['hour'], # Hour + '*', # Day of the Month + '*', # Month of the Year + '*', # Day of the Week + ]; + + $cronExprString = join(' ', $cronExprArray); + + try { + $this->configWriter->save(self::CRON_SCHEDULE_PATH, $cronExprString); + } catch (\Exception $e) { + $this->_logger->error($e->getMessage()); + throw new LocalizedException(__('Cron settings can\'t be saved')); + } + + return parent::afterSave(); + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php b/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php new file mode 100644 index 0000000000000..ac97f2a843e61 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php @@ -0,0 +1,84 @@ +subscriptionHandler = $subscriptionHandler; + parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); + } + + /** + * Add additional handling after config value was saved. + * + * @return Value + * @throws LocalizedException + */ + public function afterSave() + { + try { + if ($this->isValueChanged()) { + $enabled = $this->getData('value'); + + if ($enabled) { + $this->subscriptionHandler->processEnabled(); + } else { + $this->subscriptionHandler->processDisabled(); + } + } + } catch (\Exception $e) { + $this->_logger->error($e->getMessage()); + throw new LocalizedException(__('There was an error save new configuration value.')); + } + + return parent::afterSave(); + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php b/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php new file mode 100644 index 0000000000000..4b125949948c6 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php @@ -0,0 +1,172 @@ +configWriter = $configWriter; + $this->flagManager = $flagManager; + $this->analyticsToken = $analyticsToken; + $this->reinitableConfig = $reinitableConfig; + } + + /** + * Processing of activation MBI subscription. + * + * Activate process of subscription handling if Analytics token is not received. + * + * @return bool + */ + public function processEnabled() + { + if (!$this->analyticsToken->isTokenExist()) { + $this->setCronSchedule(); + $this->setAttemptsFlag(); + $this->reinitableConfig->reinit(); + } + + return true; + } + + /** + * Set cron schedule setting into config for activation of subscription process. + * + * @return bool + */ + private function setCronSchedule() + { + $this->configWriter->save(self::CRON_STRING_PATH, join(' ', self::CRON_EXPR_ARRAY)); + return true; + } + + /** + * Set flag as reserve counter of attempts subscription operation. + * + * @return bool + */ + private function setAttemptsFlag() + { + return $this->flagManager + ->saveFlag(self::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, $this->attemptsInitValue); + } + + /** + * Processing of deactivation MBI subscription. + * + * Disable data collection + * and interrupt subscription handling if Analytics token is not received. + * + * @return bool + */ + public function processDisabled() + { + $this->disableCollectionData(); + + if (!$this->analyticsToken->isTokenExist()) { + $this->unsetAttemptsFlag(); + } + + return true; + } + + /** + * Unset flag of attempts subscription operation. + * + * @return bool + */ + private function unsetAttemptsFlag() + { + return $this->flagManager + ->deleteFlag(self::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + } + + /** + * Unset schedule of collection data cron. + * + * @return bool + */ + private function disableCollectionData() + { + $this->configWriter->delete(CollectionTime::CRON_SCHEDULE_PATH); + + return true; + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Vertical.php b/app/code/Magento/Analytics/Model/Config/Backend/Vertical.php new file mode 100644 index 0000000000000..1aabbb91ddf87 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Backend/Vertical.php @@ -0,0 +1,32 @@ +getValue())) { + throw new LocalizedException(__('Please select a vertical.')); + } + + return $this; + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Mapper.php b/app/code/Magento/Analytics/Model/Config/Mapper.php new file mode 100644 index 0000000000000..504690b8e4763 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Mapper.php @@ -0,0 +1,66 @@ + [ + * 'name' => 'file_name', + * 'providers' => [ + * 'reportProvider' => [ + * 'name' => 'report_provider_name', + * 'class' => 'Magento\Analytics\ReportXml\ReportProvider', + * 'parameters' =>[ + * 'name' => 'report_name', + * ], + * ], + * 'customProvider' => [ + * 'name' => 'custom_provider_name', + * 'class' => 'Magento\Analytics\Model\CustomProvider', + * ], + * ], + * ] + * ]; + */ + public function execute($configData) + { + if (!isset($configData['config'][0]['file'])) { + return []; + } + + $files = []; + foreach ($configData['config'][0]['file'] as $fileData) { + /** just one set of providers is allowed by xsd */ + $providers = reset($fileData['providers']); + foreach ($providers as $providerType => $providerDataSet) { + /** just one set of provider data is allowed by xsd */ + $providerData = reset($providerDataSet); + /** just one set of parameters is allowed by xsd */ + $providerData['parameters'] = !empty($providerData['parameters']) + ? reset($providerData['parameters']) + : []; + $providerData['parameters'] = array_map( + 'reset', + $providerData['parameters'] + ); + $providers[$providerType] = $providerData; + } + $files[$fileData['name']] = $fileData; + $files[$fileData['name']]['providers'] = $providers; + } + return $files; + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Reader.php b/app/code/Magento/Analytics/Model/Config/Reader.php new file mode 100644 index 0000000000000..8980e31627717 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Reader.php @@ -0,0 +1,52 @@ +mapper = $mapper; + $this->readers = $readers; + } + + /** + * Read configuration scope. + * + * @param string|null $scope + * @return array + */ + public function read($scope = null) + { + $data = []; + foreach ($this->readers as $reader) { + $data = array_merge_recursive($data, $reader->read($scope)); + } + + return $this->mapper->execute($data); + } +} diff --git a/app/code/Magento/Analytics/Model/Config/Source/Vertical.php b/app/code/Magento/Analytics/Model/Config/Source/Vertical.php new file mode 100644 index 0000000000000..c9d9582ea7c7a --- /dev/null +++ b/app/code/Magento/Analytics/Model/Config/Source/Vertical.php @@ -0,0 +1,51 @@ +verticals = $verticals; + } + + /** + * {@inheritdoc} + */ + public function toOptionArray() + { + $result = [ + ['value' => '', 'label' => __('--Please Select--')] + ]; + + foreach ($this->verticals as $vertical) { + $result[] = ['value' => $vertical, 'label' => __($vertical)]; + } + + return $result; + } +} diff --git a/app/code/Magento/Analytics/Model/ConfigInterface.php b/app/code/Magento/Analytics/Model/ConfigInterface.php new file mode 100644 index 0000000000000..caaa2e100c1c7 --- /dev/null +++ b/app/code/Magento/Analytics/Model/ConfigInterface.php @@ -0,0 +1,22 @@ + 'command_class_name'. + * + * The list may be configured in each module via '/etc/di.xml'. + * + * @var string[] + */ + private $commands; + + /** + * @var ObjectManagerInterface + */ + private $objectManager; + + /** + * @param array $commands + * @param ObjectManagerInterface $objectManager + */ + public function __construct( + array $commands, + ObjectManagerInterface $objectManager + ) { + $this->commands = $commands; + $this->objectManager = $objectManager; + } + + /** + * Executes a command in accordance with the given name. + * + * @param string $commandName + * @return bool + * @throws NotFoundException if the command is not found. + */ + public function execute($commandName) + { + if (!array_key_exists($commandName, $this->commands)) { + throw new NotFoundException(__('Command was not found.')); + } + + /** @var \Magento\Analytics\Model\Connector\CommandInterface $command */ + $command = $this->objectManager->create($this->commands[$commandName]); + + return $command->execute(); + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/CommandInterface.php b/app/code/Magento/Analytics/Model/Connector/CommandInterface.php new file mode 100644 index 0000000000000..7a8774fe3dba9 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/CommandInterface.php @@ -0,0 +1,21 @@ +curlFactory = $curlFactory; + $this->responseFactory = $responseFactory; + $this->converter = $converter; + $this->logger = $logger; + } + + /** + * {@inheritdoc} + */ + public function request($method, $url, array $body = [], array $headers = [], $version = '1.1') + { + $response = new \Zend_Http_Response(0, []); + + try { + $curl = $this->curlFactory->create(); + $headers = $this->applyContentTypeHeaderFromConverter($headers); + + $curl->write($method, $url, $version, $headers, $this->converter->toBody($body)); + + $result = $curl->read(); + + if ($curl->getErrno()) { + $this->logger->critical( + new \Exception( + sprintf( + 'MBI service CURL connection error #%s: %s', + $curl->getErrno(), + $curl->getError() + ) + ) + ); + + return $response; + } + + $response = $this->responseFactory->create($result); + } catch (\Exception $e) { + $this->logger->critical($e); + } + + return $response; + } + + /** + * @param array $headers + * + * @return array + */ + private function applyContentTypeHeaderFromConverter(array $headers) + { + $contentTypeHeaderKey = array_search($this->converter->getContentTypeHeader(), $headers); + if ($contentTypeHeaderKey === false) { + $headers[] = $this->converter->getContentTypeHeader(); + } + + return $headers; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php new file mode 100644 index 0000000000000..a1e1f057684f6 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php @@ -0,0 +1,29 @@ +converter = $converter; + $this->responseHandlers = $responseHandlers; + } + + /** + * @param \Zend_Http_Response $response + * + * @return bool|string + */ + public function getResult(\Zend_Http_Response $response) + { + $result = false; + $responseBody = $this->converter->fromBody($response->getBody()); + if (array_key_exists($response->getStatus(), $this->responseHandlers)) { + $result = $this->responseHandlers[$response->getStatus()]->handleResponse($responseBody); + } + + return $result; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php new file mode 100644 index 0000000000000..f1a8ea6460f9d --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php @@ -0,0 +1,93 @@ +analyticsToken = $analyticsToken; + $this->httpClient = $httpClient; + $this->config = $config; + $this->responseResolver = $responseResolver; + $this->logger = $logger; + } + + /** + * Notify MBI about that data collection was finished + * + * @return bool + */ + public function execute() + { + $result = false; + if ($this->analyticsToken->isTokenExist()) { + $response = $this->httpClient->request( + ZendClient::POST, + $this->config->getValue($this->notifyDataChangedUrlPath), + [ + "access-token" => $this->analyticsToken->getToken(), + "url" => $this->config->getValue(Store::XML_PATH_SECURE_BASE_URL), + ] + ); + $result = $this->responseResolver->getResult($response); + } + return (bool)$result; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php new file mode 100644 index 0000000000000..dfa283e10d070 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php @@ -0,0 +1,115 @@ +analyticsToken = $analyticsToken; + $this->httpClient = $httpClient; + $this->config = $config; + $this->responseResolver = $responseResolver; + $this->logger = $logger; + } + + /** + * Performs obtaining of an OTP from the MBI service. + * + * Returns received OTP or FALSE in case of failure. + * + * @return string|false + */ + public function call() + { + $result = false; + + if ($this->analyticsToken->isTokenExist()) { + $response = $this->httpClient->request( + ZendClient::POST, + $this->config->getValue($this->otpUrlConfigPath), + [ + "access-token" => $this->analyticsToken->getToken(), + "url" => $this->config->getValue(Store::XML_PATH_SECURE_BASE_URL), + ] + ); + + $result = $this->responseResolver->getResult($response); + if (!$result) { + $this->logger->warning( + sprintf( + 'Obtaining of an OTP from the MBI service has been failed: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); + } + } + + return $result; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php new file mode 100644 index 0000000000000..d9a672e81f43d --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php @@ -0,0 +1,24 @@ +analyticsToken = $analyticsToken; + $this->subscriptionHandler = $subscriptionHandler; + $this->subscriptionStatusProvider = $subscriptionStatusProvider; + } + + /** + * @inheritdoc + */ + public function handleResponse(array $responseBody) + { + if ($this->subscriptionStatusProvider->getStatus() === SubscriptionStatusProvider::ENABLED) { + $this->analyticsToken->storeToken(null); + $this->subscriptionHandler->processEnabled(); + } + return false; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php new file mode 100644 index 0000000000000..b2261e418abc7 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php @@ -0,0 +1,51 @@ +analyticsToken = $analyticsToken; + $this->converter = $converter; + } + + /** + * @inheritdoc + */ + public function handleResponse(array $body) + { + if (isset($body['access-token']) && !empty($body['access-token'])) { + $this->analyticsToken->storeToken($body['access-token']); + return $body['access-token']; + } + + return false; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php new file mode 100644 index 0000000000000..73fc575ae2821 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php @@ -0,0 +1,24 @@ +analyticsToken = $analyticsToken; + $this->integrationManager = $integrationManager; + $this->config = $config; + $this->httpClient = $httpClient; + $this->logger = $logger; + $this->responseResolver = $responseResolver; + } + + /** + * Executes signUp command + * + * During this call Magento generates or retrieves access token for the integration user + * In case successful generation Magento activates user and sends access token to MA + * As the response, Magento receives a token to MA + * Magento stores this token in System Configuration + * + * This method returns true in case of success + * + * @return bool + */ + public function execute() + { + $result = false; + $integrationToken = $this->integrationManager->generateToken(); + if ($integrationToken) { + $this->integrationManager->activateIntegration(); + $response = $this->httpClient->request( + ZendClient::POST, + $this->config->getValue($this->signUpUrlPath), + [ + "token" => $integrationToken->getData('token'), + "url" => $this->config->getValue(Store::XML_PATH_SECURE_BASE_URL), + ] + ); + + $result = $this->responseResolver->getResult($response); + if (!$result) { + $this->logger->warning( + sprintf( + 'Subscription for MBI service has been failed. An error occurred during token exchange: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); + } + } + + return (bool)$result; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php new file mode 100644 index 0000000000000..8f05f1107e87e --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php @@ -0,0 +1,114 @@ +analyticsToken = $analyticsToken; + $this->httpClient = $httpClient; + $this->config = $config; + $this->logger = $logger; + $this->flagManager = $flagManager; + $this->responseResolver = $responseResolver; + } + + /** + * Executes update request to MBI api in case store url was changed + * + * @return bool + */ + public function execute() + { + $result = false; + if ($this->analyticsToken->isTokenExist()) { + $response = $this->httpClient->request( + ZendClient::PUT, + $this->config->getValue($this->updateUrlPath), + [ + "url" => $this->flagManager + ->getFlagData(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE), + "new-url" => $this->config->getValue(Store::XML_PATH_SECURE_BASE_URL), + "access-token" => $this->analyticsToken->getToken(), + ] + ); + $result = $this->responseResolver->getResult($response); + if (!$result) { + $this->logger->warning( + sprintf( + 'Update of the subscription for MBI service has been failed: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); + } + } + + return (bool)$result; + } +} diff --git a/app/code/Magento/Analytics/Model/Cryptographer.php b/app/code/Magento/Analytics/Model/Cryptographer.php new file mode 100644 index 0000000000000..6905eee372ae2 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Cryptographer.php @@ -0,0 +1,130 @@ +analyticsToken = $analyticsToken; + $this->encodedContextFactory = $encodedContextFactory; + } + + /** + * Encrypt input data. + * + * @param string $source + * @return EncodedContext + * @throws LocalizedException + */ + public function encode($source) + { + if (!is_string($source)) { + try { + $source = (string)$source; + } catch (\Exception $e) { + throw new LocalizedException(__('Input data must be string or convertible into string.')); + } + } elseif (!$source) { + throw new LocalizedException(__('Input data must be non-empty string.')); + } + if (!$this->validateCipherMethod($this->cipherMethod)) { + throw new LocalizedException(__('Not valid cipher method.')); + } + $initializationVector = $this->getInitializationVector(); + + $encodedContext = $this->encodedContextFactory->create([ + 'content' => openssl_encrypt( + $source, + $this->cipherMethod, + $this->getKey(), + OPENSSL_RAW_DATA, + $initializationVector + ), + 'initializationVector' => $initializationVector, + ]); + + return $encodedContext; + } + + /** + * Return key for encryption. + * + * @return string + * @throws LocalizedException + */ + private function getKey() + { + $token = $this->analyticsToken->getToken(); + if (!$token) { + throw new LocalizedException(__('Encryption key can\'t be empty.')); + } + return hash('sha256', $token); + } + + /** + * Return established cipher method. + * + * @return string + */ + private function getCipherMethod() + { + return $this->cipherMethod; + } + + /** + * Return each time generated random initialization vector which depends on the cipher method. + * + * @return string + */ + private function getInitializationVector() + { + $ivSize = openssl_cipher_iv_length($this->getCipherMethod()); + return openssl_random_pseudo_bytes($ivSize); + } + + /** + * Check that cipher method is allowed for encryption. + * + * @param string $cipherMethod + * @return bool + */ + private function validateCipherMethod($cipherMethod) + { + $methods = openssl_get_cipher_methods(); + return (false !== array_search($cipherMethod, $methods)); + } +} diff --git a/app/code/Magento/Analytics/Model/EncodedContext.php b/app/code/Magento/Analytics/Model/EncodedContext.php new file mode 100644 index 0000000000000..5fb2d0c15aef7 --- /dev/null +++ b/app/code/Magento/Analytics/Model/EncodedContext.php @@ -0,0 +1,52 @@ +content = $content; + $this->initializationVector = $initializationVector; + } + + /** + * @return string + */ + public function getContent() + { + return $this->content; + } + + /** + * @return string + */ + public function getInitializationVector() + { + return $this->initializationVector; + } +} diff --git a/app/code/Magento/Analytics/Model/Exception/State/SubscriptionUpdateException.php b/app/code/Magento/Analytics/Model/Exception/State/SubscriptionUpdateException.php new file mode 100644 index 0000000000000..5d127037afea9 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Exception/State/SubscriptionUpdateException.php @@ -0,0 +1,17 @@ +filesystem = $filesystem; + $this->archive = $archive; + $this->reportWriter = $reportWriter; + $this->cryptographer = $cryptographer; + $this->fileRecorder = $fileRecorder; + } + + /** + * @inheritdoc + */ + public function prepareExportData() + { + try { + $tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP); + + $this->prepareDirectory($tmpDirectory, $this->getTmpFilesDirRelativePath()); + $this->reportWriter->write($tmpDirectory, $this->getTmpFilesDirRelativePath()); + + $tmpFilesDirectoryAbsolutePath = $this->validateSource($tmpDirectory, $this->getTmpFilesDirRelativePath()); + $archiveAbsolutePath = $this->prepareFileDirectory($tmpDirectory, $this->getArchiveRelativePath()); + $this->pack( + $tmpFilesDirectoryAbsolutePath, + $archiveAbsolutePath + ); + + $this->validateSource($tmpDirectory, $this->getArchiveRelativePath()); + $this->fileRecorder->recordNewFile( + $this->cryptographer->encode($tmpDirectory->readFile($this->getArchiveRelativePath())) + ); + } finally { + $tmpDirectory->delete($this->getTmpFilesDirRelativePath()); + $tmpDirectory->delete($this->getArchiveRelativePath()); + } + + return true; + } + + /** + * Return relative path to a directory for temporary files with reports data. + * + * @return string + */ + private function getTmpFilesDirRelativePath() + { + return $this->subdirectoryPath . 'tmp/'; + } + + /** + * Return relative path to a directory for an archive. + * + * @return string + */ + private function getArchiveRelativePath() + { + return $this->subdirectoryPath . $this->archiveName; + } + + /** + * Clean up a directory. + * + * @param WriteInterface $directory + * @param string $path + * @return string + */ + private function prepareDirectory(WriteInterface $directory, $path) + { + $directory->delete($path); + + return $directory->getAbsolutePath($path); + } + + /** + * Remove a file and a create parent directory a file. + * + * @param WriteInterface $directory + * @param string $path + * @return string + */ + private function prepareFileDirectory(WriteInterface $directory, $path) + { + $directory->delete($path); + if (dirname($path) !== '.') { + $directory->create(dirname($path)); + } + + return $directory->getAbsolutePath($path); + } + + /** + * Packing data into an archive. + * + * @param string $source + * @param string $destination + * @return bool + */ + private function pack($source, $destination) + { + $this->archive->pack( + $source, + $destination, + is_dir($source) ?: false + ); + + return true; + } + + /** + * Validate that data source exist. + * + * Return absolute path in a validated data source. + * + * @param WriteInterface $directory + * @param string $path + * @return string + * @throws LocalizedException If source is not exist. + */ + private function validateSource(WriteInterface $directory, $path) + { + if (!$directory->isExist($path)) { + throw new LocalizedException(__('Source "%1" is not exist', $directory->getAbsolutePath($path))); + } + + return $directory->getAbsolutePath($path); + } +} diff --git a/app/code/Magento/Analytics/Model/ExportDataHandlerInterface.php b/app/code/Magento/Analytics/Model/ExportDataHandlerInterface.php new file mode 100644 index 0000000000000..65efb33659c89 --- /dev/null +++ b/app/code/Magento/Analytics/Model/ExportDataHandlerInterface.php @@ -0,0 +1,19 @@ +exportDataHandler = $exportDataHandler; + $this->analyticsConnector = $connector; + } + + /** + * {@inheritdoc} + * Execute notification command. + * + * @return bool + */ + public function prepareExportData() + { + $result = $this->exportDataHandler->prepareExportData(); + $this->analyticsConnector->execute('notifyDataChanged'); + return $result; + } +} diff --git a/app/code/Magento/Analytics/Model/FileInfo.php b/app/code/Magento/Analytics/Model/FileInfo.php new file mode 100644 index 0000000000000..19bdaf21b2a20 --- /dev/null +++ b/app/code/Magento/Analytics/Model/FileInfo.php @@ -0,0 +1,52 @@ +path = $path; + $this->initializationVector = $initializationVector; + } + + /** + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * @return string + */ + public function getInitializationVector() + { + return $this->initializationVector; + } +} diff --git a/app/code/Magento/Analytics/Model/FileInfoManager.php b/app/code/Magento/Analytics/Model/FileInfoManager.php new file mode 100644 index 0000000000000..e37700e665420 --- /dev/null +++ b/app/code/Magento/Analytics/Model/FileInfoManager.php @@ -0,0 +1,123 @@ +flagManager = $flagManager; + $this->fileInfoFactory = $fileInfoFactory; + } + + /** + * Save FileInfo object. + * + * @param FileInfo $fileInfo + * @return bool + * @throws LocalizedException + */ + public function save(FileInfo $fileInfo) + { + $parameters = []; + $parameters['initializationVector'] = $fileInfo->getInitializationVector(); + $parameters['path'] = $fileInfo->getPath(); + + $emptyParameters = array_diff($parameters, array_filter($parameters)); + if ($emptyParameters) { + throw new LocalizedException( + __('These arguments can\'t be empty "%1"', implode(', ', array_keys($emptyParameters))) + ); + } + + foreach ($this->encodedParameters as $encodedParameter) { + $parameters[$encodedParameter] = $this->encodeValue($parameters[$encodedParameter]); + } + + $this->flagManager->saveFlag($this->flagCode, $parameters); + + return true; + } + + /** + * Load FileInfo object. + * + * @return FileInfo + */ + public function load() + { + $parameters = $this->flagManager->getFlagData($this->flagCode) ?: []; + + $encodedParameters = array_intersect($this->encodedParameters, array_keys($parameters)); + foreach ($encodedParameters as $encodedParameter) { + $parameters[$encodedParameter] = $this->decodeValue($parameters[$encodedParameter]); + } + + $fileInfo = $this->fileInfoFactory->create($parameters); + + return $fileInfo; + } + + /** + * Encode value. + * + * @param string $value + * @return string + */ + private function encodeValue($value) + { + return base64_encode($value); + } + + /** + * Decode value. + * + * @param string $value + * @return string + */ + private function decodeValue($value) + { + return base64_decode($value); + } +} diff --git a/app/code/Magento/Analytics/Model/FileRecorder.php b/app/code/Magento/Analytics/Model/FileRecorder.php new file mode 100644 index 0000000000000..70438a98d56f1 --- /dev/null +++ b/app/code/Magento/Analytics/Model/FileRecorder.php @@ -0,0 +1,136 @@ +fileInfoManager = $fileInfoManager; + $this->fileInfoFactory = $fileInfoFactory; + $this->filesystem = $filesystem; + } + + /** + * Save new encrypted file, register it and remove old registered file. + * + * @param EncodedContext $encodedContext + * @return bool + */ + public function recordNewFile(EncodedContext $encodedContext) + { + $directory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA); + + $fileRelativePath = $this->getFileRelativePath(); + $directory->writeFile($fileRelativePath, $encodedContext->getContent()); + + $fileInfo = $this->fileInfoManager->load(); + $this->registerFile($encodedContext, $fileRelativePath); + $this->removeOldFile($fileInfo, $directory); + + return true; + } + + /** + * Return relative path to encoded file. + * + * @return string + */ + private function getFileRelativePath() + { + return $this->fileSubdirectoryPath . hash('sha256', time()) + . '/' . $this->encodedFileName; + } + + /** + * Register encoded file. + * + * @param EncodedContext $encodedContext + * @param string $fileRelativePath + * @return bool + */ + private function registerFile(EncodedContext $encodedContext, $fileRelativePath) + { + $newFileInfo = $this->fileInfoFactory->create( + [ + 'path' => $fileRelativePath, + 'initializationVector' => $encodedContext->getInitializationVector(), + ] + ); + $this->fileInfoManager->save($newFileInfo); + + return true; + } + + /** + * Remove previously registered file. + * + * @param FileInfo $fileInfo + * @param WriteInterface $directory + * @return bool + */ + private function removeOldFile(FileInfo $fileInfo, WriteInterface $directory) + { + if (!$fileInfo->getPath()) { + return true; + } + + $directory->delete($fileInfo->getPath()); + + $directoryName = dirname($fileInfo->getPath()); + if ($directoryName !== '.') { + $directory->delete($directoryName); + } + + return true; + } +} diff --git a/app/code/Magento/Analytics/Model/IntegrationManager.php b/app/code/Magento/Analytics/Model/IntegrationManager.php new file mode 100644 index 0000000000000..61a40a955e026 --- /dev/null +++ b/app/code/Magento/Analytics/Model/IntegrationManager.php @@ -0,0 +1,126 @@ +integrationService = $integrationService; + $this->config = $config; + $this->oauthService = $oauthService; + } + + /** + * Activate predefined integration user + * + * @return bool + * @throws NoSuchEntityException + */ + public function activateIntegration() + { + $integration = $this->integrationService->findByName( + $this->config->getConfigDataValue('analytics/integration_name') + ); + if (!$integration->getId()) { + throw new NoSuchEntityException(__('Cannot find predefined integration user!')); + } + $integrationData = $this->getIntegrationData(Integration::STATUS_ACTIVE); + $integrationData['integration_id'] = $integration->getId(); + $this->integrationService->update($integrationData); + return true; + } + + /** + * This method execute Generate Token command and enable integration + * + * @return bool|\Magento\Integration\Model\Oauth\Token + */ + public function generateToken() + { + $consumerId = $this->generateIntegration()->getConsumerId(); + $accessToken = $this->oauthService->getAccessToken($consumerId); + if (!$accessToken && $this->oauthService->createAccessToken($consumerId, true)) { + $accessToken = $this->oauthService->getAccessToken($consumerId); + } + return $accessToken; + } + + /** + * Returns consumer Id for MA integration user + * + * @return \Magento\Integration\Model\Integration + */ + private function generateIntegration() + { + $integration = $this->integrationService->findByName( + $this->config->getConfigDataValue('analytics/integration_name') + ); + if (!$integration->getId()) { + $integration = $this->integrationService->create($this->getIntegrationData()); + } + return $integration; + } + + /** + * Returns default attributes for MA integration user + * + * @param int $status + * @return array + */ + private function getIntegrationData($status = Integration::STATUS_INACTIVE) + { + $integrationData = [ + 'name' => $this->config->getConfigDataValue('analytics/integration_name'), + 'status' => $status, + 'all_resources' => false, + 'resource' => [ + 'Magento_Analytics::analytics', + 'Magento_Analytics::analytics_api' + ], + ]; + return $integrationData; + } +} diff --git a/app/code/Magento/Analytics/Model/Link.php b/app/code/Magento/Analytics/Model/Link.php new file mode 100644 index 0000000000000..4a40796df4fd0 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Link.php @@ -0,0 +1,54 @@ +url = $url; + $this->initializationVector = $initializationVector; + } + + /** + * @return string + */ + public function getUrl() + { + return $this->url; + } + + /** + * @return string + */ + public function getInitializationVector() + { + return $this->initializationVector; + } +} diff --git a/app/code/Magento/Analytics/Model/LinkProvider.php b/app/code/Magento/Analytics/Model/LinkProvider.php new file mode 100644 index 0000000000000..2474653f4916c --- /dev/null +++ b/app/code/Magento/Analytics/Model/LinkProvider.php @@ -0,0 +1,87 @@ +linkFactory = $linkFactory; + $this->fileInfoManager = $fileInfoManager; + $this->storeManager = $storeManager; + } + + /** + * Returns base url to file according to store configuration + * + * @param FileInfo $fileInfo + * @return string + */ + private function getBaseUrl(FileInfo $fileInfo) + { + return $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA) . $fileInfo->getPath(); + } + + /** + * Verify is requested file ready + * + * @param FileInfo $fileInfo + * @return bool + */ + private function isFileReady(FileInfo $fileInfo) + { + return $fileInfo->getPath() && $fileInfo->getInitializationVector(); + } + + /** + * @inheritdoc + */ + public function get() + { + $fileInfo = $this->fileInfoManager->load(); + if (!$this->isFileReady($fileInfo)) { + throw new NoSuchEntityException(__('File is not ready yet.')); + } + return $this->linkFactory->create( + [ + 'url' => $this->getBaseUrl($fileInfo), + 'initializationVector' => base64_encode($fileInfo->getInitializationVector()) + ] + ); + } +} diff --git a/app/code/Magento/Analytics/Model/Plugin/BaseUrlConfigPlugin.php b/app/code/Magento/Analytics/Model/Plugin/BaseUrlConfigPlugin.php new file mode 100644 index 0000000000000..174272614fb19 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Plugin/BaseUrlConfigPlugin.php @@ -0,0 +1,61 @@ +subscriptionUpdateHandler = $subscriptionUpdateHandler; + } + + /** + * Add additional handling after config value was saved. + * + * @param Value $subject + * @param Value $result + * @return Value + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function afterAfterSave( + Value $subject, + Value $result + ) { + if ($this->isPluginApplicable($result)) { + $this->subscriptionUpdateHandler->processUrlUpdate($result->getOldValue()); + } + + return $result; + } + + /** + * @param Value $result + * @return bool + */ + private function isPluginApplicable(Value $result) + { + return $result->isValueChanged() + && ($result->getPath() === Store::XML_PATH_SECURE_BASE_URL) + && ($result->getScope() === ScopeConfigInterface::SCOPE_TYPE_DEFAULT); + } +} diff --git a/app/code/Magento/Analytics/Model/ProviderFactory.php b/app/code/Magento/Analytics/Model/ProviderFactory.php new file mode 100644 index 0000000000000..3a23430fca077 --- /dev/null +++ b/app/code/Magento/Analytics/Model/ProviderFactory.php @@ -0,0 +1,39 @@ +objectManager = $objectManager; + } + + /** + * @param string $providerName + * @return object + */ + public function create($providerName) + { + return $this->objectManager->get($providerName); + } +} diff --git a/app/code/Magento/Analytics/Model/ReportUrlProvider.php b/app/code/Magento/Analytics/Model/ReportUrlProvider.php new file mode 100644 index 0000000000000..e7fdf6f9e8132 --- /dev/null +++ b/app/code/Magento/Analytics/Model/ReportUrlProvider.php @@ -0,0 +1,94 @@ +analyticsToken = $analyticsToken; + $this->otpRequest = $otpRequest; + $this->config = $config; + $this->flagManager = $flagManager; + } + + /** + * Provide URL on resource with reports. + * + * @return string + * @throws SubscriptionUpdateException + */ + public function getUrl() + { + if ($this->flagManager->getFlagData(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE)) { + throw new SubscriptionUpdateException(__( + 'Your Base URL has been changed and your reports are being updated. ' + . 'Advanced Reporting will be available once this change has been processed. Please try again later.' + )); + } + + $url = $this->config->getValue($this->urlReportConfigPath); + if ($this->analyticsToken->isTokenExist()) { + $otp = $this->otpRequest->call(); + if ($otp) { + $query = http_build_query(['otp' => $otp], '', '&'); + $url .= '?' . $query; + } + } + + return $url; + } +} diff --git a/app/code/Magento/Analytics/Model/ReportWriter.php b/app/code/Magento/Analytics/Model/ReportWriter.php new file mode 100644 index 0000000000000..7128658947908 --- /dev/null +++ b/app/code/Magento/Analytics/Model/ReportWriter.php @@ -0,0 +1,101 @@ +config = $config; + $this->reportValidator = $reportValidator; + $this->providerFactory = $providerFactory; + } + + /** + * {@inheritdoc} + */ + public function write(WriteInterface $directory, $path) + { + $errorsList = []; + foreach ($this->config->get() as $file) { + $provider = reset($file['providers']); + if (isset($provider['parameters']['name'])) { + $error = $this->reportValidator->validate($provider['parameters']['name']); + if ($error) { + $errorsList[] = $error; + continue; + } + } + /** @var $providerObject */ + $providerObject = $this->providerFactory->create($provider['class']); + $fileName = $provider['parameters'] ? $provider['parameters']['name'] : $provider['name']; + $fileFullPath = $path . $fileName . '.csv'; + $fileData = $providerObject->getReport(...array_values($provider['parameters'])); + $stream = $directory->openFile($fileFullPath, 'w+'); + $stream->lock(); + $headers = []; + foreach ($fileData as $row) { + if (!$headers) { + $headers = array_keys($row); + $stream->writeCsv($headers); + } + $stream->writeCsv($row); + } + $stream->unlock(); + $stream->close(); + } + if ($errorsList) { + $errorStream = $directory->openFile($path . $this->errorsFileName, 'w+'); + foreach ($errorsList as $error) { + $errorStream->lock(); + $errorStream->writeCsv($error); + $errorStream->unlock(); + } + $errorStream->close(); + } + + return true; + } +} diff --git a/app/code/Magento/Analytics/Model/ReportWriterInterface.php b/app/code/Magento/Analytics/Model/ReportWriterInterface.php new file mode 100644 index 0000000000000..a611095a47ae4 --- /dev/null +++ b/app/code/Magento/Analytics/Model/ReportWriterInterface.php @@ -0,0 +1,28 @@ +moduleManager = $moduleManager; + } + + /** + * Returns module with module status + * + * @return array + */ + public function current() + { + $current = parent::current(); + if (is_array($current) && isset($current['module_name'])) { + $current['status'] = + $this->moduleManager->isEnabled($current['module_name']) == 1 ? 'Enabled' : "Disabled"; + } + return $current; + } +} diff --git a/app/code/Magento/Analytics/Model/StoreConfigurationProvider.php b/app/code/Magento/Analytics/Model/StoreConfigurationProvider.php new file mode 100644 index 0000000000000..0d226a9de7dc2 --- /dev/null +++ b/app/code/Magento/Analytics/Model/StoreConfigurationProvider.php @@ -0,0 +1,102 @@ +scopeConfig = $scopeConfig; + $this->configPaths = $configPaths; + $this->storeManager = $storeManager; + } + + /** + * Generates report using config paths from di.xml + * For each website and store + * @return \IteratorIterator + */ + public function getReport() + { + $configReport = $this->generateReportForScope(ScopeConfigInterface::SCOPE_TYPE_DEFAULT, 0); + + /** @var WebsiteInterface $website */ + foreach ($this->storeManager->getWebsites() as $website) { + $configReport = array_merge( + $this->generateReportForScope(ScopeInterface::SCOPE_WEBSITES, $website->getId()), + $configReport + ); + } + + /** @var StoreInterface $store */ + foreach ($this->storeManager->getStores() as $store) { + $configReport = array_merge( + $this->generateReportForScope(ScopeInterface::SCOPE_STORES, $store->getId()), + $configReport + ); + } + return new \IteratorIterator(new \ArrayIterator($configReport)); + } + + /** + * Creates report from config for scope type and scope id. + * + * @param string $scope + * @param int $scopeId + * @return array + */ + private function generateReportForScope($scope, $scopeId) + { + $report = []; + foreach ($this->configPaths as $configPath) { + $report[] = [ + "config_path" => $configPath, + "scope" => $scope, + "scope_id" => $scopeId, + "value" => $this->scopeConfig->getValue( + $configPath, + $scope, + $scopeId + ) + ]; + } + return $report; + } +} diff --git a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php new file mode 100644 index 0000000000000..1dd831a672faa --- /dev/null +++ b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php @@ -0,0 +1,120 @@ +scopeConfig = $scopeConfig; + $this->analyticsToken = $analyticsToken; + $this->flagManager = $flagManager; + } + + /** + * Retrieve subscription status to Magento BI Advanced Reporting. + * + * Statuses: + * Enabled - if subscription is enabled and MA token was received; + * Pending - if subscription is enabled and MA token was not received; + * Disabled - if subscription is not enabled. + * Failed - if subscription is enabled and token was not received after attempts ended. + * + * @return string + */ + public function getStatus() + { + $isSubscriptionEnabledInConfig = $this->scopeConfig->getValue('analytics/subscription/enabled'); + if ($isSubscriptionEnabledInConfig) { + return $this->getStatusForEnabledSubscription(); + } + + return $this->getStatusForDisabledSubscription(); + } + + /** + * Retrieve status for subscription that enabled in config. + * + * @return string + */ + public function getStatusForEnabledSubscription() + { + $status = static::ENABLED; + if ($this->flagManager->getFlagData(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE)) { + $status = self::PENDING; + } + + if (!$this->analyticsToken->isTokenExist()) { + $status = static::PENDING; + if ($this->flagManager->getFlagData(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE) === null) { + $status = static::FAILED; + } + } + + return $status; + } + + /** + * Retrieve status for subscription that disabled in config. + * + * @return string + */ + public function getStatusForDisabledSubscription() + { + return static::DISABLED; + } +} diff --git a/app/code/Magento/Analytics/Model/System/Message/NotificationAboutFailedSubscription.php b/app/code/Magento/Analytics/Model/System/Message/NotificationAboutFailedSubscription.php new file mode 100644 index 0000000000000..9aaa2ebb3b56f --- /dev/null +++ b/app/code/Magento/Analytics/Model/System/Message/NotificationAboutFailedSubscription.php @@ -0,0 +1,80 @@ +subscriptionStatusProvider = $subscriptionStatusProvider; + $this->urlBuilder = $urlBuilder; + } + + /** + * @inheritdoc + * + * @codeCoverageIgnore + */ + public function getIdentity() + { + return hash('sha256', 'ANALYTICS_NOTIFICATION'); + } + + /** + * {@inheritdoc} + */ + public function isDisplayed() + { + return $this->subscriptionStatusProvider->getStatus() === SubscriptionStatusProvider::FAILED; + } + + /** + * {@inheritdoc} + */ + public function getText() + { + $messageDetails = ''; + + $messageDetails .= __('Failed to synchronize data to the Magento Business Intelligence service. '); + $messageDetails .= __( + 'Retry Synchronization', + $this->urlBuilder->getUrl('analytics/subscription/retry') + ); + + return $messageDetails; + } + + /** + * @inheritdoc + * + * @codeCoverageIgnore + */ + public function getSeverity() + { + return self::SEVERITY_MAJOR; + } +} diff --git a/app/code/Magento/Analytics/README.md b/app/code/Magento/Analytics/README.md new file mode 100644 index 0000000000000..7ec64abcd9b86 --- /dev/null +++ b/app/code/Magento/Analytics/README.md @@ -0,0 +1,41 @@ +# Magento_Analytics Module + +The Magento_Analytics module integrates your Magento instance with the [Magento Business Intelligence (MBI)](https://magento.com/products/business-intelligence) to use [Advanced Reporting](http://devdocs.magento.com/guides/v2.2/advanced-reporting/modules.html) functionality. + +The module implements the following functionality: + +* enabling subscription to the MBI and automatic re-subscription +* changing the base URL with the same MBI account remained +* declaring the configuration schemas for report data collection +* collecting the Magento instance data as reports for the MBI +* introducing API that provides the collected data +* extending Magento configuration with the module parameters: + * subscription status (enabled/disabled) + * industry (a business area in which the instance website works) + * time of data collection (time of the day when the module collects data) + +## Structure + +Beyond the [usual module file structure](http://devdocs.magento.com/guides/v2.2/architecture/archi_perspectives/components/modules/mod_intro.html) the module contains a directory `ReportXml`. +[Report XML](http://devdocs.magento.com/guides/v2.2/advanced-reporting/report-xml.html) is a markup language used to build reports for Advanced Reporting. +The language declares SQL queries using XML declaration. + +## Subscription Process + +The subscription to the MBI service is enabled during the installation process of the Analytics module. Each administrator will be notified of these new features upon their initial login to the Admin Panel. + +## Analytics Settings + +Configuration settings for the Analytics module can be modified in the Admin Panel on the Stores > Configuration page under the General > Advanced Reporting tab. + +The following options can be adjusted: +* Advanced Reporting Service (Enabled/Disabled) + * Alters the status of the Advanced Reporting subscription +* Time of day to send data (Hour/Minute/Second in the store's time zone) + * Defines when the data collection process for the Advanced Reporting service occurs +* Industry + * Defines the industry of the store in order to create a personalized Advanced Reporting experience + +## Extensibility + +We do not recommend to extend the Magento_Analytics module. It introduces an API that is purposed to transfer the collected data. Note that the API cannot be used for other needs. diff --git a/app/code/Magento/Analytics/ReportXml/Config.php b/app/code/Magento/Analytics/ReportXml/Config.php new file mode 100644 index 0000000000000..f50dcf941bf50 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/Config.php @@ -0,0 +1,43 @@ +data = $data; + } + + /** + * Returns config value by name + * + * @param string $queryName + * @return array + */ + public function get($queryName) + { + return $this->data->get($queryName); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/Config/Converter/Xml.php b/app/code/Magento/Analytics/ReportXml/Config/Converter/Xml.php new file mode 100644 index 0000000000000..9e0b20a6ad414 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/Config/Converter/Xml.php @@ -0,0 +1,61 @@ +hasAttributes()) { + $attrs = $source->attributes; + foreach ($attrs as $attr) { + $result[$attr->name] = $attr->value; + } + } + if ($source->hasChildNodes()) { + $children = $source->childNodes; + if ($children->length == 1) { + $child = $children->item(0); + if ($child->nodeType == XML_TEXT_NODE) { + $result['_value'] = $child->nodeValue; + return count($result) == 1 ? $result['_value'] : $result; + } + } + foreach ($children as $child) { + if ($child instanceof \DOMCharacterData) { + continue; + } + $result[$child->nodeName][] = $this->convertNode($child); + } + } + return $result; + } + + /** + * Converts XML document into corresponding array. + * + * @param \DOMDocument $source + * @return array + */ + public function convert($source) + { + return $this->convertNode($source); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/Config/Mapper.php b/app/code/Magento/Analytics/ReportXml/Config/Mapper.php new file mode 100644 index 0000000000000..4dda8f3c733a6 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/Config/Mapper.php @@ -0,0 +1,37 @@ +readers = $readers; + $this->mapper = $mapper; + } + + /** + * Reads configuration according to the given scope. + * + * @param string|null $scope + * @return array + */ + public function read($scope = null) + { + $data = []; + foreach ($this->readers as $reader) { + $data = array_merge_recursive($data, $reader->read($scope)); + } + return $this->mapper->execute($data); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/ConfigInterface.php b/app/code/Magento/Analytics/ReportXml/ConfigInterface.php new file mode 100644 index 0000000000000..ec03ddf429c06 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/ConfigInterface.php @@ -0,0 +1,23 @@ +resourceConnection = $resourceConnection; + $this->objectManager = $objectManager; + } + + /** + * Creates one-time connection for export + * + * @param string $connectionName + * @return AdapterInterface + */ + public function getConnection($connectionName) + { + $connection = $this->resourceConnection->getConnection($connectionName); + $connectionClassName = get_class($connection); + $configData = $connection->getConfig(); + $configData['use_buffered_query'] = false; + unset($configData['persistent']); + return $this->objectManager->create( + $connectionClassName, + [ + 'config' => $configData + ] + ); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/AssemblerInterface.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/AssemblerInterface.php new file mode 100644 index 0000000000000..083b4843c185a --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/AssemblerInterface.php @@ -0,0 +1,27 @@ +conditionResolver = $conditionResolver; + $this->nameResolver = $nameResolver; + } + + /** + * Assembles WHERE conditions + * + * @param SelectBuilder $selectBuilder + * @param array $queryConfig + * @return SelectBuilder + */ + public function assemble(SelectBuilder $selectBuilder, $queryConfig) + { + if (!isset($queryConfig['source']['filter'])) { + return $selectBuilder; + } + $filters = $this->conditionResolver->getFilter( + $selectBuilder, + $queryConfig['source']['filter'], + $this->nameResolver->getAlias($queryConfig['source']) + ); + $selectBuilder->setFilters(array_merge_recursive($selectBuilder->getFilters(), [$filters])); + return $selectBuilder; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php new file mode 100644 index 0000000000000..811119ace221b --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php @@ -0,0 +1,69 @@ +nameResolver = $nameResolver; + $this->columnsResolver = $columnsResolver; + $this->resourceConnection = $resourceConnection; + } + + /** + * Assembles FROM condition + * + * @param SelectBuilder $selectBuilder + * @param array $queryConfig + * @return SelectBuilder + */ + public function assemble(SelectBuilder $selectBuilder, $queryConfig) + { + $selectBuilder->setFrom( + [ + $this->nameResolver->getAlias($queryConfig['source']) => + $this->resourceConnection + ->getTableName($this->nameResolver->getName($queryConfig['source'])), + ] + ); + $columns = $this->columnsResolver->getColumns($selectBuilder, $queryConfig['source']); + $selectBuilder->setColumns(array_merge($selectBuilder->getColumns(), $columns)); + return $selectBuilder; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php new file mode 100644 index 0000000000000..f3c6540a25171 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php @@ -0,0 +1,113 @@ +conditionResolver = $conditionResolver; + $this->nameResolver = $nameResolver; + $this->columnsResolver = $columnsResolver; + $this->resourceConnection = $resourceConnection; + } + + /** + * Assembles JOIN conditions + * + * @param SelectBuilder $selectBuilder + * @param array $queryConfig + * @return SelectBuilder + */ + public function assemble(SelectBuilder $selectBuilder, $queryConfig) + { + if (!isset($queryConfig['source']['link-source'])) { + return $selectBuilder; + } + $joins = []; + $filters = $selectBuilder->getFilters(); + + $sourceAlias = $this->nameResolver->getAlias($queryConfig['source']); + + foreach ($queryConfig['source']['link-source'] as $join) { + $joinAlias = $this->nameResolver->getAlias($join); + + $joins[$joinAlias] = [ + 'link-type' => isset($join['link-type']) ? $join['link-type'] : 'left', + 'table' => [ + $joinAlias => $this->resourceConnection + ->getTableName($this->nameResolver->getName($join)), + ], + 'condition' => $this->conditionResolver->getFilter( + $selectBuilder, + $join['using'], + $joinAlias, + $sourceAlias + ) + ]; + if (isset($join['filter'])) { + $filters = array_merge( + $filters, + [ + $this->conditionResolver->getFilter( + $selectBuilder, + $join['filter'], + $joinAlias, + $sourceAlias + ) + ] + ); + } + $columns = $this->columnsResolver->getColumns($selectBuilder, isset($join['attribute']) ? $join : []); + $selectBuilder->setColumns(array_merge($selectBuilder->getColumns(), $columns)); + } + $selectBuilder->setFilters($filters); + $selectBuilder->setJoins(array_merge($selectBuilder->getJoins(), $joins)); + return $selectBuilder; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/ColumnsResolver.php b/app/code/Magento/Analytics/ReportXml/DB/ColumnsResolver.php new file mode 100644 index 0000000000000..e6474d4c5dc6d --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/ColumnsResolver.php @@ -0,0 +1,100 @@ +nameResolver = $nameResolver; + $this->resourceConnection = $resourceConnection; + } + + /** + * Returns connection + * + * @return \Magento\Framework\DB\Adapter\AdapterInterface + */ + private function getConnection() + { + if (!$this->connection) { + $this->connection = $this->resourceConnection->getConnection(); + } + return $this->connection; + } + + /** + * Set columns list to SelectBuilder + * + * @param SelectBuilder $selectBuilder + * @param array $entityConfig + * @return array + */ + public function getColumns(SelectBuilder $selectBuilder, $entityConfig) + { + if (!isset($entityConfig['attribute'])) { + return []; + } + $group = []; + $columns = $selectBuilder->getColumns(); + foreach ($entityConfig['attribute'] as $attributeData) { + $columnAlias = $this->nameResolver->getAlias($attributeData); + $tableAlias = $this->nameResolver->getAlias($entityConfig); + $columnName = $this->nameResolver->getName($attributeData); + if (isset($attributeData['function'])) { + $prefix = ''; + if (isset($attributeData['distinct']) && $attributeData['distinct'] == true) { + $prefix = ' DISTINCT '; + } + $expression = new ColumnValueExpression( + strtoupper($attributeData['function']) . '(' . $prefix + . $this->getConnection()->quoteIdentifier($tableAlias . '.' . $columnName) + . ')' + ); + } else { + $expression = $tableAlias . '.' . $columnName; + } + $columns[$columnAlias] = $expression; + if (isset($attributeData['group'])) { + $group[$columnAlias] = $expression; + } + } + $selectBuilder->setGroup(array_merge($selectBuilder->getGroup(), $group)); + return $columns; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/ConditionResolver.php b/app/code/Magento/Analytics/ReportXml/DB/ConditionResolver.php new file mode 100644 index 0000000000000..773b96959e794 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/ConditionResolver.php @@ -0,0 +1,166 @@ + '%1$s = %2$s', + 'neq' => '%1$s != %2$s', + 'like' => '%1$s LIKE %2$s', + 'nlike' => '%1$s NOT LIKE %2$s', + 'in' => '%1$s IN(%2$s)', + 'nin' => '%1$s NOT IN(%2$s)', + 'notnull' => '%1$s IS NOT NULL', + 'null' => '%1$s IS NULL', + 'gt' => '%1$s > %2$s', + 'lt' => '%1$s < %2$s', + 'gteq' => '%1$s >= %2$s', + 'lteq' => '%1$s <= %2$s', + 'finset' => 'FIND_IN_SET(%2$s, %1$s)' + ]; + + /** + * @var \Magento\Framework\DB\Adapter\AdapterInterface + */ + private $connection; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * ConditionResolver constructor. + * @param ResourceConnection $resourceConnection + */ + public function __construct( + ResourceConnection $resourceConnection + ) { + $this->resourceConnection = $resourceConnection; + } + + /** + * Returns connection + * + * @return \Magento\Framework\DB\Adapter\AdapterInterface + */ + private function getConnection() + { + if (!$this->connection) { + $this->connection = $this->resourceConnection->getConnection(); + } + return $this->connection; + } + + /** + * Returns value for condition + * + * @param string $condition + * @param string $referencedEntity + * @return mixed|null|string|\Zend_Db_Expr + */ + private function getValue($condition, $referencedEntity) + { + $value = null; + $argument = isset($condition['_value']) ? $condition['_value'] : null; + if (!isset($condition['type'])) { + $condition['type'] = 'value'; + } + + switch ($condition['type']) { + case "value": + $value = $this->getConnection()->quote($argument); + break; + case "variable": + $value = new Expression($argument); + break; + case "identifier": + $value = $this->getConnection()->quoteIdentifier( + $referencedEntity ? $referencedEntity . '.' . $argument : $argument + ); + break; + } + return $value; + } + + /** + * Returns condition for WHERE + * + * @param SelectBuilder $selectBuilder + * @param string $tableName + * @param array $condition + * @param null|string $referencedEntity + * @return string + */ + private function getCondition(SelectBuilder $selectBuilder, $tableName, $condition, $referencedEntity = null) + { + $columns = $selectBuilder->getColumns(); + if (isset($columns[$condition['attribute']]) + && $columns[$condition['attribute']] instanceof Expression + ) { + $expression = $columns[$condition['attribute']]; + } else { + $expression = $this->getConnection()->quoteIdentifier($tableName . '.' . $condition['attribute']); + } + return sprintf( + $this->conditionMap[$condition['operator']], + $expression, + $this->getValue($condition, $referencedEntity) + ); + } + + /** + * Build WHERE condition + * + * @param SelectBuilder $selectBuilder + * @param array $filterConfig + * @param string $aliasName + * @param null|string $referencedAlias + * @return array + */ + public function getFilter(SelectBuilder $selectBuilder, $filterConfig, $aliasName, $referencedAlias = null) + { + $filtersParts = []; + foreach ($filterConfig as $filter) { + $glue = $filter['glue']; + $parts = []; + foreach ($filter['condition'] as $condition) { + if (isset($condition['type']) && $condition['type'] == 'variable') { + $selectBuilder->setParams(array_merge($selectBuilder->getParams(), [$condition['_value']])); + } + $parts[] = $this->getCondition( + $selectBuilder, + $aliasName, + $condition, + $referencedAlias + ); + } + if (isset($filter['filter'])) { + $parts[] = '(' . $this->getFilter( + $selectBuilder, + $filter['filter'], + $aliasName, + $referencedAlias + ) . ')'; + } + $filtersParts[] = '(' . implode(' ' . strtoupper($glue) . ' ', $parts) . ')'; + } + return implode(' OR ', $filtersParts); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/NameResolver.php b/app/code/Magento/Analytics/ReportXml/DB/NameResolver.php new file mode 100644 index 0000000000000..c9543002eb272 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/NameResolver.php @@ -0,0 +1,40 @@ +getName($elementConfig); + if (isset($elementConfig['alias'])) { + $alias = $elementConfig['alias']; + } + return $alias; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/ReportValidator.php b/app/code/Magento/Analytics/ReportXml/DB/ReportValidator.php new file mode 100644 index 0000000000000..21a641f0a71c7 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/ReportValidator.php @@ -0,0 +1,64 @@ +connectionFactory = $connectionFactory; + $this->queryFactory = $queryFactory; + } + + /** + * Tries to do query for provided report with limit 0 and return error information if it failed + * + * @param string $name + * @param SearchCriteriaInterface $criteria + * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function validate($name, SearchCriteriaInterface $criteria = null) + { + $query = $this->queryFactory->create($name); + $connection = $this->connectionFactory->getConnection($query->getConnectionName()); + $query->getSelect()->limit(0); + try { + $connection->query($query->getSelect()); + } catch (\Zend_Db_Statement_Exception $e) { + return [$name, $e->getMessage()]; + } + + return []; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/SelectBuilder.php b/app/code/Magento/Analytics/ReportXml/DB/SelectBuilder.php new file mode 100644 index 0000000000000..4e5a1940773b1 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/SelectBuilder.php @@ -0,0 +1,289 @@ +resourceConnection = $resourceConnection; + } + + /** + * Get join condition + * + * @return array + */ + public function getJoins() + { + return $this->joins; + } + + /** + * Set joins conditions + * + * @param array $joins + * @return void + */ + public function setJoins($joins) + { + $this->joins = $joins; + } + + /** + * Get connection name + * + * @return string + */ + public function getConnectionName() + { + return $this->connectionName; + } + + /** + * Set connection name + * + * @param string $connectionName + * @return void + */ + public function setConnectionName($connectionName) + { + $this->connectionName = $connectionName; + } + + /** + * Get columns + * + * @return array + */ + public function getColumns() + { + return $this->columns; + } + + /** + * Set columns + * + * @param array $columns + * @return void + */ + public function setColumns($columns) + { + $this->columns = $columns; + } + + /** + * Get filters + * + * @return array + */ + public function getFilters() + { + return $this->filters; + } + + /** + * Set filters + * + * @param array $filters + * @return void + */ + public function setFilters($filters) + { + $this->filters = $filters; + } + + /** + * Get from condition + * + * @return array + */ + public function getFrom() + { + return $this->from; + } + + /** + * Set from condition + * + * @param array $from + * @return void + */ + public function setFrom($from) + { + $this->from = $from; + } + + /** + * Process JOIN conditions + * + * @param Select $select + * @param array $joinConfig + * @return Select + */ + private function processJoin(Select $select, $joinConfig) + { + switch ($joinConfig['link-type']) { + case 'left': + $select->joinLeft($joinConfig['table'], $joinConfig['condition'], []); + break; + case 'inner': + $select->joinInner($joinConfig['table'], $joinConfig['condition'], []); + break; + case 'right': + $select->joinRight($joinConfig['table'], $joinConfig['condition'], []); + break; + } + return $select; + } + + /** + * Creates Select object + * + * @return Select + */ + public function create() + { + $connection = $this->resourceConnection->getConnection($this->getConnectionName()); + $select = $connection->select(); + $select->from($this->getFrom(), []); + $select->columns($this->getColumns()); + foreach ($this->getFilters() as $filter) { + $select->where($filter); + } + foreach ($this->getJoins() as $joinConfig) { + $select = $this->processJoin($select, $joinConfig); + } + if (!empty($this->getGroup())) { + $select->group(implode(', ', $this->getGroup())); + } + return $select; + } + + /** + * Returns group + * + * @return array + */ + public function getGroup() + { + return $this->group; + } + + /** + * Set group + * + * @param array $group + * @return void + */ + public function setGroup($group) + { + $this->group = $group; + } + + /** + * Get parameters + * + * @return array + */ + public function getParams() + { + return $this->params; + } + + /** + * Set parameters + * + * @param array $params + * @return void + */ + public function setParams($params) + { + $this->params = $params; + } + + /** + * Get having condition + * + * @return array + */ + public function getHaving() + { + return $this->having; + } + + /** + * Set having condition + * + * @param array $having + * @return void + */ + public function setHaving($having) + { + $this->having = $having; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/DB/SelectBuilderFactory.php b/app/code/Magento/Analytics/ReportXml/DB/SelectBuilderFactory.php new file mode 100644 index 0000000000000..1d88d4618efc5 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/DB/SelectBuilderFactory.php @@ -0,0 +1,43 @@ +objectManager = $objectManager; + } + + /** + * Create class instance with specified parameters + * + * @param array $data + * @return SelectBuilder + */ + public function create(array $data = []) + { + return $this->objectManager->create(SelectBuilder::class, $data); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/IteratorFactory.php b/app/code/Magento/Analytics/ReportXml/IteratorFactory.php new file mode 100644 index 0000000000000..a196cef8b66dc --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/IteratorFactory.php @@ -0,0 +1,61 @@ +objectManager = $objectManager; + $this->defaultIteratorName = $defaultIteratorName; + } + + /** + * Creates instance of the result iterator with the query result as an input + * Result iterator can be changed through report configuration + * + * < ... + * + * Uses IteratorIterator by default + * + * @param \Traversable $result + * @param string|null $iteratorName + * @return \IteratorIterator + */ + public function create(\Traversable $result, $iteratorName = null) + { + return $this->objectManager->create( + $iteratorName ?: $this->defaultIteratorName, + [ + 'iterator' => $result + ] + ); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/Query.php b/app/code/Magento/Analytics/ReportXml/Query.php new file mode 100644 index 0000000000000..46ec2fb494183 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/Query.php @@ -0,0 +1,96 @@ +select = $select; + $this->connectionName = $connectionName; + $this->selectHydrator = $selectHydrator; + $this->config = $config; + } + + /** + * @return Select + */ + public function getSelect() + { + return $this->select; + } + + /** + * @return string + */ + public function getConnectionName() + { + return $this->connectionName; + } + + /** + * @return array + */ + public function getConfig() + { + return $this->config; + } + + /** + * Specify data which should be serialized to JSON + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php + * @return mixed data which can be serialized by json_encode, + * which is a value of any type other than a resource. + * @since 5.4.0 + */ + public function jsonSerialize() + { + return [ + 'connectionName' => $this->getConnectionName(), + 'select_parts' => $this->selectHydrator->extract($this->getSelect()), + 'config' => $this->getConfig() + ]; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/QueryFactory.php b/app/code/Magento/Analytics/ReportXml/QueryFactory.php new file mode 100644 index 0000000000000..8ed7e767b28b3 --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/QueryFactory.php @@ -0,0 +1,142 @@ +config = $config; + $this->selectBuilderFactory = $selectBuilderFactory; + $this->assemblers = $assemblers; + $this->queryCache = $queryCache; + $this->objectManager = $objectManager; + $this->selectHydrator = $selectHydrator; + } + + /** + * Returns query connection name according to configuration + * + * @param string $queryConfig + * @return string + */ + private function getQueryConnectionName($queryConfig) + { + $connectionName = 'default'; + if (isset($queryConfig['connection'])) { + $connectionName = $queryConfig['connection']; + } + return $connectionName; + } + + /** + * Create query according to configuration settings + * + * @param string $queryName + * @return Query + */ + private function constructQuery($queryName) + { + $queryConfig = $this->config->get($queryName); + $selectBuilder = $this->selectBuilderFactory->create(); + $selectBuilder->setConnectionName($this->getQueryConnectionName($queryConfig)); + foreach ($this->assemblers as $assembler) { + $selectBuilder = $assembler->assemble($selectBuilder, $queryConfig); + } + $select = $selectBuilder->create(); + return $this->objectManager->create( + Query::class, + [ + 'select' => $select, + 'selectHydrator' => $this->selectHydrator, + 'connectionName' => $selectBuilder->getConnectionName(), + 'config' => $queryConfig + ] + ); + } + + /** + * Creates query by name + * + * @param string $queryName + * @return Query + */ + public function create($queryName) + { + $cached = $this->queryCache->load($queryName); + if ($cached) { + $queryData = json_decode($cached, true); + return $this->objectManager->create( + Query::class, + [ + 'select' => $this->selectHydrator->recreate($queryData['select_parts']), + 'selectHydrator' => $this->selectHydrator, + 'connectionName' => $queryData['connectionName'], + 'config' => $queryData['config'] + ] + ); + } + $query = $this->constructQuery($queryName); + $this->queryCache->save(json_encode($query), $queryName); + return $query; + } +} diff --git a/app/code/Magento/Analytics/ReportXml/ReportProvider.php b/app/code/Magento/Analytics/ReportXml/ReportProvider.php new file mode 100644 index 0000000000000..3ebe5941108bc --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/ReportProvider.php @@ -0,0 +1,76 @@ +queryFactory = $queryFactory; + $this->connectionFactory = $connectionFactory; + $this->iteratorFactory = $iteratorFactory; + } + + /** + * Returns custom iterator name for report + * Null for default + * + * @param Query $query + * @return string|null + */ + private function getIteratorName(Query $query) + { + $config = $query->getConfig(); + return isset($config['iterator']) ? $config['iterator'] : null; + } + + /** + * Returns report data by name and criteria + * + * @param string $name + * @return \IteratorIterator + */ + public function getReport($name) + { + $query = $this->queryFactory->create($name); + $connection = $this->connectionFactory->getConnection($query->getConnectionName()); + $statement = $connection->query($query->getSelect()); + return $this->iteratorFactory->create($statement, $this->getIteratorName($query)); + } +} diff --git a/app/code/Magento/Analytics/ReportXml/SelectHydrator.php b/app/code/Magento/Analytics/ReportXml/SelectHydrator.php new file mode 100644 index 0000000000000..02cde2fd0598d --- /dev/null +++ b/app/code/Magento/Analytics/ReportXml/SelectHydrator.php @@ -0,0 +1,143 @@ +resourceConnection = $resourceConnection; + $this->objectManager = $objectManager; + $this->selectParts = $selectParts; + } + + /** + * @return array + */ + private function getSelectParts() + { + return array_merge($this->predefinedSelectParts, $this->selectParts); + } + + /** + * Extracts Select metadata parts + * + * @param Select $select + * @return array + * @throws \Zend_Db_Select_Exception + */ + public function extract(Select $select) + { + $parts = []; + foreach ($this->getSelectParts() as $partName) { + $parts[$partName] = $select->getPart($partName); + } + return $parts; + } + + /** + * @param array $selectParts + * @return Select + */ + public function recreate(array $selectParts) + { + $select = $this->resourceConnection->getConnection()->select(); + + $select = $this->processColumns($select, $selectParts); + + foreach ($selectParts as $partName => $partValue) { + $select->setPart($partName, $partValue); + } + + return $select; + } + + /** + * Process COLUMNS part values and add this part into select. + * + * If each column contains information about select expression + * an object with the type of this expression going to be created and assigned to this column. + * + * @param Select $select + * @param array $selectParts + * @return Select + */ + private function processColumns(Select $select, array &$selectParts) + { + if (!empty($selectParts[Select::COLUMNS]) && is_array($selectParts[Select::COLUMNS])) { + $part = []; + + foreach ($selectParts[Select::COLUMNS] as $columnEntry) { + list($correlationName, $column, $alias) = $columnEntry; + if (is_array($column) && !empty($column['class'])) { + $expression = $this->objectManager->create( + $column['class'], + isset($column['arguments']) ? $column['arguments'] : [] + ); + $part[] = [$correlationName, $expression, $alias]; + } else { + $part[] = $columnEntry; + } + } + + $select->setPart(Select::COLUMNS, $part); + unset($selectParts[Select::COLUMNS]); + } + + return $select; + } +} diff --git a/app/code/Magento/Analytics/Setup/InstallData.php b/app/code/Magento/Analytics/Setup/InstallData.php new file mode 100644 index 0000000000000..aaa619bbb0caa --- /dev/null +++ b/app/code/Magento/Analytics/Setup/InstallData.php @@ -0,0 +1,53 @@ +getConnection()->insertMultiple( + $setup->getTable('core_config_data'), + [ + [ + 'scope' => 'default', + 'scope_id' => 0, + 'path' => 'analytics/subscription/enabled', + 'value' => 1 + ], + [ + 'scope' => 'default', + 'scope_id' => 0, + 'path' => SubscriptionHandler::CRON_STRING_PATH, + 'value' => join(' ', SubscriptionHandler::CRON_EXPR_ARRAY) + ] + ] + ); + + $setup->getConnection()->insert( + $setup->getTable('flag'), + [ + 'flag_code' => SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, + 'state' => 0, + 'flag_data' => 24, + ] + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php new file mode 100644 index 0000000000000..cbf06264096ac --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/AdditionalCommentTest.php @@ -0,0 +1,77 @@ +abstractElementMock = $this->getMockBuilder(AbstractElement::class) + ->setMethods(['getComment', 'getLabel']) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->formMock = $this->getMockBuilder(Form::class) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManager($this); + $this->additionalComment = $objectManager->getObject( + AdditionalComment::class, + [ + 'context' => $this->contextMock + ] + ); + } + + public function testRender() + { + $this->abstractElementMock->setForm($this->formMock); + $this->abstractElementMock->expects($this->any()) + ->method('getComment') + ->willReturn('New comment'); + $this->abstractElementMock->expects($this->any()) + ->method('getLabel') + ->willReturn('Comment label'); + $html = $this->additionalComment->render($this->abstractElementMock); + $this->assertRegexp( + "/New comment/", + $html + ); + $this->assertRegexp( + "/Comment label/", + $html + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php new file mode 100644 index 0000000000000..a652cf6b3d548 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/CollectionTimeLabelTest.php @@ -0,0 +1,81 @@ +abstractElementMock = $this->getMockBuilder(AbstractElement::class) + ->setMethods(['getComment']) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->setMethods(['getLocaleDate']) + ->disableOriginalConstructor() + ->getMock(); + $this->formMock = $this->getMockBuilder(Form::class) + ->disableOriginalConstructor() + ->getMock(); + $this->timeZoneMock = $this->getMockBuilder(TimezoneInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock->expects($this->any()) + ->method('getLocaleDate') + ->willReturn($this->timeZoneMock); + + $objectManager = new ObjectManager($this); + $this->collectionTimeLabel = $objectManager->getObject( + CollectionTimeLabel::class, + [ + 'context' => $this->contextMock + ] + ); + } + + public function testRender() + { + $timeZone = "America/New_York"; + $this->abstractElementMock->setForm($this->formMock); + $this->timeZoneMock->expects($this->once()) + ->method('getConfigTimezone') + ->willReturn($timeZone); + $this->abstractElementMock->expects($this->any()) + ->method('getComment') + ->willReturn('Eastern Standard Time (America/New_York)'); + $this->assertRegexp( + "/Eastern Standard Time \(America\/New_York\)/", + $this->collectionTimeLabel->render($this->abstractElementMock) + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php new file mode 100644 index 0000000000000..09e753e4ac8aa --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/SubscriptionStatusLabelTest.php @@ -0,0 +1,85 @@ +subscriptionStatusProviderMock = $this->getMockBuilder(SubscriptionStatusProvider::class) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->abstractElementMock = $this->getMockBuilder(AbstractElement::class) + ->setMethods(['getComment']) + ->disableOriginalConstructor() + ->getMock(); + $this->formMock = $this->getMockBuilder(Form::class) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManager($this); + $this->subscriptionStatusLabel = $objectManager->getObject( + SubscriptionStatusLabel::class, + [ + 'context' => $this->contextMock, + 'subscriptionStatusProvider' => $this->subscriptionStatusProviderMock + ] + ); + } + + public function testRender() + { + $this->abstractElementMock->setForm($this->formMock); + $this->subscriptionStatusProviderMock->expects($this->once()) + ->method('getStatus') + ->willReturn('Enabled'); + $this->abstractElementMock->expects($this->any()) + ->method('getComment') + ->willReturn('Subscription status: Enabled'); + $this->assertRegexp( + "/Subscription status: Enabled/", + $this->subscriptionStatusLabel->render($this->abstractElementMock) + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php new file mode 100644 index 0000000000000..abce48c36c86a --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Block/Adminhtml/System/Config/VerticalTest.php @@ -0,0 +1,77 @@ +abstractElementMock = $this->getMockBuilder(AbstractElement::class) + ->setMethods(['getComment', 'getLabel', 'getHint']) + ->disableOriginalConstructor() + ->getMock(); + $this->contextMock = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $this->formMock = $this->getMockBuilder(Form::class) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManager($this); + $this->vertical = $objectManager->getObject( + Vertical::class, + [ + 'context' => $this->contextMock + ] + ); + } + + public function testRender() + { + $this->abstractElementMock->setForm($this->formMock); + $this->abstractElementMock->expects($this->any()) + ->method('getComment') + ->willReturn('New comment'); + $this->abstractElementMock->expects($this->any()) + ->method('getHint') + ->willReturn('New hint'); + $html = $this->vertical->render($this->abstractElementMock); + $this->assertRegexp( + "/New comment/", + $html + ); + $this->assertRegExp( + "/New hint/", + $html + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php new file mode 100644 index 0000000000000..6f613cdc4d639 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/BIEssentials/SignUpTest.php @@ -0,0 +1,84 @@ +configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->resultRedirectFactoryMock = $this->getMockBuilder(RedirectFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->redirectMock = $this->getMockBuilder(Redirect::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->signUpController = $this->objectManagerHelper->getObject( + SignUp::class, + [ + 'config' => $this->configMock, + 'resultRedirectFactory' => $this->resultRedirectFactoryMock + ] + ); + } + + /** + * @return void + */ + public function testExecute() + { + $urlBIEssentialsConfigPath = 'analytics/url/bi_essentials'; + $this->configMock->expects($this->once()) + ->method('getValue') + ->with($urlBIEssentialsConfigPath) + ->willReturn('value'); + $this->resultRedirectFactoryMock->expects($this->once())->method('create')->willReturn($this->redirectMock); + $this->redirectMock->expects($this->once())->method('setUrl')->with('value')->willReturnSelf(); + $this->assertEquals($this->redirectMock, $this->signUpController->execute()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php new file mode 100644 index 0000000000000..4f54ce5059965 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Reports/ShowTest.php @@ -0,0 +1,185 @@ +reportUrlProviderMock = $this->getMockBuilder(ReportUrlProvider::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->redirectMock = $this->getMockBuilder(Redirect::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->showController = $this->objectManagerHelper->getObject( + Show::class, + [ + 'reportUrlProvider' => $this->reportUrlProviderMock, + 'resultFactory' => $this->resultFactoryMock, + 'messageManager' => $this->messageManagerMock, + ] + ); + } + + /** + * @return void + */ + public function testExecute() + { + $otpUrl = 'http://example.com?otp=15vbjcfdvd15645'; + + $this->resultFactoryMock + ->expects($this->once()) + ->method('create') + ->with(ResultFactory::TYPE_REDIRECT) + ->willReturn($this->redirectMock); + $this->reportUrlProviderMock + ->expects($this->once()) + ->method('getUrl') + ->with() + ->willReturn($otpUrl); + $this->redirectMock + ->expects($this->once()) + ->method('setUrl') + ->with($otpUrl) + ->willReturnSelf(); + $this->assertSame($this->redirectMock, $this->showController->execute()); + } + + /** + * @dataProvider executeWithExceptionDataProvider + * + * @param \Exception $exception + */ + public function testExecuteWithException(\Exception $exception) + { + + $this->resultFactoryMock + ->expects($this->once()) + ->method('create') + ->with(ResultFactory::TYPE_REDIRECT) + ->willReturn($this->redirectMock); + $this->reportUrlProviderMock + ->expects($this->once()) + ->method('getUrl') + ->with() + ->willThrowException($exception); + if ($exception instanceof LocalizedException) { + $message = $exception->getMessage(); + } else { + $message = __('Sorry, there has been an error processing your request. Please try again later.'); + } + $this->messageManagerMock + ->expects($this->once()) + ->method('addExceptionMessage') + ->with($exception, $message) + ->willReturnSelf(); + $this->redirectMock + ->expects($this->once()) + ->method('setPath') + ->with('adminhtml') + ->willReturnSelf(); + $this->assertSame($this->redirectMock, $this->showController->execute()); + } + + /** + * @return array + */ + public function executeWithExceptionDataProvider() + { + return [ + 'ExecuteWithLocalizedException' => [new LocalizedException(__('TestMessage'))], + 'ExecuteWithException' => [new \Exception('TestMessage')], + ]; + } + + /** + * @return void + */ + public function testExecuteWithSubscriptionUpdateException() + { + $exception = new SubscriptionUpdateException(__('TestMessage')); + $this->resultFactoryMock + ->expects($this->once()) + ->method('create') + ->with(ResultFactory::TYPE_REDIRECT) + ->willReturn($this->redirectMock); + $this->reportUrlProviderMock + ->expects($this->once()) + ->method('getUrl') + ->with() + ->willThrowException($exception); + $this->messageManagerMock + ->expects($this->once()) + ->method('addNoticeMessage') + ->with($exception->getMessage()) + ->willReturnSelf(); + $this->redirectMock + ->expects($this->once()) + ->method('setPath') + ->with('adminhtml') + ->willReturnSelf(); + $this->assertSame($this->redirectMock, $this->showController->execute()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php new file mode 100644 index 0000000000000..17c485a8df230 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php @@ -0,0 +1,159 @@ +resultFactoryMock = $this->getMockBuilder(ResultFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->resultRedirectMock = $this->getMockBuilder(Redirect::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->subscriptionHandlerMock = $this->getMockBuilder(SubscriptionHandler::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->retryController = $this->objectManagerHelper->getObject( + Retry::class, + [ + 'resultFactory' => $this->resultFactoryMock, + 'subscriptionHandler' => $this->subscriptionHandlerMock, + 'messageManager' => $this->messageManagerMock, + ] + ); + } + + /** + * @return void + */ + public function testExecute() + { + $this->resultFactoryMock + ->expects($this->once()) + ->method('create') + ->with(ResultFactory::TYPE_REDIRECT) + ->willReturn($this->resultRedirectMock); + $this->resultRedirectMock + ->expects($this->once()) + ->method('setPath') + ->with('adminhtml') + ->willReturnSelf(); + $this->subscriptionHandlerMock + ->expects($this->once()) + ->method('processEnabled') + ->with() + ->willReturn(true); + $this->assertSame( + $this->resultRedirectMock, + $this->retryController->execute() + ); + } + + /** + * @dataProvider executeExceptionsDataProvider + * + * @param \Exception $exception + * @param Phrase $message + */ + public function testExecuteWithException(\Exception $exception, Phrase $message) + { + $this->resultFactoryMock + ->expects($this->once()) + ->method('create') + ->with(ResultFactory::TYPE_REDIRECT) + ->willReturn($this->resultRedirectMock); + $this->resultRedirectMock + ->expects($this->once()) + ->method('setPath') + ->with('adminhtml') + ->willReturnSelf(); + $this->subscriptionHandlerMock + ->expects($this->once()) + ->method('processEnabled') + ->with() + ->willThrowException($exception); + $this->messageManagerMock + ->expects($this->once()) + ->method('addExceptionMessage') + ->with($exception, $message); + + $this->assertSame( + $this->resultRedirectMock, + $this->retryController->execute() + ); + } + + /** + * @return array + */ + public function executeExceptionsDataProvider() + { + return [ + [new LocalizedException(__('TestMessage')), __('TestMessage')], + [ + new \Exception('TestMessage'), + __('Sorry, there has been an error processing your request. Please try again later.') + ], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php b/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php new file mode 100644 index 0000000000000..81c57d79033c8 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Cron/CollectDataTest.php @@ -0,0 +1,91 @@ +exportDataHandlerMock = $this->getMockBuilder(ExportDataHandlerInterface::class) + ->getMockForAbstractClass(); + + $this->subscriptionStatusMock = $this->getMockBuilder(SubscriptionStatusProvider::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->collectData = $this->objectManagerHelper->getObject( + CollectData::class, + [ + 'exportDataHandler' => $this->exportDataHandlerMock, + 'subscriptionStatus' => $this->subscriptionStatusMock, + ] + ); + } + + /** + * @param string $status + * @return void + * @dataProvider executeDataProvider + */ + public function testExecute($status) + { + $this->subscriptionStatusMock + ->expects($this->once()) + ->method('getStatus') + ->with() + ->willReturn($status); + $this->exportDataHandlerMock + ->expects(($status === SubscriptionStatusProvider::ENABLED) ? $this->once() : $this->never()) + ->method('prepareExportData') + ->with(); + + $this->assertTrue($this->collectData->execute()); + } + + /** + * @return array + */ + public function executeDataProvider() + { + return [ + 'Subscription is enabled' => [SubscriptionStatusProvider::ENABLED], + 'Subscription is disabled' => [SubscriptionStatusProvider::DISABLED], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php new file mode 100644 index 0000000000000..959a11f9e1058 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Cron/SignUpTest.php @@ -0,0 +1,133 @@ +connectorMock = $this->getMockBuilder(Connector::class) + ->disableOriginalConstructor() + ->getMock(); + $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->signUp = new SignUp( + $this->connectorMock, + $this->configWriterMock, + $this->flagManagerMock, + $this->reinitableConfigMock + ); + } + + public function testExecute() + { + $attemptsCount = 10; + + $this->flagManagerMock->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE) + ->willReturn($attemptsCount); + + $attemptsCount -= 1; + $this->flagManagerMock->expects($this->once()) + ->method('saveFlag') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, $attemptsCount); + $this->connectorMock->expects($this->once()) + ->method('execute') + ->with('signUp') + ->willReturn(true); + $this->addDeleteAnalyticsCronExprAsserts(); + $this->flagManagerMock->expects($this->once()) + ->method('deleteFlag') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + $this->assertTrue($this->signUp->execute()); + } + + public function testExecuteFlagNotExist() + { + $this->flagManagerMock->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE) + ->willReturn(null); + $this->addDeleteAnalyticsCronExprAsserts(); + $this->assertFalse($this->signUp->execute()); + } + + public function testExecuteZeroAttempts() + { + $attemptsCount = 0; + $this->flagManagerMock->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE) + ->willReturn($attemptsCount); + $this->addDeleteAnalyticsCronExprAsserts(); + $this->flagManagerMock->expects($this->once()) + ->method('deleteFlag') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + $this->assertFalse($this->signUp->execute()); + } + + /** + * Add assertions for method deleteAnalyticsCronExpr. + * + * @return void + */ + private function addDeleteAnalyticsCronExprAsserts() + { + $this->configWriterMock + ->expects($this->once()) + ->method('delete') + ->with(SubscriptionHandler::CRON_STRING_PATH) + ->willReturn(true); + $this->reinitableConfigMock + ->expects($this->once()) + ->method('reinit') + ->willReturnSelf(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php b/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php new file mode 100644 index 0000000000000..ede53d8783a7a --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Cron/UpdateTest.php @@ -0,0 +1,214 @@ +connectorMock = $this->getMockBuilder(Connector::class) + ->disableOriginalConstructor() + ->getMock(); + $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->update = new Update( + $this->connectorMock, + $this->configWriterMock, + $this->reinitableConfigMock, + $this->flagManagerMock, + $this->analyticsTokenMock + ); + } + + /** + * @return void + */ + public function testExecuteWithoutToken() + { + $this->flagManagerMock + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE) + ->willReturn(10); + $this->connectorMock + ->expects($this->once()) + ->method('execute') + ->with('update') + ->willReturn(false); + $this->analyticsTokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + $this->addFinalOutputAsserts(); + $this->assertFalse($this->update->execute()); + } + + /** + * @param bool $isExecuted + */ + private function addFinalOutputAsserts(bool $isExecuted = true) + { + $this->flagManagerMock + ->expects($this->exactly(2 * $isExecuted)) + ->method('deleteFlag') + ->withConsecutive( + [SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE], + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE] + ); + $this->configWriterMock + ->expects($this->exactly((int)$isExecuted)) + ->method('delete') + ->with(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH); + $this->reinitableConfigMock + ->expects($this->exactly((int)$isExecuted)) + ->method('reinit') + ->with(); + } + + /** + * @param $counterData + * @return void + * @dataProvider executeWithEmptyReverseCounterDataProvider + */ + public function testExecuteWithEmptyReverseCounter($counterData) + { + $this->flagManagerMock + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE) + ->willReturn($counterData); + $this->connectorMock + ->expects($this->never()) + ->method('execute') + ->with('update') + ->willReturn(false); + $this->analyticsTokenMock + ->method('isTokenExist') + ->willReturn(true); + $this->addFinalOutputAsserts(); + $this->assertFalse($this->update->execute()); + } + + /** + * Provides empty states of the reverse counter. + * + * @return array + */ + public function executeWithEmptyReverseCounterDataProvider() + { + return [ + [null], + [0] + ]; + } + + /** + * @param int $reverseCount + * @param bool $commandResult + * @param bool $finalConditionsIsExpected + * @param bool $functionResult + * @return void + * @dataProvider executeRegularScenarioDataProvider + */ + public function testExecuteRegularScenario( + int $reverseCount, + bool $commandResult, + bool $finalConditionsIsExpected, + bool $functionResult + ) { + $this->flagManagerMock + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE) + ->willReturn($reverseCount); + $this->connectorMock + ->expects($this->once()) + ->method('execute') + ->with('update') + ->willReturn($commandResult); + $this->analyticsTokenMock + ->method('isTokenExist') + ->willReturn(true); + $this->addFinalOutputAsserts($finalConditionsIsExpected); + $this->assertSame($functionResult, $this->update->execute()); + } + + /** + * @return array + */ + public function executeRegularScenarioDataProvider() + { + return [ + 'The last attempt with command execution result False' => [ + 'Reverse count' => 1, + 'Command result' => false, + 'Executed final output conditions' => true, + 'Function result' => false, + ], + 'Not the last attempt with command execution result False' => [ + 'Reverse count' => 10, + 'Command result' => false, + 'Executed final output conditions' => false, + 'Function result' => false, + ], + 'Command execution result True' => [ + 'Reverse count' => 10, + 'Command result' => true, + 'Executed final output conditions' => true, + 'Function result' => true, + ], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php b/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php new file mode 100644 index 0000000000000..57315543bc32d --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/AnalyticsTokenTest.php @@ -0,0 +1,129 @@ +reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->tokenModel = $this->objectManagerHelper->getObject( + AnalyticsToken::class, + [ + 'reinitableConfig' => $this->reinitableConfigMock, + 'config' => $this->configMock, + 'configWriter' => $this->configWriterMock, + 'tokenPath' => $this->tokenPath, + ] + ); + } + + /** + * @return void + */ + public function testStoreToken() + { + $value = 'jjjj0000'; + + $this->configWriterMock + ->expects($this->once()) + ->method('save') + ->with($this->tokenPath, $value); + + $this->reinitableConfigMock + ->expects($this->once()) + ->method('reinit') + ->willReturnSelf(); + + $this->assertTrue($this->tokenModel->storeToken($value)); + } + + /** + * @return void + */ + public function testGetToken() + { + $value = 'jjjj0000'; + + $this->configMock + ->expects($this->once()) + ->method('getValue') + ->with($this->tokenPath) + ->willReturn($value); + + $this->assertSame($value, $this->tokenModel->getToken()); + } + + /** + * @return void + */ + public function testIsTokenExist() + { + $this->assertFalse($this->tokenModel->isTokenExist()); + + $this->configMock + ->expects($this->once()) + ->method('getValue') + ->with($this->tokenPath) + ->willReturn('0000'); + $this->assertTrue($this->tokenModel->isTokenExist()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php new file mode 100644 index 0000000000000..f5f721c038c57 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Baseurl/SubscriptionUpdateHandlerTest.php @@ -0,0 +1,178 @@ +reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->subscriptionUpdateHandler = $this->objectManagerHelper->getObject( + SubscriptionUpdateHandler::class, + [ + 'reinitableConfig' => $this->reinitableConfigMock, + 'analyticsToken' => $this->analyticsTokenMock, + 'flagManager' => $this->flagManagerMock, + 'configWriter' => $this->configWriterMock, + ] + ); + } + + /** + * @return void + */ + public function testTokenDoesNotExist() + { + $this->analyticsTokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->with() + ->willReturn(false); + $this->flagManagerMock + ->expects($this->never()) + ->method('saveFlag'); + $this->configWriterMock + ->expects($this->never()) + ->method('save'); + $this->assertTrue($this->subscriptionUpdateHandler->processUrlUpdate('http://store.com')); + } + + /** + * @return void + */ + public function testTokenAndPreviousBaseUrlExist() + { + $url = 'https://store.com'; + $this->analyticsTokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->with() + ->willReturn(true); + $this->flagManagerMock + ->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE) + ->willReturn(true); + $this->flagManagerMock + ->expects($this->once()) + ->method('saveFlag') + ->withConsecutive( + [SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE, $this->attemptsInitValue], + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, $url] + ); + $this->configWriterMock + ->expects($this->once()) + ->method('save') + ->with(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH, $this->cronExpression); + $this->reinitableConfigMock + ->expects($this->once()) + ->method('reinit') + ->with(); + $this->assertTrue($this->subscriptionUpdateHandler->processUrlUpdate($url)); + } + + /** + * @return void + */ + public function testTokenExistAndWithoutPreviousBaseUrl() + { + $url = 'https://store.com'; + $this->analyticsTokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->with() + ->willReturn(true); + $this->flagManagerMock + ->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE) + ->willReturn(false); + $this->flagManagerMock + ->expects($this->exactly(2)) + ->method('saveFlag') + ->withConsecutive( + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, $url], + [SubscriptionUpdateHandler::SUBSCRIPTION_UPDATE_REVERSE_COUNTER_FLAG_CODE, $this->attemptsInitValue] + ); + $this->configWriterMock + ->expects($this->once()) + ->method('save') + ->with(SubscriptionUpdateHandler::UPDATE_CRON_STRING_PATH, $this->cronExpression); + $this->reinitableConfigMock + ->expects($this->once()) + ->method('reinit') + ->with(); + $this->assertTrue($this->subscriptionUpdateHandler->processUrlUpdate($url)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php new file mode 100644 index 0000000000000..071b96111ac8b --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/CollectionTimeTest.php @@ -0,0 +1,111 @@ +configWriterMock = $this->getMockBuilder(WriterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->collectionTime = $this->objectManagerHelper->getObject( + CollectionTime::class, + [ + 'configWriter' => $this->configWriterMock, + '_logger' => $this->loggerMock, + ] + ); + } + + /** + * @return void + */ + public function testAfterSave() + { + $this->collectionTime->setData('value', '05,04,03'); + + $this->configWriterMock + ->expects($this->once()) + ->method('save') + ->with(CollectionTime::CRON_SCHEDULE_PATH, join(' ', ['04', '05', '*', '*', '*'])); + + $this->assertInstanceOf( + Value::class, + $this->collectionTime->afterSave() + ); + } + + /** + * @return void + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testAfterSaveWrongValue() + { + $this->collectionTime->setData('value', '00,01'); + $this->collectionTime->afterSave(); + } + + /** + * @return void + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testAfterSaveWithLocalizedException() + { + $exception = new \Exception('Test message'); + $this->collectionTime->setData('value', '05,04,03'); + + $this->configWriterMock + ->expects($this->once()) + ->method('save') + ->with(CollectionTime::CRON_SCHEDULE_PATH, join(' ', ['04', '05', '*', '*', '*'])) + ->willThrowException($exception); + $this->loggerMock + ->expects($this->once()) + ->method('error') + ->with($exception->getMessage()); + $this->collectionTime->afterSave(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php new file mode 100644 index 0000000000000..82aa4dc72dfe0 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/Enabled/SubscriptionHandlerTest.php @@ -0,0 +1,152 @@ +flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configWriterMock = $this->getMockBuilder(WriterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->tokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->subscriptionHandler = $this->objectManagerHelper->getObject( + SubscriptionHandler::class, + [ + 'flagManager' => $this->flagManagerMock, + 'configWriter' => $this->configWriterMock, + 'attemptsInitValue' => $this->attemptsInitValue, + 'analyticsToken' => $this->tokenMock, + ] + ); + } + + public function testProcessEnabledTokenExist() + { + $this->tokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + $this->configWriterMock + ->expects($this->never()) + ->method('save'); + $this->flagManagerMock + ->expects($this->never()) + ->method('saveFlag'); + $this->assertTrue( + $this->subscriptionHandler->processEnabled() + ); + } + + public function testProcessEnabledTokenDoesNotExist() + { + $this->tokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + $this->configWriterMock + ->expects($this->once()) + ->method('save') + ->with(SubscriptionHandler::CRON_STRING_PATH, "0 * * * *"); + $this->flagManagerMock + ->expects($this->once()) + ->method('saveFlag') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, $this->attemptsInitValue) + ->willReturn(true); + $this->assertTrue( + $this->subscriptionHandler->processEnabled() + ); + } + + public function testProcessDisabledTokenDoesNotExist() + { + $this->configWriterMock + ->expects($this->once()) + ->method('delete') + ->with(CollectionTime::CRON_SCHEDULE_PATH); + $this->tokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + $this->flagManagerMock + ->expects($this->once()) + ->method('deleteFlag') + ->with(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE) + ->willReturn(true); + $this->assertTrue( + $this->subscriptionHandler->processDisabled() + ); + } + + public function testProcessDisabledTokenExists() + { + $this->configWriterMock + ->expects($this->once()) + ->method('delete') + ->with(CollectionTime::CRON_SCHEDULE_PATH); + $this->tokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + $this->flagManagerMock + ->expects($this->never()) + ->method('deleteFlag'); + $this->assertTrue( + $this->subscriptionHandler->processDisabled() + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php new file mode 100644 index 0000000000000..eea3193258bc6 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/EnabledTest.php @@ -0,0 +1,184 @@ +subscriptionHandlerMock = $this->getMockBuilder(SubscriptionHandler::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->enabledModel = $this->objectManagerHelper->getObject( + Enabled::class, + [ + 'subscriptionHandler' => $this->subscriptionHandlerMock, + '_logger' => $this->loggerMock, + 'config' => $this->configMock, + ] + ); + } + + /** + * @return void + */ + public function testAfterSaveSuccessEnabled() + { + $this->enabledModel->setData('value', $this->valueEnabled); + + $this->configMock + ->expects($this->any()) + ->method('getValue') + ->willReturn(!$this->valueEnabled); + + $this->subscriptionHandlerMock + ->expects($this->once()) + ->method('processEnabled') + ->with() + ->willReturn(true); + + $this->assertInstanceOf( + Value::class, + $this->enabledModel->afterSave() + ); + } + + /** + * @return void + */ + public function testAfterSaveSuccessDisabled() + { + $this->enabledModel->setData('value', $this->valueDisabled); + + $this->configMock + ->expects($this->any()) + ->method('getValue') + ->willReturn(!$this->valueDisabled); + + $this->subscriptionHandlerMock + ->expects($this->once()) + ->method('processDisabled') + ->with() + ->willReturn(true); + + $this->assertInstanceOf( + Value::class, + $this->enabledModel->afterSave() + ); + } + + /** + * @return void + */ + public function testAfterSaveSuccessValueNotChanged() + { + $this->enabledModel->setData('value', null); + + $this->configMock + ->expects($this->any()) + ->method('getValue') + ->willReturn(null); + + $this->subscriptionHandlerMock + ->expects($this->never()) + ->method('processEnabled') + ->with() + ->willReturn(true); + $this->subscriptionHandlerMock + ->expects($this->never()) + ->method('processDisabled') + ->with() + ->willReturn(true); + + $this->assertInstanceOf( + Value::class, + $this->enabledModel->afterSave() + ); + } + + /** + * @return void + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testExecuteAfterSaveFailedWithLocalizedException() + { + $exception = new \Exception('Message'); + $this->enabledModel->setData('value', $this->valueEnabled); + + $this->subscriptionHandlerMock + ->expects($this->once()) + ->method('processEnabled') + ->with() + ->willThrowException($exception); + + $this->loggerMock + ->expects($this->once()) + ->method('error') + ->with($exception->getMessage()); + + $this->enabledModel->afterSave(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php new file mode 100644 index 0000000000000..6fe7d0aa93998 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Backend/VerticalTest.php @@ -0,0 +1,59 @@ +objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\Model\Config\Backend\Vertical::class + ); + } + + /** + * @return void + */ + public function testBeforeSaveSuccess() + { + $this->subject->setValue('Apps and Games'); + + $this->assertInstanceOf( + \Magento\Analytics\Model\Config\Backend\Vertical::class, + $this->subject->beforeSave() + ); + } + + /** + * @return void + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testBeforeSaveFailedWithLocalizedException() + { + $this->subject->setValue(''); + + $this->subject->beforeSave(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php new file mode 100644 index 0000000000000..0b7f4870dbac8 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/MapperTest.php @@ -0,0 +1,142 @@ +objectManagerHelper = new ObjectManagerHelper($this); + + $this->mapper = $this->objectManagerHelper->getObject(Mapper::class); + } + + /** + * @param array $configData + * @param array $resultData + * @return void + * + * @dataProvider executingDataProvider + */ + public function testExecution($configData, $resultData) + { + $this->assertSame($resultData, $this->mapper->execute($configData)); + } + + /** + * @return array + */ + public function executingDataProvider() + { + return [ + 'wrongConfig' => [ + ['config' => ['files']], + [] + ], + 'validConfigWithFileNodes' => [ + [ + 'config' => [ + 0 => [ + 'file' => [ + 0 => [ + 'name' => 'fileName', + 'providers' => [[]] + ] + ] + ] + ] + ], + [ + 'fileName' => [ + 'name' => 'fileName', + 'providers' => [] + ] + ], + ], + 'validConfigWithProvidersNode' => [ + [ + 'config' => [ + 0 => [ + 'file' => [ + 0 => [ + 'name' => 'fileName', + 'providers' => [ + 0 => [ + 'reportProvider' => [0 => []] + ] + ] + ] + ] + ] + ] + ], + [ + 'fileName' => [ + 'name' => 'fileName', + 'providers' => [ + 'reportProvider' => ['parameters' => []] + ] + ] + ], + ], + 'validConfigWithParametersNode' => [ + [ + 'config' => [ + 0 => [ + 'file' => [ + 0 => [ + 'name' => 'fileName', + 'providers' => [ + 0 => [ + 'reportProvider' => [ + 0 => [ + 'parameters' => [ + 0 => ['name' => ['reportName']] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ], + [ + 'fileName' => [ + 'name' => 'fileName', + 'providers' => [ + 'reportProvider' => [ + 'parameters' => [ + 'name' => 'reportName' + ] + ] + ] + ] + ], + ], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php new file mode 100644 index 0000000000000..6aa9c7ef3106c --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/ReaderTest.php @@ -0,0 +1,108 @@ +mapperMock = $this->getMockBuilder(Mapper::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->readerXmlMock = $this->getMockBuilder(ReaderInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->readerDbMock = $this->getMockBuilder(ReaderInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->reader = $this->objectManagerHelper->getObject( + Reader::class, + [ + 'mapper' => $this->mapperMock, + 'readers' => [ + $this->readerXmlMock, + $this->readerDbMock, + ], + ] + ); + } + + /** + * @return void + */ + public function testRead() + { + $scope = 'store'; + $xmlReaderResult = [ + 'config' => ['node1' => ['node2' => 'node4']] + ]; + $dbReaderResult = [ + 'config' => ['node1' => ['node2' => 'node3']] + ]; + $mapperResult = ['node2' => ['node3', 'node4']]; + + $this->readerXmlMock + ->expects($this->once()) + ->method('read') + ->with($scope) + ->willReturn($xmlReaderResult); + + $this->readerDbMock + ->expects($this->once()) + ->method('read') + ->with($scope) + ->willReturn($dbReaderResult); + + $this->mapperMock + ->expects($this->once()) + ->method('execute') + ->with(array_merge_recursive($xmlReaderResult, $dbReaderResult)) + ->willReturn($mapperResult); + + $this->assertSame($mapperResult, $this->reader->read($scope)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php new file mode 100644 index 0000000000000..c13205d34f25b --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Config/Source/VerticalTest.php @@ -0,0 +1,60 @@ +objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\Model\Config\Source\Vertical::class, + [ + 'verticals' => [ + 'Apps and Games', + 'Athletic/Sporting Goods', + 'Art and Design' + ] + ] + ); + } + + /** + * @return void + */ + public function testToOptionArray() + { + $expectedOptionsArray = [ + ['value' => '', 'label' => __('--Please Select--')], + ['value' => 'Apps and Games', 'label' => __('Apps and Games')], + ['value' => 'Athletic/Sporting Goods', 'label' => __('Athletic/Sporting Goods')], + ['value' => 'Art and Design', 'label' => __('Art and Design')] + ]; + + $this->assertEquals( + $expectedOptionsArray, + $this->subject->toOptionArray() + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php new file mode 100644 index 0000000000000..8739219ebdf09 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ConfigTest.php @@ -0,0 +1,68 @@ +dataInterfaceMock = $this->getMockBuilder(DataInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->config = $this->objectManagerHelper->getObject( + Config::class, + [ + 'data' => $this->dataInterfaceMock, + ] + ); + } + + /** + * @return void + */ + public function testGet() + { + $key = 'configKey'; + $defaultValue = 'mock'; + $configValue = 'emptyString'; + + $this->dataInterfaceMock + ->expects($this->once()) + ->method('get') + ->with($key, $defaultValue) + ->willReturn($configValue); + + $this->assertSame($configValue, $this->config->get($key, $defaultValue)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php new file mode 100644 index 0000000000000..f8f3919b2489e --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php @@ -0,0 +1,218 @@ +curlMock = $this->getMockBuilder( + \Magento\Framework\HTTP\Adapter\Curl::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->loggerMock = $this->getMockBuilder( + \Psr\Log\LoggerInterface::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->curlFactoryMock = $this->getMockBuilder(CurlFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + $this->curlFactoryMock->expects($this->any()) + ->method('create') + ->willReturn($this->curlMock); + + $this->responseFactoryMock = $this->getMockBuilder( + \Magento\Analytics\Model\Connector\Http\ResponseFactory::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->converterMock = $this->createJsonConverter(); + + $this->objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\Model\Connector\Http\Client\Curl::class, + [ + 'curlFactory' => $this->curlFactoryMock, + 'responseFactory' => $this->responseFactoryMock, + 'converter' => $this->converterMock, + 'logger' => $this->loggerMock, + ] + ); + } + + /** + * Returns test parameters for request. + * + * @return array + */ + public function getTestData() + { + return [ + [ + 'data' => [ + 'version' => '1.1', + 'body'=> ['name' => 'value'], + 'url' => 'http://www.mystore.com', + 'headers' => [JsonConverter::CONTENT_TYPE_HEADER], + 'method' => \Magento\Framework\HTTP\ZendClient::POST, + ] + ] + ]; + } + + /** + * @return void + * @dataProvider getTestData + */ + public function testRequestSuccess(array $data) + { + $responseString = 'This is response.'; + $response = new \Zend_Http_Response(201, [], $responseString); + $this->curlMock->expects($this->once()) + ->method('write') + ->with( + $data['method'], + $data['url'], + $data['version'], + $data['headers'], + json_encode($data['body']) + ); + $this->curlMock->expects($this->once()) + ->method('read') + ->willReturn($responseString); + $this->curlMock->expects($this->any()) + ->method('getErrno') + ->willReturn(0); + + $this->responseFactoryMock->expects($this->any()) + ->method('create') + ->with($responseString) + ->willReturn($response); + + $this->assertEquals( + $response, + $this->subject->request( + $data['method'], + $data['url'], + $data['body'], + $data['headers'], + $data['version'] + ) + ); + } + + /** + * @return void + * @dataProvider getTestData + */ + public function testRequestError(array $data) + { + $response = new \Zend_Http_Response(0, []); + $this->curlMock->expects($this->once()) + ->method('write') + ->with( + $data['method'], + $data['url'], + $data['version'], + $data['headers'], + json_encode($data['body']) + ); + $this->curlMock->expects($this->once()) + ->method('read'); + $this->curlMock->expects($this->atLeastOnce()) + ->method('getErrno') + ->willReturn(1); + $this->curlMock->expects($this->atLeastOnce()) + ->method('getError') + ->willReturn('CURL error.'); + + $this->loggerMock->expects($this->once()) + ->method('critical') + ->with( + new \Exception( + 'MBI service CURL connection error #1: CURL error.' + ) + ); + + $this->assertEquals( + $response, + $this->subject->request( + $data['method'], + $data['url'], + $data['body'], + $data['headers'], + $data['version'] + ) + ); + } + + /** + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function createJsonConverter() + { + $converterMock = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); + $converterMock->expects($this->any())->method('toBody')->willReturnCallback(function ($value) { + return json_encode($value); + }); + $converterMock->expects($this->any()) + ->method('getContentTypeHeader') + ->willReturn(JsonConverter::CONTENT_TYPE_HEADER); + return $converterMock; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php new file mode 100644 index 0000000000000..60a19f3d5079e --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php @@ -0,0 +1,34 @@ +assertEquals(JsonConverter::CONTENT_TYPE_HEADER, $converter->getContentTypeHeader()); + } + + public function testConvertBody() + { + $body = '{"token": "secret-token"}'; + $converter = new JsonConverter(); + $this->assertEquals(json_decode($body, 1), $converter->fromBody($body)); + } + + public function testConvertData() + { + $data = ["token" => "secret-token"]; + $converter = new JsonConverter(); + $this->assertEquals(json_encode($data), $converter->toBody($data)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php new file mode 100644 index 0000000000000..7c3c484843285 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php @@ -0,0 +1,39 @@ + 'testValue']; + $response = new \Zend_Http_Response(201, [], json_encode($expectedBody)); + $responseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) + ->getMockForAbstractClass(); + $responseHandlerMock->expects($this->once()) + ->method('handleResponse') + ->with($expectedBody) + ->willReturn(true); + $notFoundResponseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) + ->getMockForAbstractClass(); + $notFoundResponseHandlerMock->expects($this->never())->method('handleResponse'); + $responseResolver = new ResponseResolver( + new JsonConverter(), + [ + 201 => $responseHandlerMock, + 404 => $notFoundResponseHandlerMock, + ] + ); + $this->assertTrue($responseResolver->getResult($response)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php new file mode 100644 index 0000000000000..cee3877631c2e --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php @@ -0,0 +1,107 @@ +analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $successHandler = $this->getMockBuilder(\Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface::class) + ->getMockForAbstractClass(); + $successHandler->method('handleResponse') + ->willReturn(true); + + $this->notifyDataChangedCommand = new NotifyDataChangedCommand( + $this->analyticsTokenMock, + $this->httpClientMock, + $this->configMock, + new ResponseResolver(new JsonConverter(), [201 => $successHandler]), + $this->loggerMock + ); + } + + public function testExecuteSuccess() + { + $configVal = "Config val"; + $token = "Secret token!"; + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + $this->configMock->expects($this->any()) + ->method('getValue') + ->willReturn($configVal); + $this->analyticsTokenMock->expects($this->once()) + ->method('getToken') + ->willReturn($token); + $this->httpClientMock->expects($this->once()) + ->method('request') + ->with( + ZendClient::POST, + $configVal, + ['access-token' => $token, 'url' => $configVal] + )->willReturn(new \Zend_Http_Response(201, [])); + $this->assertTrue($this->notifyDataChangedCommand->execute()); + } + + public function testExecuteWithoutToken() + { + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + $this->httpClientMock->expects($this->never()) + ->method('request'); + $this->assertFalse($this->notifyDataChangedCommand->execute()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php new file mode 100644 index 0000000000000..8a3f4efb15cf4 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php @@ -0,0 +1,187 @@ +loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->subject = new OTPRequest( + $this->analyticsTokenMock, + $this->httpClientMock, + $this->configMock, + $this->responseResolverMock, + $this->loggerMock + ); + } + + /** + * Returns test parameters for request. + * + * @return array + */ + private function getTestData() + { + return [ + 'otp' => 'thisisotp', + 'url' => 'http://www.mystore.com', + 'access-token' => 'thisisaccesstoken', + 'method' => \Magento\Framework\HTTP\ZendClient::POST, + 'body'=> ['access-token' => 'thisisaccesstoken','url' => 'http://www.mystore.com'], + ]; + } + + /** + * @return void + */ + public function testCallSuccess() + { + $data = $this->getTestData(); + + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + $this->analyticsTokenMock->expects($this->once()) + ->method('getToken') + ->willReturn($data['access-token']); + + $this->configMock->expects($this->any()) + ->method('getValue') + ->willReturn($data['url']); + + $this->httpClientMock->expects($this->once()) + ->method('request') + ->with( + $data['method'], + $data['url'], + $data['body'] + ) + ->willReturn(new \Zend_Http_Response(201, [])); + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->willReturn($data['otp']); + + $this->assertEquals( + $data['otp'], + $this->subject->call() + ); + } + + /** + * @return void + */ + public function testCallNoAccessToken() + { + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + + $this->httpClientMock->expects($this->never()) + ->method('request'); + + $this->assertFalse($this->subject->call()); + } + + /** + * @return void + */ + public function testCallNoOtp() + { + $data = $this->getTestData(); + + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + $this->analyticsTokenMock->expects($this->once()) + ->method('getToken') + ->willReturn($data['access-token']); + + $this->configMock->expects($this->any()) + ->method('getValue') + ->willReturn($data['url']); + + $this->httpClientMock->expects($this->once()) + ->method('request') + ->with( + $data['method'], + $data['url'], + $data['body'] + ) + ->willReturn(new \Zend_Http_Response(0, [])); + + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->willReturn(false); + + $this->loggerMock->expects($this->once()) + ->method('warning'); + + $this->assertFalse($this->subject->call()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php new file mode 100644 index 0000000000000..0ff36cca5db2d --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php @@ -0,0 +1,22 @@ +assertFalse($OTPHandler->handleResponse([])); + $expectedOtp = 123; + $this->assertEquals($expectedOtp, $OTPHandler->handleResponse(['otp' => $expectedOtp])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php new file mode 100644 index 0000000000000..707003149bcfd --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php @@ -0,0 +1,36 @@ +getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + $analyticsToken->expects($this->once()) + ->method('storeToken') + ->with(null); + $subscriptionHandler = $this->getMockBuilder(SubscriptionHandler::class) + ->disableOriginalConstructor() + ->getMock(); + $subscriptionStatusProvider = $this->getMockBuilder(SubscriptionStatusProvider::class) + ->disableOriginalConstructor() + ->getMock(); + $subscriptionStatusProvider->method('getStatus')->willReturn(SubscriptionStatusProvider::ENABLED); + $reSignUpHandler = new ReSignUp($analyticsToken, $subscriptionHandler, $subscriptionStatusProvider); + $this->assertFalse($reSignUpHandler->handleResponse([])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php new file mode 100644 index 0000000000000..81711cfc56950 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php @@ -0,0 +1,30 @@ +getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + $analyticsToken->expects($this->once()) + ->method('storeToken') + ->with($accessToken); + $signUpHandler = new SignUp($analyticsToken, new JsonConverter()); + $this->assertFalse($signUpHandler->handleResponse([])); + $this->assertEquals($accessToken, $signUpHandler->handleResponse(['access-token' => $accessToken])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php new file mode 100644 index 0000000000000..7779357e8bea7 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php @@ -0,0 +1,20 @@ +assertTrue($updateHandler->handleResponse([])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php new file mode 100644 index 0000000000000..5593496a957b7 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php @@ -0,0 +1,174 @@ +analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + $this->integrationManagerMock = $this->getMockBuilder(IntegrationManager::class) + ->disableOriginalConstructor() + ->getMock(); + $this->integrationToken = $this->getMockBuilder(IntegrationToken::class) + ->disableOriginalConstructor() + ->getMock(); + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->signUpCommand = new SignUpCommand( + $this->analyticsTokenMock, + $this->integrationManagerMock, + $this->configMock, + $this->httpClientMock, + $this->loggerMock, + $this->responseResolverMock + ); + } + + public function testExecuteSuccess() + { + $this->integrationManagerMock->expects($this->once()) + ->method('generateToken') + ->willReturn($this->integrationToken); + $this->integrationManagerMock->expects($this->once()) + ->method('activateIntegration') + ->willReturn(true); + $data = $this->getTestData(); + + $this->configMock->expects($this->any()) + ->method('getValue') + ->willReturn($data['url']); + $this->integrationToken->expects($this->any()) + ->method('getData') + ->with('token') + ->willReturn($data['integration-token']); + $httpResponse = new \Zend_Http_Response(201, [], '{"access-token": "' . $data['access-token'] . '"}'); + $this->httpClientMock->expects($this->once()) + ->method('request') + ->with( + $data['method'], + $data['url'], + $data['body'] + ) + ->willReturn($httpResponse); + $this->responseResolverMock->expects($this->any()) + ->method('getResult') + ->with($httpResponse) + ->willReturn(true); + $this->assertTrue($this->signUpCommand->execute()); + } + + public function testExecuteFailureCannotGenerateToken() + { + $this->integrationManagerMock->expects($this->once()) + ->method('generateToken') + ->willReturn(false); + $this->integrationManagerMock->expects($this->never()) + ->method('activateIntegration'); + $this->assertFalse($this->signUpCommand->execute()); + } + + public function testExecuteFailureResponseIsEmpty() + { + $this->integrationManagerMock->expects($this->once()) + ->method('generateToken') + ->willReturn($this->integrationToken); + $this->integrationManagerMock->expects($this->once()) + ->method('activateIntegration') + ->willReturn(true); + $httpResponse = new \Zend_Http_Response(0, []); + $this->httpClientMock->expects($this->once()) + ->method('request') + ->willReturn($httpResponse); + $this->responseResolverMock->expects($this->any()) + ->method('getResult') + ->willReturn(false); + $this->assertFalse($this->signUpCommand->execute()); + } + + /** + * Returns test parameters for request. + * + * @return array + */ + private function getTestData() + { + return [ + 'url' => 'http://www.mystore.com', + 'access-token' => 'thisisaccesstoken', + 'integration-token' => 'thisisintegrationtoken', + 'headers' => [JsonConverter::CONTENT_TYPE_HEADER], + 'method' => \Magento\Framework\HTTP\ZendClient::POST, + 'body'=> ['token' => 'thisisintegrationtoken','url' => 'http://www.mystore.com'], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php new file mode 100644 index 0000000000000..47253a13530e5 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php @@ -0,0 +1,143 @@ +analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->updateCommand = new UpdateCommand( + $this->analyticsTokenMock, + $this->httpClientMock, + $this->configMock, + $this->loggerMock, + $this->flagManagerMock, + $this->responseResolverMock + ); + } + + public function testExecuteSuccess() + { + $url = "old.localhost.com"; + $configVal = "Config val"; + $token = "Secret token!"; + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + + $this->configMock->expects($this->any()) + ->method('getValue') + ->willReturn($configVal); + + $this->flagManagerMock->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE) + ->willReturn($url); + + $this->analyticsTokenMock->expects($this->once()) + ->method('getToken') + ->willReturn($token); + + $this->httpClientMock->expects($this->once()) + ->method('request') + ->with( + ZendClient::PUT, + $configVal, + [ + 'url' => $url, + 'new-url' => $configVal, + 'access-token' => $token + ] + )->willReturn(new \Zend_Http_Response(200, [])); + + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->willReturn(true); + + $this->assertTrue($this->updateCommand->execute()); + } + + public function testExecuteWithoutToken() + { + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + + $this->assertFalse($this->updateCommand->execute()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php new file mode 100644 index 0000000000000..4414b81cbc183 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ConnectorTest.php @@ -0,0 +1,70 @@ +objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->signUpCommandMock = $this->getMockBuilder(SignUpCommand::class) + ->disableOriginalConstructor() + ->getMock(); + $this->commands = ['signUp' => SignUpCommand::class]; + $this->connector = new Connector($this->commands, $this->objectManagerMock); + } + + public function testExecute() + { + $commandName = 'signUp'; + $this->objectManagerMock->expects($this->once()) + ->method('create') + ->with($this->commands[$commandName]) + ->willReturn($this->signUpCommandMock); + $this->signUpCommandMock->expects($this->once()) + ->method('execute') + ->willReturn(true); + $this->assertTrue($this->connector->execute($commandName)); + } + + /** + * @expectedException \Magento\Framework\Exception\NotFoundException + */ + public function testExecuteCommandNotFound() + { + $commandName = 'register'; + $this->connector->execute($commandName); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php new file mode 100644 index 0000000000000..a896c309b4007 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/CryptographerTest.php @@ -0,0 +1,226 @@ +analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->encodedContextFactoryMock = $this->getMockBuilder(EncodedContextFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + + $this->encodedContextMock = $this->getMockBuilder(EncodedContext::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->key = ''; + $this->source = ''; + $this->initializationVectors = []; + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->cryptographer = $this->objectManagerHelper->getObject( + Cryptographer::class, + [ + 'analyticsToken' => $this->analyticsTokenMock, + 'encodedContextFactory' => $this->encodedContextFactoryMock, + 'cipherMethod' => $this->cipherMethod, + ] + ); + } + + /** + * @return void + */ + public function testEncode() + { + $token = 'some-token-value'; + $this->source = 'Some text'; + $this->key = hash('sha256', $token); + + $checkEncodedContext = function ($parameters) { + $emptyRequiredParameters = + array_diff(['content', 'initializationVector'], array_keys(array_filter($parameters))); + if ($emptyRequiredParameters) { + return false; + } + + $encryptedData = openssl_encrypt( + $this->source, + $this->cipherMethod, + $this->key, + OPENSSL_RAW_DATA, + $parameters['initializationVector'] + ); + + return ($encryptedData === $parameters['content']); + }; + + $this->analyticsTokenMock + ->expects($this->once()) + ->method('getToken') + ->with() + ->willReturn($token); + + $this->encodedContextFactoryMock + ->expects($this->once()) + ->method('create') + ->with($this->callback($checkEncodedContext)) + ->willReturn($this->encodedContextMock); + + $this->assertSame($this->encodedContextMock, $this->cryptographer->encode($this->source)); + } + + /** + * @return void + */ + public function testEncodeUniqueInitializationVector() + { + $this->source = 'Some text'; + $token = 'some-token-value'; + + $registerInitializationVector = function ($parameters) { + if (empty($parameters['initializationVector'])) { + return false; + } + + $this->initializationVectors[] = $parameters['initializationVector']; + + return true; + }; + + $this->analyticsTokenMock + ->expects($this->exactly(2)) + ->method('getToken') + ->with() + ->willReturn($token); + + $this->encodedContextFactoryMock + ->expects($this->exactly(2)) + ->method('create') + ->with($this->callback($registerInitializationVector)) + ->willReturn($this->encodedContextMock); + + $this->assertSame($this->encodedContextMock, $this->cryptographer->encode($this->source)); + $this->assertSame($this->encodedContextMock, $this->cryptographer->encode($this->source)); + $this->assertCount(2, array_unique($this->initializationVectors)); + } + + /** + * @expectedException \Magento\Framework\Exception\LocalizedException + * @dataProvider encodeNotValidSourceDataProvider + */ + public function testEncodeNotValidSource($source) + { + $this->cryptographer->encode($source); + } + + /** + * @return array + */ + public function encodeNotValidSourceDataProvider() + { + return [ + 'Array' => [[]], + 'Empty string' => [''], + ]; + } + + /** + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testEncodeNotValidCipherMethod() + { + $source = 'Some string'; + $cryptographer = $this->objectManagerHelper->getObject( + Cryptographer::class, + [ + 'cipherMethod' => 'Wrong-method', + ] + ); + + $cryptographer->encode($source); + } + + /** + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testEncodeTokenNotValid() + { + $source = 'Some string'; + + $this->analyticsTokenMock + ->expects($this->once()) + ->method('getToken') + ->with() + ->willReturn(null); + + $this->cryptographer->encode($source); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php b/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php new file mode 100644 index 0000000000000..a1a7c54510681 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/EncodedContextTest.php @@ -0,0 +1,61 @@ +objectManagerHelper = new ObjectManagerHelper($this); + } + + /** + * @param string $content + * @param string|null $initializationVector + * @return void + * @dataProvider constructDataProvider + */ + public function testConstruct($content, $initializationVector) + { + $constructorArguments = [ + 'content' => $content, + 'initializationVector' => $initializationVector, + ]; + /** @var EncodedContext $encodedContext */ + $encodedContext = $this->objectManagerHelper->getObject( + EncodedContext::class, + array_filter($constructorArguments) + ); + + $this->assertSame($content, $encodedContext->getContent()); + $this->assertSame($initializationVector ?: '', $encodedContext->getInitializationVector()); + } + + /** + * @return array + */ + public function constructDataProvider() + { + return [ + 'Without Initialization Vector' => ['content text', null], + 'With Initialization Vector' => ['content text', 'c51sd3c4sd68c5sd'], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php new file mode 100644 index 0000000000000..1582c241bf45d --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerNotificationTest.php @@ -0,0 +1,74 @@ +objectManagerHelper = new ObjectManagerHelper($this); + } + + /** + * @return void + */ + public function testThatNotifyExecuted() + { + $expectedResult = true; + $notifyCommandName = 'notifyDataChanged'; + $exportDataHandlerMockObject = $this->createExportDataHandlerMock(); + $analyticsConnectorMockObject = $this->createAnalyticsConnectorMock(); + /** + * @var $exportDataHandlerNotification ExportDataHandlerNotification + */ + $exportDataHandlerNotification = $this->objectManagerHelper->getObject( + ExportDataHandlerNotification::class, + [ + 'exportDataHandler' => $exportDataHandlerMockObject, + 'connector' => $analyticsConnectorMockObject, + ] + ); + $exportDataHandlerMockObject->expects($this->once()) + ->method('prepareExportData') + ->willReturn($expectedResult); + $analyticsConnectorMockObject->expects($this->once()) + ->method('execute') + ->with($notifyCommandName); + $this->assertEquals($expectedResult, $exportDataHandlerNotification->prepareExportData()); + } + + /** + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function createExportDataHandlerMock() + { + return $this->getMockBuilder(ExportDataHandler::class)->disableOriginalConstructor()->getMock(); + } + + /** + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function createAnalyticsConnectorMock() + { + return $this->getMockBuilder(Connector::class)->disableOriginalConstructor()->getMock(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php new file mode 100644 index 0000000000000..6ffb61d088567 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ExportDataHandlerTest.php @@ -0,0 +1,270 @@ +filesystemMock = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->archiveMock = $this->getMockBuilder(Archive::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->reportWriterMock = $this->getMockBuilder(ReportWriterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->cryptographerMock = $this->getMockBuilder(Cryptographer::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileRecorderMock = $this->getMockBuilder(FileRecorder::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->directoryMock = $this->getMockBuilder(WriteInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->encodedContextMock = $this->getMockBuilder(EncodedContext::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->exportDataHandler = $this->objectManagerHelper->getObject( + ExportDataHandler::class, + [ + 'filesystem' => $this->filesystemMock, + 'archive' => $this->archiveMock, + 'reportWriter' => $this->reportWriterMock, + 'cryptographer' => $this->cryptographerMock, + 'fileRecorder' => $this->fileRecorderMock, + 'subdirectoryPath' => $this->subdirectoryPath, + 'archiveName' => $this->archiveName, + ] + ); + } + + /** + * @param bool $isArchiveSourceDirectory + * @dataProvider prepareExportDataDataProvider + */ + public function testPrepareExportData($isArchiveSourceDirectory) + { + $tmpFilesDirectoryPath = $this->subdirectoryPath . 'tmp/'; + $archiveRelativePath = $this->subdirectoryPath . $this->archiveName; + + $archiveSource = $isArchiveSourceDirectory ? (__DIR__) : '/tmp/' . $tmpFilesDirectoryPath; + $archiveAbsolutePath = '/tmp/' . $archiveRelativePath; + + $this->filesystemMock + ->expects($this->once()) + ->method('getDirectoryWrite') + ->with(DirectoryList::SYS_TMP) + ->willReturn($this->directoryMock); + $this->directoryMock + ->expects($this->exactly(4)) + ->method('delete') + ->withConsecutive( + [$tmpFilesDirectoryPath], + [$archiveRelativePath] + ); + + $this->directoryMock + ->expects($this->exactly(4)) + ->method('getAbsolutePath') + ->withConsecutive( + [$tmpFilesDirectoryPath], + [$tmpFilesDirectoryPath], + [$archiveRelativePath], + [$archiveRelativePath] + ) + ->willReturnOnConsecutiveCalls( + $archiveSource, + $archiveSource, + $archiveAbsolutePath, + $archiveAbsolutePath + ); + + $this->reportWriterMock + ->expects($this->once()) + ->method('write') + ->with($this->directoryMock, $tmpFilesDirectoryPath); + + $this->directoryMock + ->expects($this->exactly(2)) + ->method('isExist') + ->withConsecutive( + [$tmpFilesDirectoryPath], + [$archiveRelativePath] + ) + ->willReturnOnConsecutiveCalls( + true, + true + ); + + $this->directoryMock + ->expects($this->once()) + ->method('create') + ->with(dirname($archiveRelativePath)); + + $this->archiveMock + ->expects($this->once()) + ->method('pack') + ->with( + $archiveSource, + $archiveAbsolutePath, + $isArchiveSourceDirectory ? true : false + ); + + $fileContent = 'Some text'; + $this->directoryMock + ->expects($this->once()) + ->method('readFile') + ->with($archiveRelativePath) + ->willReturn($fileContent); + + $this->cryptographerMock + ->expects($this->once()) + ->method('encode') + ->with($fileContent) + ->willReturn($this->encodedContextMock); + + $this->fileRecorderMock + ->expects($this->once()) + ->method('recordNewFile') + ->with($this->encodedContextMock); + + $this->assertTrue($this->exportDataHandler->prepareExportData()); + } + + /** + * @return array + */ + public function prepareExportDataDataProvider() + { + return [ + 'Data source for archive is directory' => [true], + 'Data source for archive doesn\'t directory' => [false], + ]; + } + + /** + * @return void + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testPrepareExportDataWithLocalizedException() + { + $tmpFilesDirectoryPath = $this->subdirectoryPath . 'tmp/'; + $archivePath = $this->subdirectoryPath . $this->archiveName; + + $this->filesystemMock + ->expects($this->once()) + ->method('getDirectoryWrite') + ->with(DirectoryList::SYS_TMP) + ->willReturn($this->directoryMock); + $this->reportWriterMock + ->expects($this->once()) + ->method('write') + ->with($this->directoryMock, $tmpFilesDirectoryPath); + $this->directoryMock + ->expects($this->exactly(3)) + ->method('delete') + ->withConsecutive( + [$tmpFilesDirectoryPath], + [$tmpFilesDirectoryPath], + [$archivePath] + ); + $this->directoryMock + ->expects($this->exactly(2)) + ->method('getAbsolutePath') + ->with($tmpFilesDirectoryPath); + $this->directoryMock + ->expects($this->once()) + ->method('isExist') + ->with($tmpFilesDirectoryPath) + ->willReturn(false); + + $this->assertNull($this->exportDataHandler->prepareExportData()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php new file mode 100644 index 0000000000000..da5f6af3ca4e1 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoManagerTest.php @@ -0,0 +1,194 @@ +flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileInfoFactoryMock = $this->getMockBuilder(FileInfoFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileInfoMock = $this->getMockBuilder(FileInfo::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->fileInfoManager = $this->objectManagerHelper->getObject( + FileInfoManager::class, + [ + 'flagManager' => $this->flagManagerMock, + 'fileInfoFactory' => $this->fileInfoFactoryMock, + 'flagCode' => $this->flagCode, + 'encodedParameters' => $this->encodedParameters, + ] + ); + } + + /** + * @return void + */ + public function testSave() + { + $path = 'path/to/file'; + $initializationVector = openssl_random_pseudo_bytes(16); + $parameters = [ + 'path' => $path, + 'initializationVector' => $initializationVector, + ]; + + $this->fileInfoMock + ->expects($this->once()) + ->method('getPath') + ->with() + ->willReturn($path); + $this->fileInfoMock + ->expects($this->once()) + ->method('getInitializationVector') + ->with() + ->willReturn($initializationVector); + + foreach ($this->encodedParameters as $encodedParameter) { + $parameters[$encodedParameter] = base64_encode($parameters[$encodedParameter]); + } + $this->flagManagerMock + ->expects($this->once()) + ->method('saveFlag') + ->with($this->flagCode, $parameters); + + $this->assertTrue($this->fileInfoManager->save($this->fileInfoMock)); + } + + /** + * @param string|null $path + * @param string|null $initializationVector + * @dataProvider saveWithLocalizedExceptionDataProvider + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testSaveWithLocalizedException($path, $initializationVector) + { + $this->fileInfoMock + ->expects($this->once()) + ->method('getPath') + ->with() + ->willReturn($path); + $this->fileInfoMock + ->expects($this->once()) + ->method('getInitializationVector') + ->with() + ->willReturn($initializationVector); + + $this->fileInfoManager->save($this->fileInfoMock); + } + + /** + * @return array + */ + public function saveWithLocalizedExceptionDataProvider() + { + return [ + 'Empty FileInfo' => [null, null], + 'FileInfo without IV' => ['path/to/file', null], + ]; + } + + /** + * @dataProvider loadDataProvider + * @param array|null $parameters + */ + public function testLoad($parameters) + { + $this->flagManagerMock + ->expects($this->once()) + ->method('getFlagData') + ->with($this->flagCode) + ->willReturn($parameters); + + $processedParameters = $parameters ?: []; + $encodedParameters = array_intersect($this->encodedParameters, array_keys($processedParameters)); + foreach ($encodedParameters as $encodedParameter) { + $processedParameters[$encodedParameter] = base64_decode($processedParameters[$encodedParameter]); + } + + $this->fileInfoFactoryMock + ->expects($this->once()) + ->method('create') + ->with($processedParameters) + ->willReturn($this->fileInfoMock); + + $this->assertSame($this->fileInfoMock, $this->fileInfoManager->load()); + } + + /** + * @return array + */ + public function loadDataProvider() + { + return [ + 'Empty flag data' => [null], + 'Correct flag data' => [[ + 'path' => 'path/to/file', + 'initializationVector' => 'xUJjl54MVke+FvMFSBpRSA==', + ]], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php new file mode 100644 index 0000000000000..43ce833f1f03f --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/FileInfoTest.php @@ -0,0 +1,62 @@ +objectManagerHelper = new ObjectManagerHelper($this); + } + + /** + * @param string|null $path + * @param string|null $initializationVector + * @return void + * @dataProvider constructDataProvider + */ + public function testConstruct($path, $initializationVector) + { + $constructorArguments = [ + 'path' => $path, + 'initializationVector' => $initializationVector, + ]; + /** @var FileInfo $fileInfo */ + $fileInfo = $this->objectManagerHelper->getObject( + FileInfo::class, + array_filter($constructorArguments) + ); + + $this->assertSame($path ?: '', $fileInfo->getPath()); + $this->assertSame($initializationVector ?: '', $fileInfo->getInitializationVector()); + } + + /** + * @return array + */ + public function constructDataProvider() + { + return [ + 'Degenerate object' => [null, null], + 'Without Initialization Vector' => ['content text', null], + 'With Initialization Vector' => ['content text', 'c51sd3c4sd68c5sd'], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php new file mode 100644 index 0000000000000..3c9520bdd995b --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/FileRecorderTest.php @@ -0,0 +1,209 @@ +fileInfoManagerMock = $this->getMockBuilder(FileInfoManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileInfoFactoryMock = $this->getMockBuilder(FileInfoFactory::class) + ->setMethods(['create']) + ->disableOriginalConstructor() + ->getMock(); + + $this->filesystemMock = $this->getMockBuilder(Filesystem::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->fileInfoMock = $this->getMockBuilder(FileInfo::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->directoryMock = $this->getMockBuilder(WriteInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->encodedContextMock = $this->getMockBuilder(EncodedContext::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->fileRecorder = $this->objectManagerHelper->getObject( + FileRecorder::class, + [ + 'fileInfoManager' => $this->fileInfoManagerMock, + 'fileInfoFactory' => $this->fileInfoFactoryMock, + 'filesystem' => $this->filesystemMock, + 'fileSubdirectoryPath' => $this->fileSubdirectoryPath, + 'encodedFileName' => $this->encodedFileName, + ] + ); + } + + /** + * @param string $pathToExistingFile + * @dataProvider recordNewFileDataProvider + */ + public function testRecordNewFile($pathToExistingFile) + { + $content = openssl_random_pseudo_bytes(200); + + $this->filesystemMock + ->expects($this->once()) + ->method('getDirectoryWrite') + ->with(DirectoryList::MEDIA) + ->willReturn($this->directoryMock); + + $this->encodedContextMock + ->expects($this->once()) + ->method('getContent') + ->with() + ->willReturn($content); + + $hashLength = 64; + $fileRelativePathPattern = '#' . preg_quote($this->fileSubdirectoryPath, '#') + . '.{' . $hashLength . '}/' . preg_quote($this->encodedFileName, '#') . '#'; + $this->directoryMock + ->expects($this->once()) + ->method('writeFile') + ->with($this->matchesRegularExpression($fileRelativePathPattern), $content) + ->willReturn($this->directoryMock); + + $this->fileInfoManagerMock + ->expects($this->once()) + ->method('load') + ->with() + ->willReturn($this->fileInfoMock); + + $this->encodedContextMock + ->expects($this->once()) + ->method('getInitializationVector') + ->with() + ->willReturn('init_vector***'); + + /** register file */ + $this->fileInfoFactoryMock + ->expects($this->once()) + ->method('create') + ->with($this->callback( + function ($parameters) { + return !empty($parameters['path']) && ('init_vector***' === $parameters['initializationVector']); + } + )) + ->willReturn($this->fileInfoMock); + $this->fileInfoManagerMock + ->expects($this->once()) + ->method('save') + ->with($this->fileInfoMock); + + /** remove old file */ + $this->fileInfoMock + ->expects($this->exactly($pathToExistingFile ? 3 : 1)) + ->method('getPath') + ->with() + ->willReturn($pathToExistingFile); + $directoryName = dirname($pathToExistingFile); + if ($directoryName === '.') { + $this->directoryMock + ->expects($this->once()) + ->method('delete') + ->with($pathToExistingFile); + } elseif ($directoryName) { + $this->directoryMock + ->expects($this->exactly(2)) + ->method('delete') + ->withConsecutive( + [$pathToExistingFile], + [$directoryName] + ); + } + + $this->assertTrue($this->fileRecorder->recordNewFile($this->encodedContextMock)); + } + + /** + * @return array + */ + public function recordNewFileDataProvider() + { + return [ + 'File doesn\'t exist' => [''], + 'Existing file into subdirectory' => ['dir_name/file.txt'], + 'Existing file doesn\'t into subdirectory' => ['file.txt'], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php b/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php new file mode 100644 index 0000000000000..3076a22c85be4 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/IntegrationManagerTest.php @@ -0,0 +1,228 @@ +integrationServiceMock = $this->getMockBuilder(IntegrationServiceInterface::class) + ->getMock(); + $this->configMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->oauthServiceMock = $this->getMockBuilder(OauthServiceInterface::class) + ->getMock(); + $this->integrationMock = $this->getMockBuilder(Integration::class) + ->disableOriginalConstructor() + ->setMethods([ + 'getId', + 'getConsumerId' + ]) + ->getMock(); + $this->integrationManager = $objectManagerHelper->getObject( + IntegrationManager::class, + [ + 'integrationService' => $this->integrationServiceMock, + 'oauthService' => $this->oauthServiceMock, + 'config' => $this->configMock + ] + ); + } + + /** + * @param string $status + * + * @return array + */ + private function getIntegrationUserData($status) + { + return [ + 'name' => 'ma-integration-user', + 'status' => $status, + 'all_resources' => false, + 'resource' => [ + 'Magento_Analytics::analytics', + 'Magento_Analytics::analytics_api' + ], + ]; + } + + /** + * @return void + */ + public function testActivateIntegrationSuccess() + { + $this->integrationServiceMock->expects($this->once()) + ->method('findByName') + ->with('ma-integration-user') + ->willReturn($this->integrationMock); + $this->integrationMock->expects($this->exactly(2)) + ->method('getId') + ->willReturn(100500); + $integrationData = $this->getIntegrationUserData(Integration::STATUS_ACTIVE); + $integrationData['integration_id'] = 100500; + $this->configMock->expects($this->exactly(2)) + ->method('getConfigDataValue') + ->with('analytics/integration_name', null, null) + ->willReturn('ma-integration-user'); + $this->integrationServiceMock->expects($this->once()) + ->method('update') + ->with($integrationData); + $this->assertTrue($this->integrationManager->activateIntegration()); + } + + /** + * @expectedException \Magento\Framework\Exception\NoSuchEntityException + */ + public function testActivateIntegrationFailureNoSuchEntity() + { + $this->integrationServiceMock->expects($this->once()) + ->method('findByName') + ->with('ma-integration-user') + ->willReturn($this->integrationMock); + $this->integrationMock->expects($this->once()) + ->method('getId') + ->willReturn(null); + $this->configMock->expects($this->once()) + ->method('getConfigDataValue') + ->with('analytics/integration_name', null, null) + ->willReturn('ma-integration-user'); + $this->integrationServiceMock->expects($this->never()) + ->method('update'); + $this->integrationManager->activateIntegration(); + } + + /** + * @dataProvider integrationIdDataProvider + * + * @param int|null $integrationId If null integration is absent. + * @return void + */ + public function testGetTokenNewIntegration($integrationId) + { + $this->configMock->expects($this->atLeastOnce()) + ->method('getConfigDataValue') + ->with('analytics/integration_name', null, null) + ->willReturn('ma-integration-user'); + $this->integrationServiceMock->expects($this->once()) + ->method('findByName') + ->with('ma-integration-user') + ->willReturn($this->integrationMock); + $this->integrationMock->expects($this->once()) + ->method('getConsumerId') + ->willReturn(100500); + $this->integrationMock->expects($this->once()) + ->method('getId') + ->willReturn($integrationId); + if (!$integrationId) { + $this->integrationServiceMock + ->expects($this->once()) + ->method('create') + ->with($this->getIntegrationUserData(Integration::STATUS_INACTIVE)) + ->willReturn($this->integrationMock); + } + $this->oauthServiceMock->expects($this->at(0)) + ->method('getAccessToken') + ->with(100500) + ->willReturn(false); + $this->oauthServiceMock->expects($this->at(2)) + ->method('getAccessToken') + ->with(100500) + ->willReturn('IntegrationToken'); + $this->oauthServiceMock->expects($this->once()) + ->method('createAccessToken') + ->with(100500, true) + ->willReturn(true); + $this->assertEquals('IntegrationToken', $this->integrationManager->generateToken()); + } + + /** + * @dataProvider integrationIdDataProvider + * + * @param int|null $integrationId If null integration is absent. + * @return void + */ + public function testGetTokenExistingIntegration($integrationId) + { + $this->configMock->expects($this->atLeastOnce()) + ->method('getConfigDataValue') + ->with('analytics/integration_name', null, null) + ->willReturn('ma-integration-user'); + $this->integrationServiceMock->expects($this->once()) + ->method('findByName') + ->with('ma-integration-user') + ->willReturn($this->integrationMock); + $this->integrationMock->expects($this->once()) + ->method('getConsumerId') + ->willReturn(100500); + $this->integrationMock->expects($this->once()) + ->method('getId') + ->willReturn($integrationId); + if (!$integrationId) { + $this->integrationServiceMock + ->expects($this->once()) + ->method('create') + ->with($this->getIntegrationUserData(Integration::STATUS_INACTIVE)) + ->willReturn($this->integrationMock); + } + $this->oauthServiceMock->expects($this->once()) + ->method('getAccessToken') + ->with(100500) + ->willReturn('IntegrationToken'); + $this->oauthServiceMock->expects($this->never()) + ->method('createAccessToken'); + $this->assertEquals('IntegrationToken', $this->integrationManager->generateToken()); + } + + /** + * @return array + */ + public function integrationIdDataProvider() + { + return [ + [1], + [null], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php new file mode 100644 index 0000000000000..c7aa2219d1eee --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php @@ -0,0 +1,166 @@ +linkInterfaceFactoryMock = $this->getMockBuilder(LinkInterfaceFactory::class) + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + $this->fileInfoManagerMock = $this->getMockBuilder(FileInfoManager::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeManagerInterfaceMock = $this->getMockBuilder(StoreManagerInterface::class) + ->getMockForAbstractClass(); + $this->linkInterfaceMock = $this->getMockBuilder(LinkInterface::class) + ->getMockForAbstractClass(); + $this->fileInfoMock = $this->getMockBuilder(FileInfo::class) + ->disableOriginalConstructor() + ->getMock(); + $this->storeMock = $this->getMockBuilder(Store::class) + ->disableOriginalConstructor() + ->getMock(); + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->linkProvider = $this->objectManagerHelper->getObject( + LinkProvider::class, + [ + 'linkFactory' => $this->linkInterfaceFactoryMock, + 'fileInfoManager' => $this->fileInfoManagerMock, + 'storeManager' => $this->storeManagerInterfaceMock + ] + ); + } + + public function testGet() + { + $baseUrl = 'http://magento.local/pub/media/'; + $fileInfoPath = 'analytics/data.tgz'; + $fileInitializationVector = 'er312esq23eqq'; + $this->fileInfoManagerMock->expects($this->once()) + ->method('load') + ->willReturn($this->fileInfoMock); + $this->linkInterfaceFactoryMock->expects($this->once()) + ->method('create') + ->with( + [ + 'initializationVector' => base64_encode($fileInitializationVector), + 'url' => $baseUrl . $fileInfoPath + ] + ) + ->willReturn($this->linkInterfaceMock); + $this->storeManagerInterfaceMock->expects($this->once()) + ->method('getStore')->willReturn($this->storeMock); + $this->storeMock->expects($this->once()) + ->method('getBaseUrl') + ->with( + UrlInterface::URL_TYPE_MEDIA + ) + ->willReturn($baseUrl); + $this->fileInfoMock->expects($this->atLeastOnce()) + ->method('getPath') + ->willReturn($fileInfoPath); + $this->fileInfoMock->expects($this->atLeastOnce()) + ->method('getInitializationVector') + ->willReturn($fileInitializationVector); + $this->assertEquals($this->linkInterfaceMock, $this->linkProvider->get()); + } + + /** + * @param string|null $fileInfoPath + * @param string|null $fileInitializationVector + * + * @dataProvider fileNotReadyDataProvider + * @expectedException \Magento\Framework\Exception\NoSuchEntityException + * @expectedExceptionMessage File is not ready yet. + */ + public function testFileNotReady($fileInfoPath, $fileInitializationVector) + { + $this->fileInfoManagerMock->expects($this->once()) + ->method('load') + ->willReturn($this->fileInfoMock); + $this->fileInfoMock->expects($this->once()) + ->method('getPath') + ->willReturn($fileInfoPath); + $this->fileInfoMock->expects($this->any()) + ->method('getInitializationVector') + ->willReturn($fileInitializationVector); + $this->linkProvider->get(); + } + + /** + * @return array + */ + public function fileNotReadyDataProvider() + { + return [ + [null, 'initVector'], + ['path', null], + ['', 'initVector'], + ['path', ''], + ['', ''], + [null, null] + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php new file mode 100644 index 0000000000000..a89e06562383b --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Plugin/BaseUrlConfigPluginTest.php @@ -0,0 +1,147 @@ +subscriptionUpdateHandlerMock = $this->getMockBuilder(SubscriptionUpdateHandler::class) + ->disableOriginalConstructor() + ->getMock(); + $this->configValueMock = $this->getMockBuilder(Value::class) + ->disableOriginalConstructor() + ->setMethods(['isValueChanged', 'getPath', 'getScope', 'getOldValue']) + ->getMock(); + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->plugin = $this->objectManagerHelper->getObject( + BaseUrlConfigPlugin::class, + [ + 'subscriptionUpdateHandler' => $this->subscriptionUpdateHandlerMock, + ] + ); + } + + /** + * @param array $configValueData + * @return void + * @dataProvider afterSavePluginIsNotApplicableDataProvider + */ + public function testAfterSavePluginIsNotApplicable( + array $configValueData + ) { + $this->configValueMock + ->method('isValueChanged') + ->willReturn($configValueData['isValueChanged']); + $this->configValueMock + ->method('getPath') + ->willReturn($configValueData['path']); + $this->configValueMock + ->method('getScope') + ->willReturn($configValueData['scope']); + $this->subscriptionUpdateHandlerMock + ->expects($this->never()) + ->method('processUrlUpdate'); + + $this->assertEquals( + $this->configValueMock, + $this->plugin->afterAfterSave($this->configValueMock, $this->configValueMock) + ); + } + + /** + * @return array + */ + public function afterSavePluginIsNotApplicableDataProvider() + { + return [ + 'Value has not been changed' => [ + 'Config Value Data' => [ + 'isValueChanged' => false, + 'path' => Store::XML_PATH_SECURE_BASE_URL, + 'scope' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT + ], + ], + 'Unsecure URL has been changed' => [ + 'Config Value Data' => [ + 'isValueChanged' => true, + 'path' => Store::XML_PATH_UNSECURE_BASE_URL, + 'scope' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT + ], + ], + 'Secure URL has been changed not in the Default scope' => [ + 'Config Value Data' => [ + 'isValueChanged' => true, + 'path' => Store::XML_PATH_SECURE_BASE_URL, + 'scope' => ScopeInterface::SCOPE_STORES + ], + ], + ]; + } + + /** + * @return void + */ + public function testAfterSavePluginIsApplicable() + { + $this->configValueMock + ->method('isValueChanged') + ->willReturn(true); + $this->configValueMock + ->method('getPath') + ->willReturn(Store::XML_PATH_SECURE_BASE_URL); + $this->configValueMock + ->method('getScope') + ->willReturn(ScopeConfigInterface::SCOPE_TYPE_DEFAULT); + $this->configValueMock + ->method('getOldValue') + ->willReturn('http://store.com'); + $this->subscriptionUpdateHandlerMock + ->expects($this->once()) + ->method('processUrlUpdate') + ->with('http://store.com'); + + $this->assertEquals( + $this->configValueMock, + $this->plugin->afterAfterSave($this->configValueMock, $this->configValueMock) + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php new file mode 100644 index 0000000000000..0607a977e5b68 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ReportUrlProviderTest.php @@ -0,0 +1,149 @@ +configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->otpRequestMock = $this->getMockBuilder(OTPRequest::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->reportUrlProvider = $this->objectManagerHelper->getObject( + ReportUrlProvider::class, + [ + 'config' => $this->configMock, + 'analyticsToken' => $this->analyticsTokenMock, + 'otpRequest' => $this->otpRequestMock, + 'flagManager' => $this->flagManagerMock, + 'urlReportConfigPath' => $this->urlReportConfigPath, + ] + ); + } + + /** + * @param bool $isTokenExist + * @param string|null $otp If null OTP was not received. + * + * @dataProvider getUrlDataProvider + */ + public function testGetUrl($isTokenExist, $otp) + { + $reportUrl = 'https://example.com/report'; + $url = ''; + + $this->configMock + ->expects($this->once()) + ->method('getValue') + ->with($this->urlReportConfigPath) + ->willReturn($reportUrl); + $this->analyticsTokenMock + ->expects($this->once()) + ->method('isTokenExist') + ->with() + ->willReturn($isTokenExist); + $this->otpRequestMock + ->expects($isTokenExist ? $this->once() : $this->never()) + ->method('call') + ->with() + ->willReturn($otp); + if ($isTokenExist && $otp) { + $url = $reportUrl . '?' . http_build_query(['otp' => $otp], '', '&'); + } + $this->assertSame($url ?: $reportUrl, $this->reportUrlProvider->getUrl()); + } + + /** + * @return array + */ + public function getUrlDataProvider() + { + return [ + 'TokenDoesNotExist' => [false, null], + 'TokenExistAndOtpEmpty' => [true, null], + 'TokenExistAndOtpValid' => [true, '249e6b658877bde2a77bc4ab'], + ]; + } + + /** + * @return void + */ + public function testGetUrlWhenSubscriptionUpdateRunning() + { + $this->flagManagerMock + ->expects($this->once()) + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE) + ->willReturn('http://store.com'); + $this->expectException(SubscriptionUpdateException::class); + $this->reportUrlProvider->getUrl(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php new file mode 100644 index 0000000000000..d9b030b84d639 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ReportWriterTest.php @@ -0,0 +1,213 @@ +configInterfaceMock = $this->getMockBuilder(ConfigInterface::class)->getMockForAbstractClass(); + $this->reportValidatorMock = $this->getMockBuilder(ReportValidator::class) + ->disableOriginalConstructor()->getMock(); + $this->providerFactoryMock = $this->getMockBuilder(ProviderFactory::class) + ->disableOriginalConstructor()->getMock(); + $this->reportProviderMock = $this->getMockBuilder(ReportProvider::class) + ->disableOriginalConstructor()->getMock(); + $this->directoryMock = $this->getMockBuilder(WriteInterface::class)->getMockForAbstractClass(); + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->reportWriter = $this->objectManagerHelper->getObject( + ReportWriter::class, + [ + 'config' => $this->configInterfaceMock, + 'reportValidator' => $this->reportValidatorMock, + 'providerFactory' => $this->providerFactoryMock + ] + ); + } + + /** + * @param array $configData + * @return void + * + * @dataProvider configDataProvider + */ + public function testWrite(array $configData) + { + $errors = []; + $fileData = [ + ['number' => 1, 'type' => 'Shoes Usual'] + ]; + $this->configInterfaceMock + ->expects($this->once()) + ->method('get') + ->with() + ->willReturn([$configData]); + $this->providerFactoryMock + ->expects($this->once()) + ->method('create') + ->with($this->providerClass) + ->willReturn($this->reportProviderMock); + $parameterName = isset(reset($configData)[0]['parameters']['name']) + ? reset($configData)[0]['parameters']['name'] + : ''; + $this->reportProviderMock->expects($this->once()) + ->method('getReport') + ->with($parameterName ?: null) + ->willReturn($fileData); + $errorStreamMock = $this->getMockBuilder( + \Magento\Framework\Filesystem\File\WriteInterface::class + )->getMockForAbstractClass(); + $errorStreamMock + ->expects($this->once()) + ->method('lock') + ->with(); + $errorStreamMock + ->expects($this->exactly(2)) + ->method('writeCsv') + ->withConsecutive( + [array_keys($fileData[0])], + [$fileData[0]] + ); + $errorStreamMock->expects($this->once())->method('unlock'); + $errorStreamMock->expects($this->once())->method('close'); + if ($parameterName) { + $this->reportValidatorMock + ->expects($this->once()) + ->method('validate') + ->with($parameterName) + ->willReturn($errors); + } + $this->directoryMock + ->expects($this->once()) + ->method('openFile') + ->with( + $this->stringContains('/var/tmp' . $parameterName ?: $this->reportName), + 'w+' + )->willReturn($errorStreamMock); + $this->assertTrue($this->reportWriter->write($this->directoryMock, '/var/tmp')); + } + + /** + * @param array $configData + * @return void + * + * @dataProvider configDataProvider + */ + public function testWriteErrorFile($configData) + { + $errors = ['orders', 'SQL Error: test']; + $this->configInterfaceMock->expects($this->once())->method('get')->willReturn([$configData]); + $errorStreamMock = $this->getMockBuilder( + \Magento\Framework\Filesystem\File\WriteInterface::class + )->getMockForAbstractClass(); + $errorStreamMock->expects($this->once())->method('lock'); + $errorStreamMock->expects($this->once())->method('writeCsv')->with($errors); + $errorStreamMock->expects($this->once())->method('unlock'); + $errorStreamMock->expects($this->once())->method('close'); + $this->reportValidatorMock->expects($this->once())->method('validate')->willReturn($errors); + $this->directoryMock->expects($this->once())->method('openFile')->with('/var/tmp' . 'errors.csv', 'w+') + ->willReturn($errorStreamMock); + $this->assertTrue($this->reportWriter->write($this->directoryMock, '/var/tmp')); + } + + /** + * @return void + */ + public function testWriteEmptyReports() + { + $this->configInterfaceMock->expects($this->once())->method('get')->willReturn([]); + $this->reportValidatorMock->expects($this->never())->method('validate'); + $this->directoryMock->expects($this->never())->method('openFile'); + $this->assertTrue($this->reportWriter->write($this->directoryMock, '/var/tmp')); + } + + /** + * @return array + */ + public function configDataProvider() + { + return [ + 'reportProvider' => [ + [ + 'providers' => [ + [ + 'name' => $this->providerName, + 'class' => $this->providerClass, + 'parameters' => [ + 'name' => $this->reportName + ], + ] + ] + ] + ], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php b/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php new file mode 100644 index 0000000000000..f314d77f32b41 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/ReportXml/ModuleIteratorTest.php @@ -0,0 +1,50 @@ +moduleManagerMock = $this->getMockBuilder(ModuleManager::class) + ->disableOriginalConstructor() + ->getMock(); + $objectManagerHelper = new ObjectManagerHelper($this); + $this->moduleIterator = $objectManagerHelper->getObject( + ModuleIterator::class, + [ + 'moduleManager' => $this->moduleManagerMock, + 'iterator' => new \ArrayIterator([0 => ['module_name' => 'Coco_Module']]) + ] + ); + } + + public function testCurrent() + { + $this->moduleManagerMock->expects($this->once()) + ->method('isEnabled') + ->with('Coco_Module') + ->willReturn(true); + foreach ($this->moduleIterator as $item) { + $this->assertEquals(['module_name' => 'Coco_Module', 'status' => 'Enabled'], $item); + } + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php new file mode 100644 index 0000000000000..cc46d175543ad --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/StoreConfigurationProviderTest.php @@ -0,0 +1,123 @@ +scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->websiteMock = $this->getMockBuilder(WebsiteInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->storeMock = $this->getMockBuilder(StoreInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configPaths = [ + 'web/unsecure/base_url', + 'currency/options/base', + 'general/locale/timezone' + ]; + + $this->storeConfigurationProvider = new StoreConfigurationProvider( + $this->scopeConfigMock, + $this->storeManagerMock, + $this->configPaths + ); + } + + public function testGetReport() + { + $map = [ + ['web/unsecure/base_url', 'default', 0, '127.0.0.1'], + ['currency/options/base', 'default', 0, 'USD'], + ['general/locale/timezone', 'default', 0, 'America/Dawson'], + ['web/unsecure/base_url', 'websites', 1, '127.0.0.2'], + ['currency/options/base', 'websites', 1, 'USD'], + ['general/locale/timezone', 'websites', 1, 'America/Belem'], + ['web/unsecure/base_url', 'stores', 2, '127.0.0.3'], + ['currency/options/base', 'stores', 2, 'USD'], + ['general/locale/timezone', 'stores', 2, 'America/Phoenix'], + ]; + + $this->scopeConfigMock + ->method('getValue') + ->will($this->returnValueMap($map)); + + $this->storeManagerMock->expects($this->once()) + ->method('getWebsites') + ->willReturn([$this->websiteMock]); + + $this->storeManagerMock->expects($this->once()) + ->method('getStores') + ->willReturn([$this->storeMock]); + + $this->websiteMock->expects($this->once()) + ->method('getId') + ->willReturn(1); + + $this->storeMock->expects($this->once()) + ->method('getId') + ->willReturn(2); + $result = iterator_to_array($this->storeConfigurationProvider->getReport()); + $resultValues = []; + foreach ($result as $item) { + $resultValues[] = array_values($item); + } + array_multisort($resultValues); + array_multisort($map); + $this->assertEquals($resultValues, $map); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php new file mode 100644 index 0000000000000..d6b041ce03178 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php @@ -0,0 +1,196 @@ +scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMockForAbstractClass(); + + $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->flagManagerMock = $this->getMockBuilder(FlagManager::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->statusProvider = $this->objectManagerHelper->getObject( + SubscriptionStatusProvider::class, + [ + 'scopeConfig' => $this->scopeConfigMock, + 'analyticsToken' => $this->analyticsTokenMock, + 'flagManager' => $this->flagManagerMock, + ] + ); + } + + /** + * @param array $flagManagerData + * @dataProvider getStatusShouldBeFailedDataProvider + */ + public function testGetStatusShouldBeFailed(array $flagManagerData) + { + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(false); + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') + ->with('analytics/subscription/enabled') + ->willReturn(true); + + $this->expectFlagManagerReturn($flagManagerData); + $this->assertEquals(SubscriptionStatusProvider::FAILED, $this->statusProvider->getStatus()); + } + + /** + * @return array + */ + public function getStatusShouldBeFailedDataProvider() + { + return [ + 'Subscription update doesn\'t active' => [ + 'Flag Manager data mapping' => [ + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, null], + [SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, null] + ], + ], + 'Subscription update is active' => [ + 'Flag Manager data mapping' => [ + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, 'http://store.com'], + [SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, null] + ], + ], + ]; + } + + /** + * @param array $flagManagerData + * @param bool $isTokenExist + * @dataProvider getStatusShouldBePendingDataProvider + */ + public function testGetStatusShouldBePending(array $flagManagerData, bool $isTokenExist) + { + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn($isTokenExist); + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') + ->with('analytics/subscription/enabled') + ->willReturn(true); + + $this->expectFlagManagerReturn($flagManagerData); + $this->assertEquals(SubscriptionStatusProvider::PENDING, $this->statusProvider->getStatus()); + } + + /** + * @return array + */ + public function getStatusShouldBePendingDataProvider() + { + return [ + 'Subscription update doesn\'t active and the token does not exist' => [ + 'Flag Manager data mapping' => [ + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, null], + [SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, 45] + ], + 'isTokenExist' => false, + ], + 'Subscription update is active and the token does not exist' => [ + 'Flag Manager data mapping' => [ + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, 'http://store.com'], + [SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, 45] + ], + 'isTokenExist' => false, + ], + 'Subscription update is active and token exist' => [ + 'Flag Manager data mapping' => [ + [SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE, 'http://store.com'], + [SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE, null] + ], + 'isTokenExist' => true, + ], + ]; + } + + public function testGetStatusShouldBeEnabled() + { + $this->flagManagerMock + ->method('getFlagData') + ->with(SubscriptionUpdateHandler::PREVIOUS_BASE_URL_FLAG_CODE) + ->willReturn(null); + $this->analyticsTokenMock->expects($this->once()) + ->method('isTokenExist') + ->willReturn(true); + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') + ->with('analytics/subscription/enabled') + ->willReturn(true); + $this->assertEquals(SubscriptionStatusProvider::ENABLED, $this->statusProvider->getStatus()); + } + + public function testGetStatusShouldBeDisabled() + { + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') + ->with('analytics/subscription/enabled') + ->willReturn(false); + $this->assertEquals(SubscriptionStatusProvider::DISABLED, $this->statusProvider->getStatus()); + } + + /** + * @param array $mapping + */ + private function expectFlagManagerReturn(array $mapping) + { + $this->flagManagerMock + ->method('getFlagData') + ->willReturnMap($mapping); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php b/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php new file mode 100644 index 0000000000000..ad1d87488d751 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/System/Message/NotificationAboutFailedSubscriptionTest.php @@ -0,0 +1,106 @@ +subscriptionStatusMock = $this->getMockBuilder(SubscriptionStatusProvider::class) + ->disableOriginalConstructor() + ->getMock(); + $this->urlBuilderMock = $this->getMockBuilder(UrlInterface::class) + ->getMockForAbstractClass(); + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->notification = $this->objectManagerHelper->getObject( + NotificationAboutFailedSubscription::class, + [ + 'subscriptionStatusProvider' => $this->subscriptionStatusMock, + 'urlBuilder' => $this->urlBuilderMock + ] + ); + } + + public function testIsDisplayedWhenMessageShouldBeDisplayed() + { + $this->subscriptionStatusMock->expects($this->once()) + ->method('getStatus') + ->willReturn( + SubscriptionStatusProvider::FAILED + ); + $this->assertTrue($this->notification->isDisplayed()); + } + + /** + * @dataProvider notDisplayedNotificationStatuses + * + * @param $status + */ + public function testIsDisplayedWhenMessageShouldNotBeDisplayed($status) + { + $this->subscriptionStatusMock->expects($this->once()) + ->method('getStatus') + ->willReturn($status); + $this->assertFalse($this->notification->isDisplayed()); + } + + public function testGetTextShouldBuildMessage() + { + $retryUrl = 'http://magento.dev/retryUrl'; + $this->urlBuilderMock->expects($this->once()) + ->method('getUrl') + ->with('analytics/subscription/retry') + ->willReturn($retryUrl); + $messageDetails = 'Failed to synchronize data to the Magento Business Intelligence service. '; + $messageDetails .= sprintf('Retry Synchronization', $retryUrl); + $this->assertEquals($messageDetails, $this->notification->getText()); + } + + /** + * Provide statuses according to which message should not be displayed. + * + * @return array + */ + public function notDisplayedNotificationStatuses() + { + return [ + [SubscriptionStatusProvider::PENDING], + [SubscriptionStatusProvider::DISABLED], + [SubscriptionStatusProvider::ENABLED], + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php new file mode 100644 index 0000000000000..3f1ed9a5cf4c0 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/Converter/XmlTest.php @@ -0,0 +1,121 @@ +objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\ReportXml\Config\Converter\Xml::class + ); + } + + /** + * @return void + */ + public function testConvertNoElements() + { + $this->assertEmpty( + $this->subject->convert(new \DOMDocument()) + ); + } + + /** + * @return void + */ + public function testConvert() + { + $dom = new \DOMDocument(); + + $expectedArray = [ + 'config' => [ + [ + 'noNamespaceSchemaLocation' => 'urn:magento:module:Magento_Analytics:etc/reports.xsd', + 'report' => [ + [ + 'name' => 'test_report_1', + 'connection' => 'sales', + 'source' => [ + [ + 'name' => 'sales_order', + 'alias' => 'orders', + 'attribute' => [ + [ + 'name' => 'entity_id', + 'alias' => 'identifier', + ] + ], + 'filter' => [ + [ + 'glue' => 'and', + 'condition' => [ + [ + 'attribute' => 'entity_id', + 'operator' => 'gt', + '_value' => '10' + ] + ] + ] + ] + ] + ] + ], + [ + 'name' => 'test_report_2', + 'connection' => 'default', + 'source' => [ + [ + 'name' => 'customer_entity', + 'alias' => 'customers', + 'attribute' => [ + [ + 'name' => 'email' + ] + ], + 'filter' => [ + [ + 'glue' => 'and', + 'condition' => [ + [ + 'attribute' => 'dob', + 'operator' => 'null' + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ]; + + $dom->loadXML(file_get_contents(__DIR__ . '/../_files/valid_reports.xml')); + + $this->assertEquals($expectedArray, $this->subject->convert($dom)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php new file mode 100644 index 0000000000000..85343b6b301d6 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/MapperTest.php @@ -0,0 +1,47 @@ +mapper = new Mapper(); + } + + public function testExecute() + { + $configData['config'][0]['report'] = [ + [ + 'source' => ['product'], + 'name' => 'Product', + ] + ]; + $expectedResult = [ + 'Product' => [ + 'source' => 'product', + 'name' => 'Product', + ] + ]; + $this->assertEquals($this->mapper->execute($configData), $expectedResult); + } + + public function testExecuteWithoutReports() + { + $configData = []; + $this->assertEquals($this->mapper->execute($configData), []); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/_files/valid_reports.xml b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/_files/valid_reports.xml new file mode 100644 index 0000000000000..e04ee96163797 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/Config/_files/valid_reports.xml @@ -0,0 +1,25 @@ + + + + + + + + 10 + + + + + + + + + + + + diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php new file mode 100644 index 0000000000000..cbc9aa129d874 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConfigTest.php @@ -0,0 +1,64 @@ +dataMock = $this->getMockBuilder(DataInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->config = $this->objectManagerHelper->getObject( + Config::class, + [ + 'data' => $this->dataMock, + ] + ); + } + + public function testGet() + { + $queryName = 'query string'; + $queryResult = [ 'query' => 1 ]; + + $this->dataMock + ->expects($this->once()) + ->method('get') + ->with($queryName) + ->willReturn($queryResult); + + $this->assertSame($queryResult, $this->config->get($queryName)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php new file mode 100644 index 0000000000000..1e4ae9142c13d --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/ConnectionFactoryTest.php @@ -0,0 +1,106 @@ +resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionMock = $this->getMockBuilder(MysqlPdoAdapter::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionNewMock = $this->getMockBuilder(MysqlPdoAdapter::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->connectionFactory = $this->objectManagerHelper->getObject( + ConnectionFactory::class, + [ + 'resourceConnection' => $this->resourceConnectionMock, + 'objectManager' => $this->objectManagerMock, + ] + ); + } + + public function testGetConnection() + { + $connectionName = 'read'; + + $this->resourceConnectionMock + ->expects($this->once()) + ->method('getConnection') + ->with($connectionName) + ->willReturn($this->connectionMock); + + $this->connectionMock + ->expects($this->once()) + ->method('getConfig') + ->with() + ->willReturn(['persistent' => 1]); + + $this->objectManagerMock + ->expects($this->once()) + ->method('create') + ->with(get_class($this->connectionMock), ['config' => ['use_buffered_query' => false]]) + ->willReturn($this->connectionNewMock); + + $this->assertSame($this->connectionNewMock, $this->connectionFactory->getConnection($connectionName)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php new file mode 100644 index 0000000000000..3b01105a8873b --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FilterAssemblerTest.php @@ -0,0 +1,143 @@ +nameResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\NameResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectBuilderMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\SelectBuilder::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->selectBuilderMock->expects($this->any()) + ->method('getFilters') + ->willReturn([]); + + $this->conditionResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\ConditionResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\ReportXml\DB\Assembler\FilterAssembler::class, + [ + 'conditionResolver' => $this->conditionResolverMock, + 'nameResolver' => $this->nameResolverMock + ] + ); + } + + /** + * @return void + */ + public function testAssembleEmpty() + { + $queryConfigMock = [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales' + ] + ]; + + $this->selectBuilderMock->expects($this->never()) + ->method('setFilters'); + + $this->assertEquals( + $this->selectBuilderMock, + $this->subject->assemble($this->selectBuilderMock, $queryConfigMock) + ); + } + + /** + * @return void + */ + public function testAssembleNotEmpty() + { + $queryConfigMock = [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales', + 'filter' => [ + [ + 'glue' => 'and', + 'condition' => [ + [ + 'attribute' => 'entity_id', + 'operator' => 'null' + ] + ] + ] + ] + ] + ]; + + $this->nameResolverMock->expects($this->any()) + ->method('getAlias') + ->with($queryConfigMock['source']) + ->willReturn($queryConfigMock['source']['alias']); + + $this->conditionResolverMock->expects($this->once()) + ->method('getFilter') + ->with( + $this->selectBuilderMock, + $queryConfigMock['source']['filter'], + $queryConfigMock['source']['alias'] + ) + ->willReturn('(sales.entity_id IS NULL)'); + + $this->selectBuilderMock->expects($this->once()) + ->method('setFilters') + ->with(['(sales.entity_id IS NULL)']); + + $this->assertEquals( + $this->selectBuilderMock, + $this->subject->assemble($this->selectBuilderMock, $queryConfigMock) + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php new file mode 100644 index 0000000000000..575db94a7b7e1 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php @@ -0,0 +1,167 @@ +nameResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\NameResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectBuilderMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\SelectBuilder::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->selectBuilderMock->expects($this->any()) + ->method('getColumns') + ->willReturn([]); + + $this->columnsResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\ColumnsResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\ReportXml\DB\Assembler\FromAssembler::class, + [ + 'nameResolver' => $this->nameResolverMock, + 'columnsResolver' => $this->columnsResolverMock, + 'resourceConnection' => $this->resourceConnection, + ] + ); + } + + /** + * @dataProvider assembleDataProvider + * @param array $queryConfig + * @param string $tableName + * @return void + */ + public function testAssemble(array $queryConfig, $tableName) + { + $this->nameResolverMock->expects($this->any()) + ->method('getAlias') + ->with($queryConfig['source']) + ->willReturn($queryConfig['source']['alias']); + + $this->nameResolverMock->expects($this->once()) + ->method('getName') + ->with($queryConfig['source']) + ->willReturn($queryConfig['source']['name']); + + $this->resourceConnection + ->expects($this->once()) + ->method('getTableName') + ->with($queryConfig['source']['name']) + ->willReturn($tableName); + + $this->selectBuilderMock->expects($this->once()) + ->method('setFrom') + ->with([$queryConfig['source']['alias'] => $tableName]); + + $this->columnsResolverMock->expects($this->once()) + ->method('getColumns') + ->with($this->selectBuilderMock, $queryConfig['source']) + ->willReturn(['entity_id' => 'sales.entity_id']); + + $this->selectBuilderMock->expects($this->once()) + ->method('setColumns') + ->with(['entity_id' => 'sales.entity_id']); + + $this->assertEquals( + $this->selectBuilderMock, + $this->subject->assemble($this->selectBuilderMock, $queryConfig) + ); + } + + /** + * @return array + */ + public function assembleDataProvider() + { + return [ + 'Tables without prefixes' => [ + [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales', + 'attribute' => [ + [ + 'name' => 'entity_id' + ] + ], + ], + ], + 'sales_order', + ], + 'Tables with prefixes' => [ + [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales', + 'attribute' => [ + [ + 'name' => 'entity_id' + ] + ], + ], + ], + 'pref_sales_order', + ] + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php new file mode 100644 index 0000000000000..aaafd731552a0 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php @@ -0,0 +1,279 @@ +nameResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\NameResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectBuilderMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\SelectBuilder::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->selectBuilderMock->expects($this->any()) + ->method('getFilters') + ->willReturn([]); + $this->selectBuilderMock->expects($this->any()) + ->method('getColumns') + ->willReturn([]); + $this->selectBuilderMock->expects($this->any()) + ->method('getJoins') + ->willReturn([]); + + $this->columnsResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\ColumnsResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->conditionResolverMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\ConditionResolver::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\ReportXml\DB\Assembler\JoinAssembler::class, + [ + 'conditionResolver' => $this->conditionResolverMock, + 'nameResolver' => $this->nameResolverMock, + 'columnsResolver' => $this->columnsResolverMock, + 'resourceConnection' => $this->resourceConnection, + ] + ); + } + + /** + * @return void + */ + public function testAssembleEmpty() + { + $queryConfigMock = [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales' + ] + ]; + + $this->selectBuilderMock->expects($this->never()) + ->method('setColumns'); + $this->selectBuilderMock->expects($this->never()) + ->method('setFilters'); + $this->selectBuilderMock->expects($this->never()) + ->method('setJoins'); + + $this->assertEquals( + $this->selectBuilderMock, + $this->subject->assemble($this->selectBuilderMock, $queryConfigMock) + ); + } + + /** + * @param array $queryConfigMock + * @param array $joinsMock + * @param array $tablesMapping + * @return void + * @dataProvider assembleNotEmptyDataProvider + */ + public function testAssembleNotEmpty(array $queryConfigMock, array $joinsMock, array $tablesMapping) + { + $filtersMock = []; + + $this->nameResolverMock->expects($this->at(0)) + ->method('getAlias') + ->with($queryConfigMock['source']) + ->willReturn($queryConfigMock['source']['alias']); + $this->nameResolverMock->expects($this->at(1)) + ->method('getAlias') + ->with($queryConfigMock['source']['link-source'][0]) + ->willReturn($queryConfigMock['source']['link-source'][0]['alias']); + $this->nameResolverMock->expects($this->once()) + ->method('getName') + ->with($queryConfigMock['source']['link-source'][0]) + ->willReturn($queryConfigMock['source']['link-source'][0]['name']); + + $this->resourceConnection + ->expects($this->any()) + ->method('getTableName') + ->willReturnOnConsecutiveCalls(...array_values($tablesMapping)); + + $this->conditionResolverMock->expects($this->at(0)) + ->method('getFilter') + ->with( + $this->selectBuilderMock, + $queryConfigMock['source']['link-source'][0]['using'], + $queryConfigMock['source']['link-source'][0]['alias'], + $queryConfigMock['source']['alias'] + ) + ->willReturn('(billing.parent_id = `sales`.`entity_id`)'); + + if (isset($queryConfigMock['source']['link-source'][0]['filter'])) { + $filtersMock = ['(sales.entity_id IS NULL)']; + + $this->conditionResolverMock->expects($this->at(1)) + ->method('getFilter') + ->with( + $this->selectBuilderMock, + $queryConfigMock['source']['link-source'][0]['filter'], + $queryConfigMock['source']['link-source'][0]['alias'], + $queryConfigMock['source']['alias'] + ) + ->willReturn($filtersMock[0]); + + $this->columnsResolverMock->expects($this->once()) + ->method('getColumns') + ->with($this->selectBuilderMock, $queryConfigMock['source']['link-source'][0]) + ->willReturn( + [ + 'entity_id' => 'sales.entity_id', + 'billing_address_id' => 'billing.entity_id' + ] + ); + + $this->selectBuilderMock->expects($this->once()) + ->method('setColumns') + ->with( + [ + 'entity_id' => 'sales.entity_id', + 'billing_address_id' => 'billing.entity_id' + ] + ); + } + + $this->selectBuilderMock->expects($this->once()) + ->method('setFilters') + ->with($filtersMock); + $this->selectBuilderMock->expects($this->once()) + ->method('setJoins') + ->with($joinsMock); + + $this->assertEquals( + $this->selectBuilderMock, + $this->subject->assemble($this->selectBuilderMock, $queryConfigMock) + ); + } + + /** + * @return array + */ + public function assembleNotEmptyDataProvider() + { + return [ + [ + [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales', + 'link-source' => [ + [ + 'name' => 'sales_order_address', + 'alias' => 'billing', + 'link-type' => 'left', + 'attribute' => [ + [ + 'alias' => 'billing_address_id', + 'name' => 'entity_id' + ] + ], + 'using' => [ + [ + 'glue' => 'and', + 'condition' => [ + [ + 'attribute' => 'parent_id', + 'operator' => 'eq', + 'type' => 'identifier', + '_value' => 'entity_id' + ] + ] + ] + ], + 'filter' => [ + [ + 'glue' => 'and', + 'condition' => [ + [ + 'attribute' => 'entity_id', + 'operator' => 'null' + ] + ] + ] + ] + ] + ] + ] + ], + [ + 'billing' => [ + 'link-type' => 'left', + 'table' => [ + 'billing' => 'pref_sales_order_address' + ], + 'condition' => '(billing.parent_id = `sales`.`entity_id`)' + ] + ], + ['sales_order_address' => 'pref_sales_order_address'] + ] + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php new file mode 100644 index 0000000000000..bdbe3d1d22c22 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ColumnsResolverTest.php @@ -0,0 +1,150 @@ +selectBuilderMock = $this->getMockBuilder(SelectBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $objectManager = new ObjectManagerHelper($this); + $this->columnsResolver = $objectManager->getObject( + ColumnsResolver::class, + [ + 'nameResolver' => new NameResolver(), + 'resourceConnection' => $this->resourceConnectionMock + ] + ); + } + + public function testGetColumnsWithoutAttributes() + { + $this->assertEquals($this->columnsResolver->getColumns($this->selectBuilderMock, []), []); + } + + /** + * @dataProvider getColumnsDataProvider + */ + public function testGetColumnsWithFunction($expectedColumns, $expectedGroup, $entityConfig) + { + $this->resourceConnectionMock->expects($this->any()) + ->method('getConnection') + ->willReturn($this->connectionMock); + $this->connectionMock->expects($this->any()) + ->method('quoteIdentifier') + ->with('cpe.name') + ->willReturn('`cpe`.`name`'); + $this->selectBuilderMock->expects($this->once()) + ->method('getColumns') + ->willReturn([]); + $this->selectBuilderMock->expects($this->once()) + ->method('getGroup') + ->willReturn([]); + $this->selectBuilderMock->expects($this->once()) + ->method('setGroup') + ->with($expectedGroup); + $this->assertEquals( + $expectedColumns, + $this->columnsResolver->getColumns( + $this->selectBuilderMock, + $entityConfig + ) + ); + } + + /** + * @return array + */ + public function getColumnsDataProvider() + { + return [ + 'COUNT( DISTINCT `cpe`.`name`) AS name' => [ + 'expectedColumns' => [ + 'name' => new ColumnValueExpression('COUNT( DISTINCT `cpe`.`name`)') + ], + 'expectedGroup' => [ + 'name' => new ColumnValueExpression('COUNT( DISTINCT `cpe`.`name`)') + ], + 'entityConfig' => + [ + 'name' => 'catalog_product_entity', + 'alias' => 'cpe', + 'attribute' => [ + [ + 'name' => 'name', + 'function' => 'COUNT', + 'distinct' => true, + 'group' => true + ] + ], + ], + ], + 'AVG(`cpe`.`name`) AS avg_name' => [ + 'expectedColumns' => [ + 'avg_name' => new ColumnValueExpression('AVG(`cpe`.`name`)') + ], + 'expectedGroup' => [], + 'entityConfig' => + [ + 'name' => 'catalog_product_entity', + 'alias' => 'cpe', + 'attribute' => [ + [ + 'name' => 'name', + 'alias' => 'avg_name', + 'function' => 'AVG', + ] + ], + ], + ] + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php new file mode 100644 index 0000000000000..c8182d068fba5 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ConditionResolverTest.php @@ -0,0 +1,108 @@ +resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectBuilderMock = $this->getMockBuilder(SelectBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->conditionResolver = new ConditionResolver($this->resourceConnectionMock); + } + + public function testGetFilter() + { + $condition = ["type" => "variable", "_value" => "1", "attribute" => "id", "operator" => "neq"]; + $valueCondition = ["type" => "value", "_value" => "2", "attribute" => "first_name", "operator" => "eq"]; + $identifierCondition = [ + "type" => "identifier", + "_value" => "other_field", + "attribute" => "last_name", + "operator" => "eq"]; + $filter = [["glue" => "AND", "condition" => [$valueCondition]]]; + $filterConfig = [ + ["glue" => "OR", "condition" => [$condition], 'filter' => $filter], + ["glue" => "OR", "condition" => [$identifierCondition]], + ]; + $aliasName = 'n'; + $this->selectBuilderMock->expects($this->any()) + ->method('setParams') + ->with(array_merge([], [$condition['_value']])); + + $this->selectBuilderMock->expects($this->once()) + ->method('getParams') + ->willReturn([]); + + $this->selectBuilderMock->expects($this->any()) + ->method('getColumns') + ->willReturn(['price' => new Expression("(n.price = 400)")]); + + $this->resourceConnectionMock->expects($this->once()) + ->method('getConnection') + ->willReturn($this->connectionMock); + + $this->connectionMock->expects($this->any()) + ->method('quote') + ->willReturn("'John'"); + $this->connectionMock->expects($this->exactly(4)) + ->method('quoteIdentifier') + ->willReturnMap([ + ['n.id', false, '`n`.`id`'], + ['n.first_name', false, '`n`.`first_name`'], + ['n.last_name', false, '`n`.`last_name`'], + ['other_field', false, '`other_field`'], + ]); + + $result = "(`n`.`id` != 1 OR ((`n`.`first_name` = 'John'))) OR (`n`.`last_name` = `other_field`)"; + $this->assertEquals( + $result, + $this->conditionResolver->getFilter($this->selectBuilderMock, $filterConfig, $aliasName) + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php new file mode 100644 index 0000000000000..4accd03aef3ea --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/NameResolverTest.php @@ -0,0 +1,90 @@ +nameResolverMock = $this->getMockBuilder(NameResolver::class) + ->disableOriginalConstructor() + ->setMethods(['getName']) + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + $this->nameResolver = $this->objectManagerHelper->getObject(NameResolver::class); + } + + public function testGetName() + { + $elementConfigMock = [ + 'name' => 'sales_order', + 'alias' => 'sales', + ]; + + $this->assertSame('sales_order', $this->nameResolver->getName($elementConfigMock)); + } + + /** + * @param array $elementConfig + * @param string|null $elementAlias + * + * @dataProvider getAliasDataProvider + */ + public function testGetAlias($elementConfig, $elementAlias) + { + $elementName = 'elementName'; + + $this->nameResolverMock + ->expects($this->once()) + ->method('getName') + ->with($elementConfig) + ->willReturn($elementName); + + $this->assertSame($elementAlias ?: $elementName, $this->nameResolverMock->getAlias($elementConfig)); + } + + /** + * @return array + */ + public function getAliasDataProvider() + { + return [ + 'ElementConfigWithAliases' => [ + ['alias' => 'sales', 'name' => 'sales_order'], + 'sales', + ], + 'ElementConfigWithoutAliases' => [ + ['name' => 'sales_order'], + null, + ] + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php new file mode 100644 index 0000000000000..bbb9ca4b511b6 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/ReportValidatorTest.php @@ -0,0 +1,125 @@ +connectionFactoryMock = $this->getMockBuilder(ConnectionFactory::class) + ->disableOriginalConstructor()->getMock(); + $this->queryFactoryMock = $this->getMockBuilder(QueryFactory::class) + ->disableOriginalConstructor()->getMock(); + $this->queryMock = $this->getMockBuilder(Query::class)->disableOriginalConstructor() + ->getMock(); + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMockForAbstractClass(); + $this->selectMock = $this->getMockBuilder(Select::class)->disableOriginalConstructor() + ->getMock(); + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->reportValidator = $this->objectManagerHelper->getObject( + ReportValidator::class, + [ + 'connectionFactory' => $this->connectionFactoryMock, + 'queryFactory' => $this->queryFactoryMock + ] + ); + } + + /** + * @dataProvider errorDataProvider + * @param string $reportName + * @param array $result + * @param \PHPUnit_Framework_MockObject_Stub $queryReturnStub + */ + public function testValidate($reportName, $result, \PHPUnit_Framework_MockObject_Stub $queryReturnStub) + { + $connectionName = 'testConnection'; + $this->queryFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->queryMock); + $this->queryMock->expects($this->once())->method('getConnectionName')->willReturn($connectionName); + $this->connectionFactoryMock->expects($this->once())->method('getConnection') + ->with($connectionName) + ->willReturn($this->connectionMock); + $this->queryMock->expects($this->atLeastOnce())->method('getSelect')->willReturn($this->selectMock); + $this->selectMock->expects($this->once())->method('limit')->with(0); + $this->connectionMock->expects($this->once())->method('query')->with($this->selectMock)->will($queryReturnStub); + $this->assertEquals($result, $this->reportValidator->validate($reportName)); + } + + /** + * Provide variations of the error returning + * + * @return array + */ + public function errorDataProvider() + { + $reportName = 'test'; + $errorMessage = 'SQL Error 42'; + return [ + [ + $reportName, + 'expectedResult' => [], + 'queryReturnStub' => $this->returnValue(null) + ], + [ + $reportName, + 'expectedResult' => [$reportName, $errorMessage], + 'queryReturnStub' => $this->throwException(new \Zend_Db_Statement_Exception($errorMessage)) + ] + ]; + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php new file mode 100644 index 0000000000000..a82a187cdb3f8 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/SelectBuilderTest.php @@ -0,0 +1,103 @@ +resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectMock = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectBuilder = new SelectBuilder($this->resourceConnectionMock); + } + + public function testCreate() + { + $connectionName = 'MySql'; + $from = ['customer c']; + $columns = ['id', 'name', 'price']; + $filter = 'filter'; + $joins = [ + ['link-type' => 'left', 'table' => 'customer', 'condition' => 'in'], + ['link-type' => 'inner', 'table' => 'price', 'condition' => 'eq'], + ['link-type' => 'right', 'table' => 'attribute', 'condition' => 'neq'], + ]; + $groups = ['id', 'name']; + $this->selectBuilder->setConnectionName($connectionName); + $this->selectBuilder->setFrom($from); + $this->selectBuilder->setColumns($columns); + $this->selectBuilder->setFilters([$filter]); + $this->selectBuilder->setJoins($joins); + $this->selectBuilder->setGroup($groups); + $this->resourceConnectionMock->expects($this->once()) + ->method('getConnection') + ->with($connectionName) + ->willReturn($this->connectionMock); + $this->connectionMock->expects($this->once()) + ->method('select') + ->willReturn($this->selectMock); + $this->selectMock->expects($this->once()) + ->method('from') + ->with($from, []); + $this->selectMock->expects($this->once()) + ->method('columns') + ->with($columns); + $this->selectMock->expects($this->once()) + ->method('where') + ->with($filter); + $this->selectMock->expects($this->once()) + ->method('joinLeft') + ->with($joins[0]['table'], $joins[0]['condition'], []); + $this->selectMock->expects($this->once()) + ->method('joinInner') + ->with($joins[1]['table'], $joins[1]['condition'], []); + $this->selectMock->expects($this->once()) + ->method('joinRight') + ->with($joins[2]['table'], $joins[2]['condition'], []); + $this->selectBuilder->create(); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php new file mode 100644 index 0000000000000..1d3f293ed676a --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/IteratorFactoryTest.php @@ -0,0 +1,59 @@ +objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->iteratorIteratorMock = $this->getMockBuilder(\IteratorIterator::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->iteratorFactory = new IteratorFactory( + $this->objectManagerMock + ); + } + + public function testCreate() + { + $arrayObject = new \ArrayIterator([1, 2, 3, 4, 5]); + $this->objectManagerMock->expects($this->once()) + ->method('create') + ->with(\IteratorIterator::class, ['iterator' => $arrayObject]) + ->willReturn($this->iteratorIteratorMock); + + $this->assertEquals($this->iteratorFactory->create($arrayObject), $this->iteratorIteratorMock); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php new file mode 100644 index 0000000000000..9a3805a50f167 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryFactoryTest.php @@ -0,0 +1,239 @@ +queryMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\Query::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\Config::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectMock = $this->getMockBuilder( + \Magento\Framework\DB\Select::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->assemblerMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\Assembler\AssemblerInterface::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->queryCacheMock = $this->getMockBuilder( + \Magento\Framework\App\CacheInterface::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerMock = $this->getMockBuilder( + \Magento\Framework\ObjectManagerInterface::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectHydratorMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\SelectHydrator::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectBuilderFactoryMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\SelectBuilderFactory::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\ReportXml\QueryFactory::class, + [ + 'config' => $this->configMock, + 'selectBuilderFactory' => $this->selectBuilderFactoryMock, + 'assemblers' => [$this->assemblerMock], + 'queryCache' => $this->queryCacheMock, + 'objectManager' => $this->objectManagerMock, + 'selectHydrator' => $this->selectHydratorMock + ] + ); + } + + /** + * @return void + */ + public function testCreateCached() + { + $queryName = 'test_query'; + + $this->queryCacheMock->expects($this->any()) + ->method('load') + ->with($queryName) + ->willReturn('{"connectionName":"sales","config":{},"select_parts":{}}'); + + $this->selectHydratorMock->expects($this->any()) + ->method('recreate') + ->with([]) + ->willReturn($this->selectMock); + + $this->objectManagerMock->expects($this->once()) + ->method('create') + ->with( + \Magento\Analytics\ReportXml\Query::class, + [ + 'select' => $this->selectMock, + 'selectHydrator' => $this->selectHydratorMock, + 'connectionName' => 'sales', + 'config' => [] + ] + ) + ->willReturn($this->queryMock); + + $this->queryCacheMock->expects($this->never()) + ->method('save'); + + $this->assertEquals( + $this->queryMock, + $this->subject->create($queryName) + ); + } + + /** + * @return void + */ + public function testCreateNotCached() + { + $queryName = 'test_query'; + + $queryConfigMock = [ + 'name' => 'test_query', + 'connection' => 'sales' + ]; + + $selectBuilderMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\DB\SelectBuilder::class + ) + ->disableOriginalConstructor() + ->getMock(); + $selectBuilderMock->expects($this->once()) + ->method('setConnectionName') + ->with($queryConfigMock['connection']); + $selectBuilderMock->expects($this->any()) + ->method('create') + ->willReturn($this->selectMock); + $selectBuilderMock->expects($this->any()) + ->method('getConnectionName') + ->willReturn($queryConfigMock['connection']); + + $this->queryCacheMock->expects($this->any()) + ->method('load') + ->with($queryName) + ->willReturn(null); + + $this->configMock->expects($this->any()) + ->method('get') + ->with($queryName) + ->willReturn($queryConfigMock); + + $this->selectBuilderFactoryMock->expects($this->any()) + ->method('create') + ->willReturn($selectBuilderMock); + + $this->assemblerMock->expects($this->once()) + ->method('assemble') + ->with($selectBuilderMock, $queryConfigMock) + ->willReturn($selectBuilderMock); + + $this->objectManagerMock->expects($this->once()) + ->method('create') + ->with( + \Magento\Analytics\ReportXml\Query::class, + [ + 'select' => $this->selectMock, + 'selectHydrator' => $this->selectHydratorMock, + 'connectionName' => $queryConfigMock['connection'], + 'config' => $queryConfigMock + ] + ) + ->willReturn($this->queryMock); + + $this->queryCacheMock->expects($this->once()) + ->method('save') + ->with(json_encode($this->queryMock), $queryName); + + $this->assertEquals( + $this->queryMock, + $this->subject->create($queryName) + ); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php new file mode 100644 index 0000000000000..a4b08a9ce5e0a --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/QueryTest.php @@ -0,0 +1,90 @@ +selectMock = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectHydratorMock = $this->getMockBuilder(selectHydrator::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->query = $this->objectManagerHelper->getObject( + Query::class, + [ + 'select' => $this->selectMock, + 'connectionName' => $this->connectionName, + 'selectHydrator' => $this->selectHydratorMock, + 'config' => [] + ] + ); + } + + /** + * @return void + */ + public function testJsonSerialize() + { + $selectParts = ['part' => 1]; + + $this->selectHydratorMock + ->expects($this->once()) + ->method('extract') + ->with($this->selectMock) + ->willReturn($selectParts); + + $expectedResult = [ + 'connectionName' => $this->connectionName, + 'select_parts' => $selectParts, + 'config' => [] + ]; + + $this->assertSame($expectedResult, $this->query->jsonSerialize()); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php new file mode 100644 index 0000000000000..5f329993dd291 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/ReportProviderTest.php @@ -0,0 +1,180 @@ +selectMock = $this->getMockBuilder( + \Magento\Framework\DB\Select::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->queryMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\Query::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->queryMock->expects($this->any()) + ->method('getSelect') + ->willReturn($this->selectMock); + + $this->iteratorMock = $this->getMockBuilder( + \IteratorIterator::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->statementMock = $this->getMockBuilder( + \Magento\Framework\DB\Statement\Pdo\Mysql::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->statementMock->expects($this->any()) + ->method('getIterator') + ->willReturn($this->iteratorMock); + + $this->connectionMock = $this->getMockBuilder( + \Magento\Framework\DB\Adapter\AdapterInterface::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->queryFactoryMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\QueryFactory::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->iteratorFactoryMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\IteratorFactory::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->iteratorMock = $this->getMockBuilder( + \IteratorIterator::class + ) + ->disableOriginalConstructor() + ->getMock(); + $this->objectManagerHelper = + new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->connectionFactoryMock = $this->getMockBuilder( + \Magento\Analytics\ReportXml\ConnectionFactory::class + ) + ->disableOriginalConstructor() + ->getMock(); + + $this->subject = $this->objectManagerHelper->getObject( + \Magento\Analytics\ReportXml\ReportProvider::class, + [ + 'queryFactory' => $this->queryFactoryMock, + 'connectionFactory' => $this->connectionFactoryMock, + 'iteratorFactory' => $this->iteratorFactoryMock + ] + ); + } + + /** + * @return void + */ + public function testGetReport() + { + $reportName = 'test_report'; + $connectionName = 'sales'; + + $this->queryFactoryMock->expects($this->once()) + ->method('create') + ->with($reportName) + ->willReturn($this->queryMock); + + $this->connectionFactoryMock->expects($this->once()) + ->method('getConnection') + ->with($connectionName) + ->willReturn($this->connectionMock); + + $this->queryMock->expects($this->once()) + ->method('getConnectionName') + ->willReturn($connectionName); + + $this->queryMock->expects($this->once()) + ->method('getConfig') + ->willReturn( + [ + 'connection' => $connectionName + ] + ); + + $this->connectionMock->expects($this->once()) + ->method('query') + ->with($this->selectMock) + ->willReturn($this->statementMock); + + $this->iteratorFactoryMock->expects($this->once()) + ->method('create') + ->with($this->statementMock, null) + ->willReturn($this->iteratorMock); + $this->assertEquals($this->iteratorMock, $this->subject->getReport($reportName)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php new file mode 100644 index 0000000000000..ce57a1eca3689 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/SelectHydratorTest.php @@ -0,0 +1,257 @@ +resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->connectionMock = $this->getMockBuilder(AdapterInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->selectMock = $this->getMockBuilder(Select::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerMock = $this->getMockBuilder(ObjectManagerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->selectHydrator = $this->objectManagerHelper->getObject( + SelectHydrator::class, + [ + 'resourceConnection' => $this->resourceConnectionMock, + 'objectManager' => $this->objectManagerMock, + ] + ); + } + + public function testExtract() + { + $selectParts = + [ + Select::DISTINCT, + Select::COLUMNS, + Select::UNION, + Select::FROM, + Select::WHERE, + Select::GROUP, + Select::HAVING, + Select::ORDER, + Select::LIMIT_COUNT, + Select::LIMIT_OFFSET, + Select::FOR_UPDATE + ]; + + $result = []; + foreach ($selectParts as $part) { + $result[$part] = "Part"; + } + $this->selectMock->expects($this->any()) + ->method('getPart') + ->willReturn("Part"); + $this->assertEquals($this->selectHydrator->extract($this->selectMock), $result); + } + + /** + * @dataProvider recreateWithoutExpressionDataProvider + * @param array $selectParts + * @param array $parts + * @param array $partValues + */ + public function testRecreateWithoutExpression($selectParts, $parts, $partValues) + { + $this->resourceConnectionMock->expects($this->once()) + ->method('getConnection') + ->willReturn($this->connectionMock); + $this->connectionMock->expects($this->once()) + ->method('select') + ->willReturn($this->selectMock); + foreach ($parts as $key => $part) { + $this->selectMock->expects($this->at($key)) + ->method('setPart') + ->with($part, $partValues[$key]); + } + + $this->assertSame($this->selectMock, $this->selectHydrator->recreate($selectParts)); + } + + /** + * @return array + */ + public function recreateWithoutExpressionDataProvider() + { + return [ + 'Select without expressions' => [ + [ + Select::COLUMNS => [ + [ + 'table_name', + 'field_name', + 'alias', + ], + [ + 'table_name', + 'field_name_2', + 'alias_2', + ], + ] + ], + [Select::COLUMNS], + [[ + [ + 'table_name', + 'field_name', + 'alias', + ], + [ + 'table_name', + 'field_name_2', + 'alias_2', + ], + ]], + ], + ]; + } + + /** + * @dataProvider recreateWithExpressionDataProvider + * @param array $selectParts + * @param array $expectedParts + * @param \PHPUnit_Framework_MockObject_MockObject[] $expressionMocks + */ + public function testRecreateWithExpression( + array $selectParts, + array $expectedParts, + array $expressionMocks + ) { + $this->objectManagerMock + ->expects($this->exactly(count($expressionMocks))) + ->method('create') + ->with($this->isType('string'), $this->isType('array')) + ->willReturnOnConsecutiveCalls(...$expressionMocks); + $this->resourceConnectionMock + ->expects($this->once()) + ->method('getConnection') + ->with() + ->willReturn($this->connectionMock); + $this->connectionMock + ->expects($this->once()) + ->method('select') + ->with() + ->willReturn($this->selectMock); + foreach (array_keys($selectParts) as $key => $partName) { + $this->selectMock + ->expects($this->at($key)) + ->method('setPart') + ->with($partName, $expectedParts[$partName]); + } + + $this->assertSame($this->selectMock, $this->selectHydrator->recreate($selectParts)); + } + + /** + * @return array + */ + public function recreateWithExpressionDataProvider() + { + $expressionMock = $this->getMockBuilder(JsonSerializableExpression::class) + ->disableOriginalConstructor() + ->getMock(); + + return [ + 'Select without expressions' => [ + 'Parts' => [ + Select::COLUMNS => [ + [ + 'table_name', + 'field_name', + 'alias', + ], + [ + 'table_name', + [ + 'class' => 'Some_class', + 'arguments' => [ + 'expression' => ['some(expression)'] + ] + ], + 'alias_2', + ], + ] + ], + 'expectedParts' => [ + Select::COLUMNS => [ + [ + 'table_name', + 'field_name', + 'alias', + ], + [ + 'table_name', + $expressionMock, + 'alias_2', + ], + ] + ], + 'expectedExpressions' => [ + $expressionMock + ] + ], + ]; + } +} diff --git a/app/code/Magento/Analytics/composer.json b/app/code/Magento/Analytics/composer.json new file mode 100644 index 0000000000000..6ff7850a95498 --- /dev/null +++ b/app/code/Magento/Analytics/composer.json @@ -0,0 +1,26 @@ +{ + "name": "magento/module-analytics", + "description": "N/A", + "require": { + "php": "~7.0.13|~7.1.0", + "magento/module-backend": "100.2.*", + "magento/module-config": "101.0.*", + "magento/module-integration": "100.2.*", + "magento/module-store": "100.2.*", + "magento/framework": "101.0.*" + }, + "type": "magento2-module", + "version": "100.2.0", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\Analytics\\": "" + } + } +} diff --git a/app/code/Magento/Analytics/docs/images/M2_MA_signup.png b/app/code/Magento/Analytics/docs/images/M2_MA_signup.png new file mode 100644 index 0000000000000..78ed8fad92881 Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/M2_MA_signup.png differ diff --git a/app/code/Magento/Analytics/docs/images/analytics_modules.png b/app/code/Magento/Analytics/docs/images/analytics_modules.png new file mode 100644 index 0000000000000..0bf6048b0d9cc Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/analytics_modules.png differ diff --git a/app/code/Magento/Analytics/docs/images/data_transition.png b/app/code/Magento/Analytics/docs/images/data_transition.png new file mode 100644 index 0000000000000..a75e97983e15d Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/data_transition.png differ diff --git a/app/code/Magento/Analytics/docs/images/definition.png b/app/code/Magento/Analytics/docs/images/definition.png new file mode 100644 index 0000000000000..16acc576320b0 Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/definition.png differ diff --git a/app/code/Magento/Analytics/docs/images/mbi_file_exchange.png b/app/code/Magento/Analytics/docs/images/mbi_file_exchange.png new file mode 100644 index 0000000000000..f39d2e4900703 Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/mbi_file_exchange.png differ diff --git a/app/code/Magento/Analytics/docs/images/signup.png b/app/code/Magento/Analytics/docs/images/signup.png new file mode 100644 index 0000000000000..561e18b3a351f Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/signup.png differ diff --git a/app/code/Magento/Analytics/docs/images/update.png b/app/code/Magento/Analytics/docs/images/update.png new file mode 100644 index 0000000000000..149f5b5d3f9bd Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/update.png differ diff --git a/app/code/Magento/Analytics/docs/images/update_request.png b/app/code/Magento/Analytics/docs/images/update_request.png new file mode 100644 index 0000000000000..7181251e3634e Binary files /dev/null and b/app/code/Magento/Analytics/docs/images/update_request.png differ diff --git a/app/code/Magento/Analytics/etc/acl.xml b/app/code/Magento/Analytics/etc/acl.xml new file mode 100644 index 0000000000000..bf2251895f929 --- /dev/null +++ b/app/code/Magento/Analytics/etc/acl.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/Magento/Analytics/etc/adminhtml/di.xml b/app/code/Magento/Analytics/etc/adminhtml/di.xml new file mode 100644 index 0000000000000..5e305e70e5ad3 --- /dev/null +++ b/app/code/Magento/Analytics/etc/adminhtml/di.xml @@ -0,0 +1,16 @@ + + + + + + + Magento\Analytics\Model\System\Message\NotificationAboutFailedSubscription + + + + diff --git a/app/code/Magento/Analytics/etc/adminhtml/menu.xml b/app/code/Magento/Analytics/etc/adminhtml/menu.xml new file mode 100644 index 0000000000000..915211c4bb85e --- /dev/null +++ b/app/code/Magento/Analytics/etc/adminhtml/menu.xml @@ -0,0 +1,19 @@ + + + + + + + + + diff --git a/app/code/Magento/Analytics/etc/adminhtml/routes.xml b/app/code/Magento/Analytics/etc/adminhtml/routes.xml new file mode 100644 index 0000000000000..0ae2762dacc5f --- /dev/null +++ b/app/code/Magento/Analytics/etc/adminhtml/routes.xml @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/app/code/Magento/Analytics/etc/adminhtml/system.xml b/app/code/Magento/Analytics/etc/adminhtml/system.xml new file mode 100644 index 0000000000000..889517e629e04 --- /dev/null +++ b/app/code/Magento/Analytics/etc/adminhtml/system.xml @@ -0,0 +1,50 @@ + + + + +
+ + general + Magento_Analytics::analytics_settings + + + For more information, see our + terms and conditions.]]> + + + Magento\Config\Model\Config\Source\Enabledisable + Magento\Analytics\Model\Config\Backend\Enabled + Magento\Analytics\Block\Adminhtml\System\Config\SubscriptionStatusLabel + analytics/subscription/enabled + + + + Magento\Analytics\Block\Adminhtml\System\Config\CollectionTimeLabel + Magento\Analytics\Model\Config\Backend\CollectionTime + + + Industry Data + + In order to personalize your Advanced Reporting experience, please select your industry. + Magento\Analytics\Model\Config\Source\Vertical + Magento\Analytics\Model\Config\Backend\Vertical + Magento\Analytics\Block\Adminhtml\System\Config\Vertical + + + + Learn more about Magento BI Essentials and BI Pro tiers.]]> + Magento\Analytics\Block\Adminhtml\System\Config\AdditionalComment + + +
+
+
diff --git a/app/code/Magento/Analytics/etc/analytics.xml b/app/code/Magento/Analytics/etc/analytics.xml new file mode 100644 index 0000000000000..77ebe751a31cf --- /dev/null +++ b/app/code/Magento/Analytics/etc/analytics.xml @@ -0,0 +1,50 @@ + + + + + + + + modules + + + + + + + + + + + + + + stores + + + + + + + + + websites + + + + + + + + + groups + + + + + diff --git a/app/code/Magento/Analytics/etc/analytics.xsd b/app/code/Magento/Analytics/etc/analytics.xsd new file mode 100644 index 0000000000000..2506e3d6a6a9a --- /dev/null +++ b/app/code/Magento/Analytics/etc/analytics.xsd @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + File name attribute can has only [a-zA-Z0-9/_]. + + + + + + + + + + Value is required. + + + + + + + diff --git a/app/code/Magento/Analytics/etc/config.xml b/app/code/Magento/Analytics/etc/config.xml new file mode 100644 index 0000000000000..b6194ba12993f --- /dev/null +++ b/app/code/Magento/Analytics/etc/config.xml @@ -0,0 +1,25 @@ + + + + + + + https://advancedreporting.rjmetrics.com/signup + https://advancedreporting.rjmetrics.com/update + https://dashboard.rjmetrics.com/v2/magento/signup + https://advancedreporting.rjmetrics.com/otp + https://advancedreporting.rjmetrics.com/report + https://advancedreporting.rjmetrics.com/report + + Magento Analytics user + + 02,00,00 + + + + diff --git a/app/code/Magento/Analytics/etc/crontab.xml b/app/code/Magento/Analytics/etc/crontab.xml new file mode 100644 index 0000000000000..a4beef0359540 --- /dev/null +++ b/app/code/Magento/Analytics/etc/crontab.xml @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml new file mode 100644 index 0000000000000..b9bb9cc9ff00c --- /dev/null +++ b/app/code/Magento/Analytics/etc/di.xml @@ -0,0 +1,275 @@ + + + + + + + + + + + + + + + Magento\Analytics\Model\Connector\SignUpCommand + Magento\Analytics\Model\Connector\UpdateCommand + Magento\Analytics\Model\Connector\NotifyDataChangedCommand + + + + + + + Magento\Analytics\ReportXml\Config\Data + + + + + Magento\Analytics\ReportXml\Config\Reader + Magento_Analytics_ReportXml_CacheId + + + + + urn:magento:module:Magento_Analytics:etc/reports.xsd + + + + + Magento\Analytics\ReportXml\Config\Converter\Xml + Magento\Analytics\ReportXml\Config\SchemaLocator + reports.xml + + name + + name + alias + + name + name + + glue + + attribute + operator + + + glue + + attribute + operator + + + glue + + attribute + operator + + glue + + attribute + operator + + + + + + + + Magento\Analytics\ReportXml\Config\Reader\Xml + + + + + + + Magento\Analytics\Model\Config\Data + + + + + Magento\Analytics\Model\Config\Reader + Magento_Analytics_CacheId + + + + + urn:magento:module:Magento_Analytics:etc/analytics.xsd + + + + + Magento\Analytics\ReportXml\Config\Converter\Xml + Magento\Analytics\Model\Config\SchemaLocator + analytics.xml + + name + + + + + + + + Magento\Analytics\ReportXml\DB\Assembler\FromAssembler + Magento\Analytics\ReportXml\DB\Assembler\FilterAssembler + Magento\Analytics\ReportXml\DB\Assembler\JoinAssembler + + + + + + + Magento\Analytics\Model\Config\Reader\Xml + + + + + + + web/unsecure/base_url + currency/options/base + general/locale/timezone + general/country/default + carriers/dhl/title + carriers/dhl/active + carriers/fedex/title + carriers/fedex/active + carriers/flatrate/title + carriers/flatrate/active + carriers/tablerate/title + carriers/tablerate/active + carriers/freeshipping/title + carriers/freeshipping/active + carriers/ups/title + carriers/ups/active + carriers/usps/title + carriers/usps/active + payment/free/title + payment/free/active + payment/checkmo/title + payment/checkmo/active + payment/purchaseorder/title + payment/purchaseorder/active + payment/banktransfer/title + payment/banktransfer/active + payment/cashondelivery/title + payment/cashondelivery/active + payment/authorizenet_directpost/title + payment/authorizenet_directpost/active + payment/paypal_billing_agreement/title + payment/paypal_billing_agreement/active + payment/braintree/title + payment/braintree/active + payment/braintree_paypal/title + payment/braintree_paypal/active + analytics/general/vertical + + + + + + + Apps and Games + Athletic/Sporting Goods + Art and Design + Auto Parts + Baby/Children’s Apparel, Gear and Toys + Beauty and Cosmetics + Books, Music and Magazines + Crafts and Stationery + Consumer Electronics + Deal Site + Fashion Apparel and Accessories + Food, Beverage and Grocery + Home Goods and Furniture + Home Improvement + Jewelry and Watches + Mass Merchant + Office Supplies + Outdoor and Camping Gear + Pet Goods + Pharma and Medical Devices + Technology B2B + Other + + + + + + + + + + \Magento\Analytics\Model\Connector\ResponseHandler\SignUp + + + + + + + Magento\Analytics\Model\Connector\ResponseHandler\Update + Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp + + + + + + + Magento\Analytics\Model\Connector\ResponseHandler\OTP + Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp + + + + + + + Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp + + + + + + SignUpResponseResolver + + + + + UpdateResponseResolver + + + + + OtpResponseResolver + + + + + NotifyDataChangedResponseResolver + + + + + + 1 + 1 + 1 + 1 + 1 + 1 + 1 + + + 1 + 1 + 1 + + + + diff --git a/app/code/Magento/Analytics/etc/module.xml b/app/code/Magento/Analytics/etc/module.xml new file mode 100644 index 0000000000000..32ee5d23a4d86 --- /dev/null +++ b/app/code/Magento/Analytics/etc/module.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/app/code/Magento/Analytics/etc/reports.xml b/app/code/Magento/Analytics/etc/reports.xml new file mode 100644 index 0000000000000..8a43658670293 --- /dev/null +++ b/app/code/Magento/Analytics/etc/reports.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/code/Magento/Analytics/etc/reports.xsd b/app/code/Magento/Analytics/etc/reports.xsd new file mode 100644 index 0000000000000..d0ba4068244fe --- /dev/null +++ b/app/code/Magento/Analytics/etc/reports.xsd @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/Magento/Analytics/etc/webapi.xml b/app/code/Magento/Analytics/etc/webapi.xml new file mode 100644 index 0000000000000..8252d039f1d03 --- /dev/null +++ b/app/code/Magento/Analytics/etc/webapi.xml @@ -0,0 +1,16 @@ + + + + + + + + + + diff --git a/app/code/Magento/Analytics/i18n/en_US.csv b/app/code/Magento/Analytics/i18n/en_US.csv new file mode 100644 index 0000000000000..516c388feb823 --- /dev/null +++ b/app/code/Magento/Analytics/i18n/en_US.csv @@ -0,0 +1,84 @@ +"Subscription status","Subscription status" +"Sorry, there has been an error processing your request. Please try again later.","Sorry, there has been an error processing your request. Please try again later." +"Sorry, there was an error processing your registration request to Magento Analytics. Please try again later.","Sorry, there was an error processing your registration request to Magento Analytics. Please try again later." +"Error occurred during postponement notification","Error occurred during postponement notification" +"Time value has an unsupported format","Time value has an unsupported format" +"Cron settings can't be saved","Cron settings can't be saved" +"There was an error save new configuration value.","There was an error save new configuration value." +"Please select a vertical.","Please select a vertical." +"--Please Select--","--Please Select--" +"Command was not found.","Command was not found." +"Input data must be string or convertible into string.","Input data must be string or convertible into string." +"Input data must be non-empty string.","Input data must be non-empty string." +"Not valid cipher method.","Not valid cipher method." +"Encryption key can't be empty.","Encryption key can't be empty." +"Source ""%1"" is not exist","Source ""%1"" is not exist" +"These arguments can't be empty ""%1""","These arguments can't be empty ""%1""" +"Cannot find predefined integration user!","Cannot find predefined integration user!" +"File is not ready yet.","File is not ready yet." +"Your Base URL has been changed and your reports are being updated. Advanced Reporting will be available once this change has been processed. Please try again later.","Your Base URL has been changed and your reports are being updated. Advanced Reporting will be available once this change has been processed. Please try again later." +"Failed to synchronize data to the Magento Business Intelligence service. ","Failed to synchronize data to the Magento Business Intelligence service. " +"Retry Synchronization","Retry Synchronization" +TestMessage,TestMessage +"Error message","Error message" +"Apps and Games","Apps and Games" +"Athletic/Sporting Goods","Athletic/Sporting Goods" +"Art and Design","Art and Design" +"Advanced Reporting","Advanced Reporting" +"Gain new insights and take command of your business' performance, using our dynamic product, order, and customer reports tailored to your customer data.","Gain new insights and take command of your business' performance, using our dynamic product, order, and customer reports tailored to your customer data." +"View details","View details" +"Go to Advanced Reporting","Go to Advanced Reporting" +"An error occurred while subscription process.","An error occurred while subscription process." +Analytics,Analytics +API,API +Configuration,Configuration +"Business Intelligence","Business Intelligence" +"BI Essentials","BI Essentials" +"This service provides a dynamic suite of reports with rich insights about your business. + Your reports can be accessed securely on a personalized dashboard outside of the admin panel by clicking on the + ""Go to Advanced Reporting"" link.
For more information, see our + terms and conditions. + ","This service provides a dynamic suite of reports with rich insights about your business. + Your reports can be accessed securely on a personalized dashboard outside of the admin panel by clicking on the + ""Go to Advanced Reporting"" link.
For more information, see our + terms and conditions." +"Advanced Reporting Service","Advanced Reporting Service" +Industry,Industry +"Time of day to send data","Time of day to send data" +"Get more insights from Magento Business Intelligence","Get more insights from Magento Business Intelligence" +"Magento Business Intelligence provides you with a simple and clear path to + becoming more data driven.
Learn more about BI Essentials tier.","Magento Business Intelligence provides you with a simple and clear path to + becoming more data driven.
Learn more about BI Essentials tier." +"Auto Parts","Auto Parts" +"Baby/Children’s Apparel, Gear and Toys","Baby/Children’s Apparel, Gear and Toys" +"Beauty and Cosmetics","Beauty and Cosmetics" +"Books, Music and Magazines","Books, Music and Magazines" +"Crafts and Stationery","Crafts and Stationery" +"Consumer Electronics","Consumer Electronics" +"Deal Site","Deal Site" +"Fashion Apparel and Accessories","Fashion Apparel and Accessories" +"Food, Beverage and Grocery","Food, Beverage and Grocery" +"Home Goods and Furniture","Home Goods and Furniture" +"Home Improvement","Home Improvement" +"Jewelry and Watches","Jewelry and Watches" +"Mass Merchant","Mass Merchant" +"Office Supplies","Office Supplies" +"Outdoor and Camping Gear","Outdoor and Camping Gear" +"Pet Goods","Pet Goods" +"Pharma and Medical Devices","Pharma and Medical Devices" +"Technology B2B","Technology B2B" +"Analytics Subscription","Analytics Subscription" +"powered by Magento Business Intelligence","powered by Magento Business Intelligence" +"Are you sure you want to opt out?","Are you sure you want to opt out?" +Cancel,Cancel +"Opt out","Opt out" +"

Advanced Reporting in included, + free of charge, in your Magento software. When you opt out, we collect no product, order, and + customer data to generate our dynamic reports.

To opt in later: You can always turn on Advanced + Reporting in you Admin Panel.

","

Advanced Reporting in included, + free of charge, in your Magento software. When you opt out, we collect no product, order, and + customer data to generate our dynamic reports.

To opt in later: You can always turn on Advanced + Reporting in you Admin Panel.

" +"In order to personalize your Advanced Reporting experience, please select your industry.","In order to personalize your Advanced Reporting experience, please select your industry." diff --git a/app/code/Magento/Analytics/registration.php b/app/code/Magento/Analytics/registration.php new file mode 100644 index 0000000000000..58d3688b7491d --- /dev/null +++ b/app/code/Magento/Analytics/registration.php @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/app/code/Magento/Analytics/view/adminhtml/templates/dashboard/section.phtml b/app/code/Magento/Analytics/view/adminhtml/templates/dashboard/section.phtml new file mode 100644 index 0000000000000..a22c603b2a8b3 --- /dev/null +++ b/app/code/Magento/Analytics/view/adminhtml/templates/dashboard/section.phtml @@ -0,0 +1,28 @@ + + +
+
+
+ escapeHtml(__('Advanced Reporting')) ?> +
+
+ escapeHtml(__('Gain new insights and take command of your business\' performance,' . + ' using our dynamic product, order, and customer reports tailored to your customer data.')) ?> +
+
+ +
diff --git a/app/code/Magento/Authorization/composer.json b/app/code/Magento/Authorization/composer.json index c0b0f9c6b13df..22483b7961841 100644 --- a/app/code/Magento/Authorization/composer.json +++ b/app/code/Magento/Authorization/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-authorization", "description": "Authorization module provides access to Magento ACL functionality.", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*" }, diff --git a/app/code/Magento/Authorizenet/composer.json b/app/code/Magento/Authorizenet/composer.json index 1022bd47a5786..c389a1c6c4dfa 100644 --- a/app/code/Magento/Authorizenet/composer.json +++ b/app/code/Magento/Authorizenet/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-authorizenet", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-sales": "101.0.*", "magento/module-store": "100.2.*", "magento/module-quote": "101.0.*", diff --git a/app/code/Magento/Backend/Block/Cache.php b/app/code/Magento/Backend/Block/Cache.php index e14358396aa70..82c36bf3a1fe4 100644 --- a/app/code/Magento/Backend/Block/Cache.php +++ b/app/code/Magento/Backend/Block/Cache.php @@ -22,24 +22,29 @@ protected function _construct() $this->_headerText = __('Cache Storage Management'); parent::_construct(); $this->buttonList->remove('add'); - $this->buttonList->add( - 'flush_magento', - [ - 'label' => __('Flush Magento Cache'), - 'onclick' => 'setLocation(\'' . $this->getFlushSystemUrl() . '\')', - 'class' => 'primary flush-cache-magento' - ] - ); - $message = __('The cache storage may contain additional data. Are you sure that you want to flush it?'); - $this->buttonList->add( - 'flush_system', - [ - 'label' => __('Flush Cache Storage'), - 'onclick' => 'confirmSetLocation(\'' . $message . '\', \'' . $this->getFlushStorageUrl() . '\')', - 'class' => 'flush-cache-storage' - ] - ); + if ($this->_authorization->isAllowed('Magento_Backend::flush_magento_cache')) { + $this->buttonList->add( + 'flush_magento', + [ + 'label' => __('Flush Magento Cache'), + 'onclick' => 'setLocation(\'' . $this->getFlushSystemUrl() . '\')', + 'class' => 'primary flush-cache-magento' + ] + ); + } + + if ($this->_authorization->isAllowed('Magento_Backend::flush_cache_storage')) { + $message = __('The cache storage may contain additional data. Are you sure that you want to flush it?'); + $this->buttonList->add( + 'flush_system', + [ + 'label' => __('Flush Cache Storage'), + 'onclick' => 'confirmSetLocation(\'' . $message . '\', \'' . $this->getFlushStorageUrl() . '\')', + 'class' => 'flush-cache-storage' + ] + ); + } } /** diff --git a/app/code/Magento/Backend/Block/Cache/Permissions.php b/app/code/Magento/Backend/Block/Cache/Permissions.php new file mode 100644 index 0000000000000..272a603145f09 --- /dev/null +++ b/app/code/Magento/Backend/Block/Cache/Permissions.php @@ -0,0 +1,62 @@ +authorization = $authorization; + } + + /** + * @return bool + */ + public function hasAccessToFlushCatalogImages() + { + return $this->authorization->isAllowed('Magento_Backend::flush_catalog_images'); + } + /** + * @return bool + */ + public function hasAccessToFlushJsCss() + { + return $this->authorization->isAllowed('Magento_Backend::flush_js_css'); + } + /** + * @return bool + */ + public function hasAccessToFlushStaticFiles() + { + return $this->authorization->isAllowed('Magento_Backend::flush_static_files'); + } + /** + * @return bool + */ + public function hasAccessToAdditionalActions() + { + return ($this->hasAccessToFlushCatalogImages() + || $this->hasAccessToFlushJsCss() + || $this->hasAccessToFlushStaticFiles()); + } +} diff --git a/app/code/Magento/Backend/Block/Dashboard/Graph.php b/app/code/Magento/Backend/Block/Dashboard/Graph.php index cecd7b8050352..301dffbdc4987 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Graph.php +++ b/app/code/Magento/Backend/Block/Dashboard/Graph.php @@ -421,6 +421,8 @@ public function getChartUrl($directUrl = true) $tmpstring = implode('|', $this->_axisLabels[$idx]); $valueBuffer[] = $indexid . ":|" . $tmpstring; + } elseif ($idx == 'y') { + $valueBuffer[] = $indexid . ":|" . implode('|', $yLabels); } $indexid++; } diff --git a/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php b/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php index 9d9409fba093b..50279786c0a5b 100644 --- a/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php +++ b/app/code/Magento/Backend/Block/Dashboard/Orders/Grid.php @@ -92,7 +92,7 @@ protected function _prepareCollection() protected function _afterLoadCollection() { foreach ($this->getCollection() as $item) { - $item->getCustomer() ?: $item->setCustomer('Guest'); + $item->getCustomer() ?: $item->setCustomer($item->getBillingAddress()->getName()); } return $this; } diff --git a/app/code/Magento/Backend/Block/GlobalSearch.php b/app/code/Magento/Backend/Block/GlobalSearch.php index f4a46283808f4..9af4e9faef761 100644 --- a/app/code/Magento/Backend/Block/GlobalSearch.php +++ b/app/code/Magento/Backend/Block/GlobalSearch.php @@ -3,19 +3,61 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Backend\Block; +use Magento\Backend\Model\GlobalSearch\SearchEntityFactory; +use Magento\Backend\Model\GlobalSearch\SearchEntity; +use Magento\Framework\App\ObjectManager; + /** * @api * @since 100.0.2 */ class GlobalSearch extends \Magento\Backend\Block\Template { + /** + * @var SearchEntityFactory + */ + private $searchEntityFactory; + /** * @var string */ protected $_template = 'Magento_Backend::system/search.phtml'; + /** + * @var array + */ + private $entityResources; + + /** + * @var array + */ + private $entityPaths; + + /** + * @param Template\Context $context + * @param array $data + * @param array $entityResources + * @param array $entityPaths + * @param SearchEntityFactory|null $searchEntityFactory + */ + public function __construct( + Template\Context $context, + array $data = [], + array $entityResources = [], + array $entityPaths = [], + SearchEntityFactory $searchEntityFactory = null + ) { + $this->entityResources = $entityResources; + $this->entityPaths = $entityPaths; + $this->searchEntityFactory = $searchEntityFactory ?: ObjectManager::getInstance() + ->get(SearchEntityFactory::class); + + parent::__construct($context, $data); + } + /** * Get components configuration * @return array @@ -34,4 +76,48 @@ public function getWidgetInitOptions() ] ]; } + + /** + * Get entities which are allowed to show. + * + * @return SearchEntity[] + */ + public function getEntitiesToShow() + { + $allowedEntityTypes = []; + $entitiesToShow = []; + + foreach ($this->entityResources as $entityType => $resource) { + if ($this->getAuthorization()->isAllowed($resource)) { + $allowedEntityTypes[] = $entityType; + } + } + + foreach ($allowedEntityTypes as $entityType) { + $url = $this->getUrlEntityType($entityType); + + $searchEntity = $this->searchEntityFactory->create(); + $searchEntity->setId('searchPreview' . $entityType); + $searchEntity->setTitle('in ' . $entityType); + $searchEntity->setUrl($url); + + $entitiesToShow[] = $searchEntity; + } + + return $entitiesToShow; + } + + /** + * Get url path by entity type. + * + * @param string $entityType + * + * @return string + */ + private function getUrlEntityType(string $entityType) + { + $urlPath = $this->entityPaths[$entityType] ?? ''; + + return $this->getUrl($urlPath); + } } diff --git a/app/code/Magento/Backend/Block/System/Store/Edit/AbstractForm.php b/app/code/Magento/Backend/Block/System/Store/Edit/AbstractForm.php index f19799d2e4939..034887c67d1ee 100644 --- a/app/code/Magento/Backend/Block/System/Store/Edit/AbstractForm.php +++ b/app/code/Magento/Backend/Block/System/Store/Edit/AbstractForm.php @@ -37,7 +37,7 @@ protected function _prepareForm() ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']] ); - $this->_prepareStoreFieldSet($form); + $this->_prepareStoreFieldset($form); $form->addField( 'store_type', diff --git a/app/code/Magento/Backend/Block/System/Store/Grid/Render/Group.php b/app/code/Magento/Backend/Block/System/Store/Grid/Render/Group.php index 59657f38465d7..3d7154eb20f92 100644 --- a/app/code/Magento/Backend/Block/System/Store/Grid/Render/Group.php +++ b/app/code/Magento/Backend/Block/System/Store/Grid/Render/Group.php @@ -27,6 +27,7 @@ public function render(\Magento\Framework\DataObject $row) $this->getUrl('adminhtml/*/editGroup', ['group_id' => $row->getGroupId()]) . '">' . $this->escapeHtml($row->getData($this->getColumn()->getIndex())) . - ''; + '
' + . '(' . __('Code') . ': ' . $row->getGroupCode() . ')'; } } diff --git a/app/code/Magento/Backend/Block/System/Store/Grid/Render/Store.php b/app/code/Magento/Backend/Block/System/Store/Grid/Render/Store.php index 23b2de683a958..9cfc8bfc52691 100644 --- a/app/code/Magento/Backend/Block/System/Store/Grid/Render/Store.php +++ b/app/code/Magento/Backend/Block/System/Store/Grid/Render/Store.php @@ -27,6 +27,7 @@ public function render(\Magento\Framework\DataObject $row) $this->getUrl('adminhtml/*/editStore', ['store_id' => $row->getStoreId()]) . '">' . $this->escapeHtml($row->getData($this->getColumn()->getIndex())) . - ''; + '
' . + '(' . __('Code') . ': ' . $row->getStoreCode() . ')'; } } diff --git a/app/code/Magento/Backend/Block/System/Store/Grid/Render/Website.php b/app/code/Magento/Backend/Block/System/Store/Grid/Render/Website.php index 913e2c903d20c..487eb4f8acfda 100644 --- a/app/code/Magento/Backend/Block/System/Store/Grid/Render/Website.php +++ b/app/code/Magento/Backend/Block/System/Store/Grid/Render/Website.php @@ -24,6 +24,7 @@ public function render(\Magento\Framework\DataObject $row) $this->getUrl('adminhtml/*/editWebsite', ['website_id' => $row->getWebsiteId()]) . '">' . $this->escapeHtml($row->getData($this->getColumn()->getIndex())) . - ''; + '
' . + '(' . __('Code') . ': ' . $row->getCode() . ')'; } } diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Date.php b/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Date.php index 40a5d92c56b6f..632603d389d21 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Date.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Date.php @@ -127,7 +127,7 @@ public function getHtml() /** * @param string|null $index - * @return string + * @return array|string|int|float|null */ public function getEscapedValue($index = null) { @@ -138,6 +138,11 @@ public function getEscapedValue($index = null) $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT) ); } + + if (is_string($value)) { + return $this->escapeHtml($value); + } + return $value; } diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Datetime.php b/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Datetime.php index 96b3471db845e..a5e4a34389671 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Datetime.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Datetime.php @@ -140,8 +140,8 @@ public function getHtml() /** * Return escaped value for calendar * - * @param string $index - * @return string + * @param string|null $index + * @return array|string|int|float|null */ public function getEscapedValue($index = null) { @@ -150,6 +150,11 @@ public function getEscapedValue($index = null) if ($value instanceof \DateTimeInterface) { return $this->_localeDate->formatDateTime($value); } + + if (is_string($value)) { + return $this->escapeHtml($value); + } + return $value; } diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Radio.php b/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Radio.php index 2cbe264c5f396..479a2b6b20293 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Radio.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Column/Filter/Radio.php @@ -31,8 +31,7 @@ public function getCondition() { if ($this->getValue()) { return $this->getColumn()->getValue(); - } else { - return [['neq' => $this->getColumn()->getValue()], ['is' => new \Zend_Db_Expr('NULL')]]; } + return [['neq' => $this->getColumn()->getValue()], ['is' => new \Zend_Db_Expr('NULL')]]; } } diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Massaction.php b/app/code/Magento/Backend/Block/Widget/Grid/Massaction.php index d9b00d2ba2503..662cbedaed8db 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Massaction.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Massaction.php @@ -3,8 +3,15 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + namespace Magento\Backend\Block\Widget\Grid; +use Magento\Backend\Block\Template\Context; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\AuthorizationInterface; +use Magento\Framework\DataObject; +use Magento\Framework\Json\EncoderInterface; + /** * Grid widget massaction default block * @@ -14,4 +21,72 @@ */ class Massaction extends \Magento\Backend\Block\Widget\Grid\Massaction\AbstractMassaction { + /** + * @var AuthorizationInterface + */ + private $authorization; + + /** + * Map bind item id to a particular acl type + * itemId => acl + * + * @var array + */ + private $restrictions = [ + 'enable' => 'Magento_Backend::toggling_cache_type', + 'disable' => 'Magento_Backend::toggling_cache_type', + 'refresh' => 'Magento_Backend::refresh_cache_type', + ]; + + /** + * Massaction constructor. + * + * @param Context $context + * @param EncoderInterface $jsonEncoder + * @param array $data + * @param AuthorizationInterface $authorization + */ + public function __construct( + Context $context, + EncoderInterface $jsonEncoder, + array $data = [], + AuthorizationInterface $authorization = null + ) { + $this->authorization = $authorization ?: ObjectManager::getInstance()->get(AuthorizationInterface::class); + + parent::__construct($context, $jsonEncoder, $data); + } + + /** + * {@inheritdoc} + * + * @param string $itemId + * @param array|DataObject $item + * + * @return $this + */ + public function addItem($itemId, $item) + { + if (!$this->isRestricted($itemId)) { + parent::addItem($itemId, $item); + } + + return $this; + } + + /** + * Check if access to action restricted + * + * @param string $itemId + * + * @return bool + */ + private function isRestricted(string $itemId): bool + { + if (!key_exists($itemId, $this->restrictions)) { + return false; + } + + return !$this->authorization->isAllowed($this->restrictions[$itemId]); + } } diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Massaction/AbstractMassaction.php b/app/code/Magento/Backend/Block/Widget/Grid/Massaction/AbstractMassaction.php index 8252ed1a1e2f8..e790cbfa69d8a 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Massaction/AbstractMassaction.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Massaction/AbstractMassaction.php @@ -222,9 +222,8 @@ public function getSelectedJson() if ($selected = $this->getRequest()->getParam($this->getFormFieldNameInternal())) { $selected = explode(',', $selected); return join(',', $selected); - } else { - return ''; } + return ''; } /** @@ -237,9 +236,8 @@ public function getSelected() if ($selected = $this->getRequest()->getParam($this->getFormFieldNameInternal())) { $selected = explode(',', $selected); return $selected; - } else { - return []; } + return []; } /** diff --git a/app/code/Magento/Backend/Block/Widget/Grid/Massaction/Extended.php b/app/code/Magento/Backend/Block/Widget/Grid/Massaction/Extended.php index 42f5e61bf5fa8..eae1a137e927d 100644 --- a/app/code/Magento/Backend/Block/Widget/Grid/Massaction/Extended.php +++ b/app/code/Magento/Backend/Block/Widget/Grid/Massaction/Extended.php @@ -218,9 +218,8 @@ public function getSelectedJson() if ($selected = $this->getRequest()->getParam($this->getFormFieldNameInternal())) { $selected = explode(',', $selected); return join(',', $selected); - } else { - return ''; } + return ''; } /** @@ -233,9 +232,8 @@ public function getSelected() if ($selected = $this->getRequest()->getParam($this->getFormFieldNameInternal())) { $selected = explode(',', $selected); return $selected; - } else { - return []; } + return []; } /** diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Auth/Login.php b/app/code/Magento/Backend/Controller/Adminhtml/Auth/Login.php index b34e4d9c84939..e1ea57f63035e 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Auth/Login.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Auth/Login.php @@ -50,9 +50,8 @@ public function execute() // redirect according to rewrite rule if ($requestUrl != $backendUrl) { return $this->getRedirect($backendUrl); - } else { - return $this->resultPageFactory->create(); } + return $this->resultPageFactory->create(); } /** diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanImages.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanImages.php index 1895bd08c464f..7a926b1c09c3e 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanImages.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanImages.php @@ -11,6 +11,13 @@ class CleanImages extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::flush_catalog_images'; + /** * Clean JS/css files cache * diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanMedia.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanMedia.php index 521cb9806a135..72f23ab65cf8a 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanMedia.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanMedia.php @@ -11,6 +11,13 @@ class CleanMedia extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::flush_js_css'; + /** * Clean JS/css files cache * diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFiles.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFiles.php index adfbf7cfe63c8..27ae2fc31e150 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFiles.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/CleanStaticFiles.php @@ -10,6 +10,13 @@ class CleanStaticFiles extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::flush_static_files'; + /** * Clean static files cache * diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushAll.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushAll.php index 2f9dc9ad6a7a5..ca89ea58fa6f3 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushAll.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushAll.php @@ -8,6 +8,13 @@ class FlushAll extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::flush_cache_storage'; + /** * Flush cache storage * diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushSystem.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushSystem.php index 0f55a59353d65..f0fed159e0f22 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushSystem.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/FlushSystem.php @@ -8,6 +8,13 @@ class FlushSystem extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::flush_magento_cache'; + /** * Flush all magento cache * diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassDisable.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassDisable.php index 204105852b9f1..2bfa937b06b77 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassDisable.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassDisable.php @@ -16,6 +16,13 @@ */ class MassDisable extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::toggling_cache_type'; + /** * @var State */ diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassEnable.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassEnable.php index 32acf47887c44..113e0f2d8961b 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassEnable.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassEnable.php @@ -16,6 +16,13 @@ */ class MassEnable extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::toggling_cache_type'; + /** * @var State */ diff --git a/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassRefresh.php b/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassRefresh.php index e18aa1555e11b..3843b030afb3d 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassRefresh.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/Cache/MassRefresh.php @@ -11,6 +11,13 @@ class MassRefresh extends \Magento\Backend\Controller\Adminhtml\Cache { + /** + * Authorization level of a basic admin session + * + * @see _isAllowed() + */ + const ADMIN_RESOURCE = 'Magento_Backend::refresh_cache_type'; + /** * Mass action for cache refresh * diff --git a/app/code/Magento/Backend/Controller/Adminhtml/System/Account/Save.php b/app/code/Magento/Backend/Controller/Adminhtml/System/Account/Save.php index c9bce1cbf3888..1b10c151a9d21 100644 --- a/app/code/Magento/Backend/Controller/Adminhtml/System/Account/Save.php +++ b/app/code/Magento/Backend/Controller/Adminhtml/System/Account/Save.php @@ -32,9 +32,8 @@ private function getSecurityCookie() { if (!($this->securityCookie instanceof SecurityCookie)) { return \Magento\Framework\App\ObjectManager::getInstance()->get(SecurityCookie::class); - } else { - return $this->securityCookie; } + return $this->securityCookie; } /** @@ -54,9 +53,9 @@ public function execute() $user = $this->_objectManager->create(\Magento\User\Model\User::class)->load($userId); $user->setId($userId) - ->setUsername($this->getRequest()->getParam('username', false)) - ->setFirstname($this->getRequest()->getParam('firstname', false)) - ->setLastname($this->getRequest()->getParam('lastname', false)) + ->setUserName($this->getRequest()->getParam('username', false)) + ->setFirstName($this->getRequest()->getParam('firstname', false)) + ->setLastName($this->getRequest()->getParam('lastname', false)) ->setEmail(strtolower($this->getRequest()->getParam('email', false))); if ($this->_objectManager->get(\Magento\Framework\Validator\Locale::class)->isValid($interfaceLocale)) { diff --git a/app/code/Magento/Backend/Model/Auth/StorageInterface.php b/app/code/Magento/Backend/Model/Auth/StorageInterface.php index 52b2b089c71e1..e643165a93317 100644 --- a/app/code/Magento/Backend/Model/Auth/StorageInterface.php +++ b/app/code/Magento/Backend/Model/Auth/StorageInterface.php @@ -23,7 +23,7 @@ interface StorageInterface public function processLogin(); /** - * Perform login specific actions + * Perform logout specific actions * * @return $this * @abstract diff --git a/app/code/Magento/Backend/Model/GlobalSearch/SearchEntity.php b/app/code/Magento/Backend/Model/GlobalSearch/SearchEntity.php new file mode 100644 index 0000000000000..18691802b9218 --- /dev/null +++ b/app/code/Magento/Backend/Model/GlobalSearch/SearchEntity.php @@ -0,0 +1,73 @@ +getData('id'); + } + + /** + * Get url. + * + * @return string + */ + public function getUrl() + { + return $this->getData('url'); + } + + /** + * Get title. + * + * @return string + */ + public function getTitle() + { + return $this->getData('title'); + } + + /** + * Set Id. + * + * @param string $value + */ + public function setId(string $value) + { + $this->setData('id', $value); + } + + /** + * Set url. + * + * @param string $value + */ + public function setUrl(string $value) + { + $this->setData('url', $value); + } + + /** + * Set title. + * + * @param string $value + */ + public function setTitle(string $value) + { + $this->setData('title', $value); + } +} diff --git a/app/code/Magento/Backend/Model/Menu/Item.php b/app/code/Magento/Backend/Model/Menu/Item.php index fe6564d24e891..67c6216cbbc06 100644 --- a/app/code/Magento/Backend/Model/Menu/Item.php +++ b/app/code/Magento/Backend/Model/Menu/Item.php @@ -467,15 +467,15 @@ public function toArray() { return [ 'parent_id' => $this->_parentId, - 'module_name' => $this->_moduleName, + 'module' => $this->_moduleName, 'sort_index' => $this->_sortIndex, - 'depends_on_config' => $this->_dependsOnConfig, + 'dependsOnConfig' => $this->_dependsOnConfig, 'id' => $this->_id, 'resource' => $this->_resource, 'path' => $this->_path, 'action' => $this->_action, - 'depends_on_module' => $this->_dependsOnModule, - 'tooltip' => $this->_tooltip, + 'dependsOnModule' => $this->_dependsOnModule, + 'toolTip' => $this->_tooltip, 'title' => $this->_title, 'target' => $this->target, 'sub_menu' => isset($this->_submenu) ? $this->_submenu->toArray() : null @@ -492,23 +492,22 @@ public function toArray() public function populateFromArray(array $data) { $this->_parentId = $this->_getArgument($data, 'parent_id'); - $this->_moduleName = $this->_getArgument($data, 'module_name', 'Magento_Backend'); + $this->_moduleName = $this->_getArgument($data, 'module', 'Magento_Backend'); $this->_sortIndex = $this->_getArgument($data, 'sort_index'); - $this->_dependsOnConfig = $this->_getArgument($data, 'depends_on_config'); + $this->_dependsOnConfig = $this->_getArgument($data, 'dependsOnConfig'); $this->_id = $this->_getArgument($data, 'id'); $this->_resource = $this->_getArgument($data, 'resource'); $this->_path = $this->_getArgument($data, 'path', ''); $this->_action = $this->_getArgument($data, 'action'); - $this->_dependsOnModule = $this->_getArgument($data, 'depends_on_module'); - $this->_tooltip = $this->_getArgument($data, 'tooltip', ''); + $this->_dependsOnModule = $this->_getArgument($data, 'dependsOnModule'); + $this->_tooltip = $this->_getArgument($data, 'toolTip'); $this->_title = $this->_getArgument($data, 'title'); $this->target = $this->_getArgument($data, 'target'); + $this->_submenu = null; if (isset($data['sub_menu'])) { $menu = $this->_menuFactory->create(); $menu->populateFromArray($data['sub_menu']); $this->_submenu = $menu; - } else { - $this->_submenu = null; } } } diff --git a/app/code/Magento/Backend/Model/Url.php b/app/code/Magento/Backend/Model/Url.php index 48b443fe7ffd3..cf895268bcb7d 100644 --- a/app/code/Magento/Backend/Model/Url.php +++ b/app/code/Magento/Backend/Model/Url.php @@ -202,7 +202,7 @@ public function getUrl($routePath = null, $routeParams = null) } $cacheSecretKey = false; - if (is_array($routeParams) && isset($routeParams['_cache_secret_key'])) { + if (isset($routeParams['_cache_secret_key'])) { unset($routeParams['_cache_secret_key']); $cacheSecretKey = true; } @@ -210,25 +210,22 @@ public function getUrl($routePath = null, $routeParams = null) if (!$this->useSecretKey()) { return $result; } + $this->_setRoutePath($routePath); $routeName = $this->_getRouteName('*'); $controllerName = $this->_getControllerName(self::DEFAULT_CONTROLLER_NAME); $actionName = $this->_getActionName(self::DEFAULT_ACTION_NAME); - if ($cacheSecretKey) { - $secret = [self::SECRET_KEY_PARAM_NAME => "\${$routeName}/{$controllerName}/{$actionName}\$"]; - } else { - $secret = [ - self::SECRET_KEY_PARAM_NAME => $this->getSecretKey($routeName, $controllerName, $actionName), - ]; - } - if (is_array($routeParams)) { - $routeParams = array_merge($secret, $routeParams); - } else { - $routeParams = $secret; - } - if (is_array($this->_getRouteParams())) { - $routeParams = array_merge($this->_getRouteParams(), $routeParams); + + if (!isset($routeParams[self::SECRET_KEY_PARAM_NAME])) { + if (!is_array($routeParams)) { + $routeParams = []; + } + $secretKey = $cacheSecretKey + ? "\${$routeName}/{$controllerName}/{$actionName}\$" + : $this->getSecretKey($routeName, $controllerName, $actionName); + $routeParams[self::SECRET_KEY_PARAM_NAME] = $secretKey; } + return parent::getUrl("{$routeName}/{$controllerName}/{$actionName}", $routeParams); } diff --git a/app/code/Magento/Backend/Model/Widget/Grid/Parser.php b/app/code/Magento/Backend/Model/Widget/Grid/Parser.php index e2b77fb471acd..fbed7149aa565 100644 --- a/app/code/Magento/Backend/Model/Widget/Grid/Parser.php +++ b/app/code/Magento/Backend/Model/Widget/Grid/Parser.php @@ -30,8 +30,9 @@ public function parseExpression($expression) $expression = trim($expression); foreach ($this->_operations as $operation) { $splittedExpr = preg_split('/\\' . $operation . '/', $expression, -1, PREG_SPLIT_DELIM_CAPTURE); - if (count($splittedExpr) > 1) { - for ($i = 0; $i < count($splittedExpr); $i++) { + $count = count($splittedExpr); + if ($count > 1) { + for ($i = 0; $i < $count; $i++) { $stack = array_merge($stack, $this->parseExpression($splittedExpr[$i])); if ($i > 0) { $stack[] = $operation; diff --git a/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php b/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php new file mode 100644 index 0000000000000..6975b8ac092ad --- /dev/null +++ b/app/code/Magento/Backend/Test/Unit/Block/Cache/PermissionsTest.php @@ -0,0 +1,76 @@ +objectManager = new ObjectManager($this); + + $this->mockAuthorization = $this->getMockBuilder(Authorization::class) + ->disableOriginalConstructor() + ->setMethods(['isAllowed']) + ->getMock(); + + $this->permissions = new Permissions($this->mockAuthorization); + } + + public function testHasAccessToFlushCatalogImages() + { + $this->mockAuthorization->expects($this->atLeastOnce()) + ->method('isAllowed') + ->with('Magento_Backend::flush_catalog_images') + ->willReturn(true); + + $this->assertTrue($this->permissions->hasAccessToFlushCatalogImages()); + } + + public function testHasAccessToFlushJsCss() + { + $this->mockAuthorization->expects($this->atLeastOnce()) + ->method('isAllowed') + ->with('Magento_Backend::flush_js_css') + ->willReturn(true); + + $this->assertTrue($this->permissions->hasAccessToFlushJsCss()); + } + + public function testHasAccessToFlushStaticFiles() + { + $this->mockAuthorization->expects($this->atLeastOnce()) + ->method('isAllowed') + ->with('Magento_Backend::flush_static_files') + ->willReturn(true); + + $this->assertTrue($this->permissions->hasAccessToFlushStaticFiles()); + } +} diff --git a/app/code/Magento/Backend/Test/Unit/Block/GlobalSearchTest.php b/app/code/Magento/Backend/Test/Unit/Block/GlobalSearchTest.php new file mode 100644 index 0000000000000..0010ffad87524 --- /dev/null +++ b/app/code/Magento/Backend/Test/Unit/Block/GlobalSearchTest.php @@ -0,0 +1,123 @@ + \Magento\Catalog\Controller\Adminhtml\Product::ADMIN_RESOURCE, + 'Orders' => \Magento\Sales\Controller\Adminhtml\Order::ADMIN_RESOURCE, + 'Customers' => \Magento\Customer\Controller\Adminhtml\Index::ADMIN_RESOURCE, + 'Pages' => \Magento\Cms\Controller\Adminhtml\Page\Index::ADMIN_RESOURCE, + ]; + + /** + * @var array + */ + private $entityPaths = [ + 'Products' => 'catalog/product/index/', + 'Orders' => 'sales/order/index/', + 'Customers' => 'customer/index/index', + 'Pages' => 'cms/page/index/', + ]; + + protected function setUp() + { + $objectManager = new ObjectManager($this); + + $this->authorization = $this->createMock(\Magento\Framework\AuthorizationInterface::class); + $this->urlBuilder = $this->createMock(\Magento\Framework\UrlInterface::class); + $context = $this->createMock(\Magento\Backend\Block\Template\Context::class); + + $context->expects($this->atLeastOnce())->method('getAuthorization')->willReturn($this->authorization); + $context->expects($this->atLeastOnce())->method('getUrlBuilder')->willReturn($this->urlBuilder); + + $this->searchEntityFactory = $this->createMock(\Magento\Backend\Model\GlobalSearch\SearchEntityFactory::class); + + $this->globalSearch = $objectManager->getObject( + GlobalSearch::class, + [ + 'context' => $context, + 'searchEntityFactory' => $this->searchEntityFactory, + 'entityResources' => $this->entityResources, + 'entityPaths' => $this->entityPaths, + ] + ); + } + + /** + * @param array $results + * @param int $expectedEntitiesQty + * + * @dataProvider getEntitiesToShowDataProvider + */ + public function testGetEntitiesToShow(array $results, int $expectedEntitiesQty) + { + $searchEntity = $this->createMock(SearchEntity::class); + + $this->authorization->expects($this->exactly(count($results)))->method('isAllowed') + ->willReturnOnConsecutiveCalls($results[0], $results[1], $results[2], $results[3]); + $this->urlBuilder->expects($this->exactly($expectedEntitiesQty)) + ->method('getUrl')->willReturn('some/url/is/here'); + $this->searchEntityFactory->expects($this->exactly($expectedEntitiesQty)) + ->method('create')->willReturn($searchEntity); + + $searchEntity->expects($this->exactly($expectedEntitiesQty))->method('setId'); + $searchEntity->expects($this->exactly($expectedEntitiesQty))->method('setTitle'); + $searchEntity->expects($this->exactly($expectedEntitiesQty))->method('setUrl'); + + $this->assertSame($expectedEntitiesQty, count($this->globalSearch->getEntitiesToShow())); + } + + public function getEntitiesToShowDataProvider() + { + return [ + [ + [true, false, true, false], + 2, + ], + [ + [true, true, true, true], + 4, + ], + [ + [false, false, false, false], + 0, + ], + ]; + } +} diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php index be171a8ed40bf..df242a4cf6129 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnSetTest.php @@ -117,7 +117,7 @@ public function testSetFilterTypePropagatesFilterTypeToColumns() public function testGetRowUrlIfUrlPathNotSet() { - $this->assertEquals('#', $this->_block->getRowUrl(new \StdClass())); + $this->assertEquals('#', $this->_block->getRowUrl(new \stdClass())); } public function testGetRowUrl() diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php index da13af87b71ea..c5c56fd75fbe7 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/ColumnTest.php @@ -351,7 +351,7 @@ public function testSetGetGrid() $this->_block->setFilter('StdClass'); - $grid = new \StdClass(); + $grid = new \stdClass(); $this->_block->setGrid($grid); $this->assertEquals($grid, $this->_block->getGrid()); } diff --git a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php index bb389a996e1ed..29ce448a04ecb 100644 --- a/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php +++ b/app/code/Magento/Backend/Test/Unit/Block/Widget/Grid/MassactionTest.php @@ -10,6 +10,7 @@ namespace Magento\Backend\Test\Unit\Block\Widget\Grid; use Magento\Backend\Block\Widget\Grid\Massaction\VisibilityCheckerInterface as VisibilityChecker; +use Magento\Framework\Authorization; class MassactionTest extends \PHPUnit\Framework\TestCase { @@ -43,6 +44,11 @@ class MassactionTest extends \PHPUnit\Framework\TestCase */ protected $_requestMock; + /** + * @var Authorization|\PHPUnit_Framework_MockObject_MockObject + */ + protected $_authorizationMock; + /** * @var VisibilityChecker|\PHPUnit_Framework_MockObject_MockObject */ @@ -86,11 +92,17 @@ protected function setUp() $this->visibilityCheckerMock = $this->getMockBuilder(VisibilityChecker::class) ->getMockForAbstractClass(); + $this->_authorizationMock = $this->getMockBuilder(Authorization::class) + ->disableOriginalConstructor() + ->setMethods(['isAllowed']) + ->getMock(); + $arguments = [ 'layout' => $this->_layoutMock, 'request' => $this->_requestMock, 'urlBuilder' => $this->_urlModelMock, - 'data' => ['massaction_id_field' => 'test_id', 'massaction_id_filter' => 'test_id'] + 'data' => ['massaction_id_field' => 'test_id', 'massaction_id_filter' => 'test_id'], + 'authorization' => $this->_authorizationMock, ]; $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); @@ -145,6 +157,10 @@ public function testItemsProcessing($itemId, $item, $expectedItem) ->method('getUrl') ->willReturnMap($urlReturnValueMap); + $this->_authorizationMock->expects($this->any()) + ->method('isAllowed') + ->willReturn(true); + $this->_block->addItem($itemId, $item); $this->assertEquals(1, $this->_block->getCount()); @@ -184,6 +200,28 @@ public function itemsProcessingDataProvider() "id" => 'test_id2', ] ) + ], + [ + 'enabled', + new \Magento\Framework\DataObject(["label" => "Test Item Enabled", "url" => "*/*/test2"]), + new \Magento\Framework\DataObject( + [ + "label" => "Test Item Enabled", + "url" => "http://localhost/index.php/backend/admin/test/test2", + "id" => 'enabled', + ] + ) + ], + [ + 'refresh', + new \Magento\Framework\DataObject(["label" => "Test Item Refresh", "url" => "*/*/test2"]), + new \Magento\Framework\DataObject( + [ + "label" => "Test Item Refresh", + "url" => "http://localhost/index.php/backend/admin/test/test2", + "id" => 'refresh', + ] + ) ] ]; } @@ -237,7 +275,7 @@ public function testGetGridIdsJsonWithoutUseSelectAll() public function testGetGridIdsJsonWithUseSelectAll(array $items, $result) { $this->_block->setUseSelectAll(true); - + if ($this->_block->getMassactionIdField()) { $massActionIdField = $this->_block->getMassactionIdField(); } else { @@ -290,14 +328,20 @@ public function dataProviderGetGridIdsJsonWithUseSelectAll() * @param int $count * @param bool $withVisibilityChecker * @param bool $isVisible + * @param bool $isAllowed + * * @dataProvider addItemDataProvider */ - public function testAddItem($itemId, $item, $count, $withVisibilityChecker, $isVisible) + public function testAddItem($itemId, $item, $count, $withVisibilityChecker, $isVisible, $isAllowed) { $this->visibilityCheckerMock->expects($this->any()) ->method('isVisible') ->willReturn($isVisible); + $this->_authorizationMock->expects($this->any()) + ->method('isAllowed') + ->willReturn($isAllowed); + if ($withVisibilityChecker) { $item['visible'] = $this->visibilityCheckerMock; } @@ -311,7 +355,7 @@ public function testAddItem($itemId, $item, $count, $withVisibilityChecker, $isV ->willReturnMap($urlReturnValueMap); $this->_block->addItem($itemId, $item); - $this->assertEquals($count, $this->_block->getCount()); + $this->assertEquals($count, $this->_block->getCount(), $itemId); } /** @@ -325,7 +369,8 @@ public function addItemDataProvider() 'item' => ['label' => 'Test 1', 'url' => '*/*/test1'], 'count' => 1, 'withVisibilityChecker' => false, - '$isVisible' => false, + 'isVisible' => false, + 'isAllowed' => true, ], [ 'itemId' => 'test2', @@ -333,21 +378,56 @@ public function addItemDataProvider() 'count' => 1, 'withVisibilityChecker' => false, 'isVisible' => true, + 'isAllowed' => true, ], [ - 'itemId' => 'test1', - 'item' => ['label' => 'Test 1. Hide', 'url' => '*/*/test1'], + 'itemId' => 'test3', + 'item' => ['label' => 'Test 3. Hide', 'url' => '*/*/test3'], 'count' => 0, 'withVisibilityChecker' => true, 'isVisible' => false, + 'isAllowed' => true, ], [ - 'itemId' => 'test2', - 'item' => ['label' => 'Test 2. Does not hide', 'url' => '*/*/test2'], + 'itemId' => 'test4', + 'item' => ['label' => 'Test 4. Does not hide', 'url' => '*/*/test4'], 'count' => 1, 'withVisibilityChecker' => true, 'isVisible' => true, - ] + 'isAllowed' => true, + ], + [ + 'itemId' => 'enable', + 'item' => ['label' => 'Test 5. Not restricted', 'url' => '*/*/test5'], + 'count' => 1, + 'withVisibilityChecker' => true, + 'isVisible' => true, + 'isAllowed' => true, + ], + [ + 'itemId' => 'enable', + 'item' => ['label' => 'Test 5. restricted', 'url' => '*/*/test5'], + 'count' => 0, + 'withVisibilityChecker' => true, + 'isVisible' => true, + 'isAllowed' => false, + ], + [ + 'itemId' => 'refresh', + 'item' => ['label' => 'Test 6. Not Restricted', 'url' => '*/*/test6'], + 'count' => 1, + 'withVisibilityChecker' => true, + 'isVisible' => true, + 'isAllowed' => true, + ], + [ + 'itemId' => 'refresh', + 'item' => ['label' => 'Test 6. Restricted', 'url' => '*/*/test6'], + 'count' => 0, + 'withVisibilityChecker' => true, + 'isVisible' => true, + 'isAllowed' => false, + ], ]; } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php b/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php index 31a13191750a3..2f0102ffd410d 100755 --- a/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Config/SessionLifetime/BackendModelTest.php @@ -20,7 +20,8 @@ public function testBeforeSave($value, $errorMessage = null) \Magento\Backend\Model\Config\SessionLifetime\BackendModel::class ); if ($errorMessage !== null) { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class, $errorMessage); + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage($errorMessage); } $model->setValue($value); $object = $model->beforeSave(); diff --git a/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php b/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php index 74368537c39c7..ad172cbfbd165 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Menu/ItemTest.php @@ -56,9 +56,9 @@ class ItemTest extends \PHPUnit\Framework\TestCase 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ]; protected function setUp() diff --git a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php index b0c74461980a2..82f07e264b963 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php +++ b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_constructor_data.php @@ -12,21 +12,21 @@ 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], [ 'parent_id' => null, - 'module_name' => 'Magento_Backend', + 'module' => 'Magento_Backend', 'sort_index' => null, - 'depends_on_config' => 'system/config/isEnabled', + 'dependsOnConfig' => 'system/config/isEnabled', 'id' => 'item', 'resource' => 'Magento_Config::config', 'path' => '', 'action' => '/system/config', - 'depends_on_module' => 'Magento_Backend', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'toolTip' => 'Item tooltip', 'title' => 'Item Title', 'sub_menu' => null, 'target' => null @@ -38,43 +38,43 @@ 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => '5', 'resource' => null, 'path' => null, 'action' => null, - 'depends_on_module' => null, - 'tooltip' => null, + 'dependsOnModule' => null, + 'toolTip' => null, 'title' => null, 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], ], [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => '5', 'resource' => null, 'path' => '', 'action' => null, - 'depends_on_module' => null, - 'tooltip' => '', + 'dependsOnModule' => null, + 'toolTip' => '', 'title' => null, 'sub_menu' => ['submenuArray'], 'target' => null @@ -83,51 +83,51 @@ 'data with submenu to constructor' => [ [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => '5', 'resource' => null, 'path' => null, 'action' => null, - 'depends_on_module' => null, - 'tooltip' => null, + 'dependsOnModule' => null, + 'toolTip' => null, 'title' => null, 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], ], [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], ], [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => null, 'resource' => null, 'path' => '', 'action' => null, - 'depends_on_module' => null, - 'tooltip' => '', + 'dependsOnModule' => null, + 'toolTip' => '', 'title' => null, 'sub_menu' => ['submenuArray'], 'target' => null diff --git a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php index 30a43b0158ae3..b1a310d7d440b 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php +++ b/app/code/Magento/Backend/Test/Unit/Model/_files/menu_item_data.php @@ -11,22 +11,22 @@ 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', 'sub_menu' => null, ], [ 'parent_id' => null, - 'module_name' => 'Magento_Backend', + 'module' => 'Magento_Backend', 'sort_index' => null, - 'depends_on_config' => 'system/config/isEnabled', + 'dependsOnConfig' => 'system/config/isEnabled', 'id' => 'item', 'resource' => 'Magento_Config::config', 'path' => '', 'action' => '/system/config', - 'depends_on_module' => 'Magento_Backend', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'toolTip' => 'Item tooltip', 'title' => 'Item Title', 'sub_menu' => null, 'target' => null @@ -35,46 +35,46 @@ 'with submenu' => [ [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => '5', 'resource' => null, 'path' => null, 'action' => null, - 'depends_on_module' => null, - 'tooltip' => null, + 'dependsOnModule' => null, + 'toolTip' => null, 'title' => null, 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], ], [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => '5', 'resource' => null, 'path' => null, 'action' => null, - 'depends_on_module' => null, - 'tooltip' => '', + 'dependsOnModule' => null, + 'toolTip' => '', 'title' => null, 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], 'target' => null ] @@ -82,38 +82,38 @@ 'small set of data' => [ [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], ], [ 'parent_id' => '1', - 'module_name' => 'Magento_Module1', + 'module' => 'Magento_Module1', 'sort_index' => '50', - 'depends_on_config' => null, + 'dependsOnConfig' => null, 'id' => null, 'resource' => null, 'path' => '', 'action' => null, - 'depends_on_module' => null, - 'tooltip' => '', + 'dependsOnModule' => null, + 'toolTip' => '', 'title' => null, 'sub_menu' => [ 'id' => 'item', 'title' => 'Item Title', 'action' => '/system/config', 'resource' => 'Magento_Config::config', - 'depends_on_module' => 'Magento_Backend', - 'depends_on_config' => 'system/config/isEnabled', - 'tooltip' => 'Item tooltip', + 'dependsOnModule' => 'Magento_Backend', + 'dependsOnConfig' => 'system/config/isEnabled', + 'toolTip' => 'Item tooltip', ], 'target' => null ] diff --git a/app/code/Magento/Backend/composer.json b/app/code/Magento/Backend/composer.json index 036f0b4d54a46..8d8be79f1c916 100644 --- a/app/code/Magento/Backend/composer.json +++ b/app/code/Magento/Backend/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-backend", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-store": "100.2.*", "magento/module-directory": "100.2.*", "magento/module-developer": "100.2.*", @@ -24,7 +24,7 @@ "magento/module-theme": "100.2.*" }, "type": "magento2-module", - "version": "100.2.0", + "version": "100.2.3", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Backend/etc/acl.xml b/app/code/Magento/Backend/etc/acl.xml index af4ab5856e94c..cf9471e75bed9 100644 --- a/app/code/Magento/Backend/etc/acl.xml +++ b/app/code/Magento/Backend/etc/acl.xml @@ -38,7 +38,21 @@ - + + + + + + + + + + + + + + + diff --git a/app/code/Magento/Backend/etc/adminhtml/di.xml b/app/code/Magento/Backend/etc/adminhtml/di.xml index 97a39139411c0..de8286e7f3ecc 100644 --- a/app/code/Magento/Backend/etc/adminhtml/di.xml +++ b/app/code/Magento/Backend/etc/adminhtml/di.xml @@ -145,6 +145,9 @@ Magento\Config\Model\Config\Structure\ElementVisibilityInterface::HIDDEN Magento\Config\Model\Config\Structure\ElementVisibilityInterface::DISABLED + + + @@ -152,4 +155,20 @@ Magento\Backend\Block\Template + + + + Magento_Catalog::products + Magento_Sales::sales_order + Magento_Customer::manage + Magento_Cms::page + + + catalog/product/index/ + sales/order/index/ + customer/index/index + cms/page/index/ + + + diff --git a/app/code/Magento/Backend/etc/adminhtml/system.xml b/app/code/Magento/Backend/etc/adminhtml/system.xml index 27fd16cc920dc..3a58ef9f63e8d 100644 --- a/app/code/Magento/Backend/etc/adminhtml/system.xml +++ b/app/code/Magento/Backend/etc/adminhtml/system.xml @@ -215,7 +215,7 @@ Magento\Directory\Model\Config\Source\Country - + Magento\Directory\Model\Config\Source\Country @@ -409,7 +409,7 @@ general Magento_Config::web - + @@ -419,7 +419,7 @@ Warning! When using Store Code in URLs, in some cases system may not work properly if URLs without Store Codes are specified in the third party services (e.g. PayPal etc.).]]> - + Magento\Config\Model\Config\Source\Web\Redirect I.e. redirect from http://example.com/store/ to http://www.example.com/store/ diff --git a/app/code/Magento/Backend/i18n/en_US.csv b/app/code/Magento/Backend/i18n/en_US.csv index 2730d4d92835b..aa28a670b9205 100644 --- a/app/code/Magento/Backend/i18n/en_US.csv +++ b/app/code/Magento/Backend/i18n/en_US.csv @@ -214,10 +214,13 @@ YTD,YTD "Admin session lifetime must be greater than or equal to 60 seconds","Admin session lifetime must be greater than or equal to 60 seconds" Order,Order "Order #%1","Order #%1" -"Access denied","Access denied" -"Please try to sign out and sign in again.","Please try to sign out and sign in again." -"If you continue to receive this message, please contact the store owner.","If you continue to receive this message, please contact the store owner." "You need more permissions to access this.","You need more permissions to access this." +"Sorry, you need permissions to view this content.","Sorry, you need permissions to view this content." +"Next steps","Next steps" +"If you think this is an error, try signing out and signing in again.","If you think this is an error, try signing out and signing in again." +"Contact a system administrator or store owner to gain permissions.","Contact a system administrator or store owner to gain permissions." +"Return to","Return to" +"previous page","previous page" "Welcome, please sign in","Welcome, please sign in" Username,Username "user name","user name" @@ -458,3 +461,7 @@ Pagination,Pagination "Alternative text for the next pages link in the pagination menu. If empty, default arrow image is used.","Alternative text for the next pages link in the pagination menu. If empty, default arrow image is used." "Anchor Text for Next","Anchor Text for Next" "Theme Name","Theme Name" +"In Products","In Products" +"In Orders","In Orders" +"In Customers","In Customers" +"In Pages","In Pages" diff --git a/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_cache_index.xml b/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_cache_index.xml index ab5ddc414b51f..4bbe70b6cdb92 100644 --- a/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_cache_index.xml +++ b/app/code/Magento/Backend/view/adminhtml/layout/adminhtml_cache_index.xml @@ -11,7 +11,11 @@ - + + + Magento\Backend\Block\Cache\Permissions + + diff --git a/app/code/Magento/Backend/view/adminhtml/templates/admin/access_denied.phtml b/app/code/Magento/Backend/view/adminhtml/templates/admin/access_denied.phtml index 852ecd5a07962..843328fbf17d7 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/admin/access_denied.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/admin/access_denied.phtml @@ -12,12 +12,23 @@ * @see \Magento\Backend\Block\Denied */ ?> -

-hasAvailableResources()): ?> -

-
- -

- -

- +
+
+

escapeHtml(__('Sorry, you need permissions to view this content.')) ?>

+ escapeHtml(__('Next steps')) ?> + +
diff --git a/app/code/Magento/Backend/view/adminhtml/templates/page/header.phtml b/app/code/Magento/Backend/view/adminhtml/templates/page/header.phtml index 40b7173f47417..8feccc9cf1b8f 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/page/header.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/page/header.phtml @@ -29,7 +29,7 @@ data-mage-init='{"dropdown":{}}' data-toggle="dropdown"> - +
    @@ -39,7 +39,7 @@ href="getUrl('adminhtml/system_account/index') ?>" getUiId('user', 'account', 'settings') ?> title="escapeHtml(__('Account Setting')) ?>"> - (escapeHtml($block->getUser()->getUsername()) ?>) + (escapeHtml($block->getUser()->getUserName()) ?>) diff --git a/app/code/Magento/Backend/view/adminhtml/templates/page/report.phtml b/app/code/Magento/Backend/view/adminhtml/templates/page/report.phtml index 3a3dbd99bfba9..4ef6d378cc4a4 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/page/report.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/page/report.phtml @@ -8,5 +8,7 @@ ?> getBugreportUrl()): ?> - + + + diff --git a/app/code/Magento/Backend/view/adminhtml/templates/system/cache/additional.phtml b/app/code/Magento/Backend/view/adminhtml/templates/system/cache/additional.phtml index 84bbc4ea601ef..8e30afdf51f7f 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/system/cache/additional.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/system/cache/additional.phtml @@ -5,34 +5,39 @@ */ // @codingStandardsIgnoreFile + +/** @var \Magento\Backend\Block\Cache\Permissions|null $permissions */ +$permissions = $block->getData('permissions'); ?> -
    -

    - -

    -

    - - -

    -

    - - -

    - isInProductionMode()): - ?> -

    - - -

    - - getChildHtml() ?> -
    +hasAccessToAdditionalActions()): ?> +
    + hasAccessToFlushCatalogImages()): ?> +

    + escapeHtml(__('Additional Cache Management')); ?> +

    +

    + + escapeHtml(__('Pregenerated product images files')); ?> +

    + + hasAccessToFlushJsCss()): ?> +

    + + escapeHtml(__('Themes JavaScript and CSS files combined to one file')) ?> +

    + + isInProductionMode() && $permissions->hasAccessToFlushStaticFiles()): ?> +

    + + escapeHtml(__('Preprocessed view files and static files')); ?> +

    + + getChildHtml() ?> +
    + diff --git a/app/code/Magento/Backend/view/adminhtml/templates/system/search.phtml b/app/code/Magento/Backend/view/adminhtml/templates/system/search.phtml index a528133b2bc3a..3c65c0358eb57 100644 --- a/app/code/Magento/Backend/view/adminhtml/templates/system/search.phtml +++ b/app/code/Magento/Backend/view/adminhtml/templates/system/search.phtml @@ -27,18 +27,15 @@ - diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/category/tree.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/category/tree.phtml index a3cf4b478ad3b..9865589556e7b 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/category/tree.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/category/tree.phtml @@ -59,6 +59,8 @@ } }; + var treeRoot = '#tree-div'; + /** * Fix ext compatibility with prototype 1.6 */ @@ -491,7 +493,7 @@ if (data.error) { reRenderTree(); } else { - $(obj.tree.container.dom).trigger('categoryMove.tree'); + $(treeRoot).trigger('categoryMove.tree'); } $('.page-main-actions').next('.messages').remove(); $('.page-main-actions').next('#messages').remove(); diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/js.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/js.phtml index 69bc847c30f46..8a5f1919f78be 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/js.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/js.phtml @@ -196,9 +196,11 @@ function switchDefaultValueField() helper('Magento\Catalog\Helper\Data')->getAttributeHiddenFields() as $type => $fields): ?> case '': + var isFrontTabHidden = false; getFrontTab().hide(); + isFrontTabHidden = true; defaultValueTextVisibility = defaultValueTextareaVisibility = @@ -210,6 +212,10 @@ function switchDefaultValueField() setRowVisibility('', false); + + if (!isFrontTabHidden){ + getFrontTab().show(); + } break; diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/options.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/options.phtml index a0041d2e02988..f812a27f87ad9 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/options.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/attribute/options.phtml @@ -57,7 +57,7 @@ $stores = $block->getStoresSortedBySortOrder(); - - diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/view/form.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/view/form.phtml index c8c915a3140da..4d7005dfe6cb2 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/view/form.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/view/form.phtml @@ -16,7 +16,7 @@ getProduct(); ?>
    -
    getOptions()): ?> enctype="multipart/form-data"> diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/view/opengraph/general.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/view/opengraph/general.phtml index b1e46776af465..a2b91a5eeb99f 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/view/opengraph/general.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/view/opengraph/general.phtml @@ -9,7 +9,7 @@ /** @var $block \Magento\Catalog\Block\Product\View */ ?> - + diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/view/options/type/text.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/view/options/type/text.phtml index 79dc8591fd724..11aedc33c2d42 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/view/options/type/text.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/view/options/type/text.phtml @@ -29,6 +29,7 @@ $class = ($_option->getIsRequire()) ? ' required' : ''; if ($_option->getMaxCharacters()) { $_textValidate['maxlength'] = $_option->getMaxCharacters(); } + $_textValidate['validate-no-utf8mb4-characters'] = true; ?> getIsRequire()) ? ' required' : ''; if ($_option->getMaxCharacters()) { $_textAreaValidate['maxlength'] = $_option->getMaxCharacters(); } + $_textAreaValidate['validate-no-utf8mb4-characters'] = true; ?> \n
    \n
    \n"; -},"7":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n
    \n
    \n
    \n"; -},"9":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.isFile : depth0),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.program(10, data, 0),"data":data})) != null ? stack1 : ""); -},"10":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = (helpers.renderTextParam || (depth0 && depth0.renderTextParam) || helpers.helperMissing).call(depth0 != null ? depth0 : {},depth0,{"name":"renderTextParam","hash":{},"fn":container.program(11, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"11":function(container,depth0,helpers,partials,data) { - return ""; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isBody : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(9, data, 0),"data":data})) != null ? stack1 : "") - + "\n\n" - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.description : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.paramType : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n \n\n"; -},"useData":true}); -templates['param_list'] = template({"1":function(container,depth0,helpers,partials,data) { - return " required"; -},"3":function(container,depth0,helpers,partials,data) { - return " multiple=\"multiple\""; -},"5":function(container,depth0,helpers,partials,data) { - return " required "; -},"7":function(container,depth0,helpers,partials,data) { - var stack1; - - return " \n"; -},"8":function(container,depth0,helpers,partials,data) { - return " selected=\"\" "; -},"10":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n \n\n"; -},"11":function(container,depth0,helpers,partials,data) { - return " selected=\"\" "; -},"13":function(container,depth0,helpers,partials,data) { - return " (default) "; -},"15":function(container,depth0,helpers,partials,data) { - return ""; -},"17":function(container,depth0,helpers,partials,data) { - return ""; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n\n \n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.required : depth0),{"name":"if","hash":{},"fn":container.program(15, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = ((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"description","hash":{},"data":data}) : helper))) != null ? stack1 : "") - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.required : depth0),{"name":"if","hash":{},"fn":container.program(17, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.paramType : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n"; -},"useData":true}); -templates['param_readonly'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n
    \n"; -},"3":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0["default"] : depth0),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.program(6, data, 0),"data":data})) != null ? stack1 : ""); -},"4":function(container,depth0,helpers,partials,data) { - var stack1; - - return " " - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || helpers.helperMissing).call(depth0 != null ? depth0 : {},(depth0 != null ? depth0["default"] : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n"; -},"6":function(container,depth0,helpers,partials,data) { - return " (empty)\n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isBody : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(3, data, 0),"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.description : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.paramType : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n"; -},"useData":true}); -templates['param_readonly_required'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n"; -},"3":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0["default"] : depth0),{"name":"if","hash":{},"fn":container.program(4, data, 0),"inverse":container.program(6, data, 0),"data":data})) != null ? stack1 : ""); -},"4":function(container,depth0,helpers,partials,data) { - var stack1; - - return " " - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || helpers.helperMissing).call(depth0 != null ? depth0 : {},(depth0 != null ? depth0["default"] : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n"; -},"6":function(container,depth0,helpers,partials,data) { - return " (empty)\n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isBody : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(3, data, 0),"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.description : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.paramType : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n"; -},"useData":true}); -templates['param_required'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.isFile : depth0),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.program(4, data, 0),"data":data})) != null ? stack1 : ""); -},"2":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n"; -},"4":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0["default"] : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : ""); -},"5":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "
    \n \n
    \n
    \n"; -},"7":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n
    \n
    \n
    \n"; -},"9":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers["if"].call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.isFile : depth0),{"name":"if","hash":{},"fn":container.program(10, data, 0),"inverse":container.program(12, data, 0),"data":data})) != null ? stack1 : ""); -},"10":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n"; -},"12":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = (helpers.renderTextParam || (depth0 && depth0.renderTextParam) || helpers.helperMissing).call(depth0 != null ? depth0 : {},depth0,{"name":"renderTextParam","hash":{},"fn":container.program(13, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"13":function(container,depth0,helpers,partials,data) { - return ""; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n\n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isBody : depth0),{"name":"if","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(9, data, 0),"data":data})) != null ? stack1 : "") - + "\n\n " - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.description : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.paramType : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n"; -},"useData":true}); -templates['parameter_content_type'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.consumes : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"2":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n"; -},"4":function(container,depth0,helpers,partials,data) { - return " \n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "\n\n"; -},"useData":true}); -templates['popup'] = template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var helper; - - return "
    \n
    " - + container.escapeExpression(((helper = (helper = helpers.title || (depth0 != null ? depth0.title : depth0)) != null ? helper : helpers.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : {},{"name":"title","hash":{},"data":data}) : helper))) - + "
    \n
    \n

    \n
    \n \n
    \n
    \n
    "; -},"useData":true}); -templates['resource'] = template({"1":function(container,depth0,helpers,partials,data) { - return " : "; -},"3":function(container,depth0,helpers,partials,data) { - var stack1; - - return "
  • \n Raw\n
  • \n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, helper, options, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing, buffer = - "
    \n

    \n " - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.name : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + " "; - stack1 = ((helper = (helper = helpers.summary || (depth0 != null ? depth0.summary : depth0)) != null ? helper : alias2),(options={"name":"summary","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data}),(typeof helper === "function" ? helper.call(alias1,options) : helper)); - if (!helpers.summary) { stack1 = helpers.blockHelperMissing.call(depth0,stack1,options)} - if (stack1 != null) { buffer += stack1; } - return buffer + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.summary : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n

    \n
      \n
    • \n Show/Hide\n
    • \n
    • \n \n List Operations\n \n
    • \n
    • \n \n Expand Operations\n \n
    • \n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.url : depth0),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "
    \n
    \n\n"; -},"useData":true}); -templates['response_content_type'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.produces : depth0),{"name":"each","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); -},"2":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n"; -},"4":function(container,depth0,helpers,partials,data) { - return " \n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; - - return "\n\n"; -},"useData":true}); -templates['signature'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}; - - return "\n
    \n\n
    \n\n
    \n
    \n " - + container.escapeExpression((helpers.sanitize || (depth0 && depth0.sanitize) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.signature : depth0),{"name":"sanitize","hash":{},"data":data})) - + "\n
    \n\n
    \n" - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.sampleJSON : depth0),{"name":"if","hash":{},"fn":container.program(2, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.sampleXML : depth0),{"name":"if","hash":{},"fn":container.program(5, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "
    \n
    \n"; -},"2":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}; - - return "
    \n
    "
    -    + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.sampleJSON : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "")
    -    + "
    \n " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isParam : depth0),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n
    \n"; -},"3":function(container,depth0,helpers,partials,data) { - return ""; -},"5":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}; - - return "
    \n
    "
    -    + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || helpers.helperMissing).call(alias1,(depth0 != null ? depth0.sampleXML : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "")
    -    + "
    \n " - + ((stack1 = helpers["if"].call(alias1,(depth0 != null ? depth0.isParam : depth0),{"name":"if","hash":{},"fn":container.program(3, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + "\n
    \n"; -},"7":function(container,depth0,helpers,partials,data) { - var stack1; - - return " " - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || helpers.helperMissing).call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.signature : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1; - - return ((stack1 = (helpers.ifCond || (depth0 && depth0.ifCond) || helpers.helperMissing).call(depth0 != null ? depth0 : {},(depth0 != null ? depth0.sampleJSON : depth0),"||",(depth0 != null ? depth0.sampleXML : depth0),{"name":"ifCond","hash":{},"fn":container.program(1, data, 0),"inverse":container.program(7, data, 0),"data":data})) != null ? stack1 : ""); -},"useData":true}); -templates['status_code'] = template({"1":function(container,depth0,helpers,partials,data) { - var stack1, helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return " \n " - + container.escapeExpression(((helper = (helper = helpers.key || (data && data.key)) != null ? helper : alias2),(typeof helper === "function" ? helper.call(alias1,{"name":"key","hash":{},"data":data}) : helper))) - + "\n " - + ((stack1 = (helpers.sanitize || (depth0 && depth0.sanitize) || alias2).call(alias1,(depth0 != null ? depth0.description : depth0),{"name":"sanitize","hash":{},"data":data})) != null ? stack1 : "") - + "\n " - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.type : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n \n"; -},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { - var stack1, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing; - - return "" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.code : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n" - + ((stack1 = (helpers.escape || (depth0 && depth0.escape) || alias2).call(alias1,(depth0 != null ? depth0.message : depth0),{"name":"escape","hash":{},"data":data})) != null ? stack1 : "") - + "\n\n\n \n \n" - + ((stack1 = helpers.each.call(alias1,(depth0 != null ? depth0.headers : depth0),{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "") - + " \n
    \n"; -},"useData":true}); -})();} - /* jshint ignore:end */ -'use strict'; - - -$(function() { - - // Helper function for vertically aligning DOM elements - // http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/ - $.fn.vAlign = function() { - return this.each(function(){ - var ah = $(this).height(); - var ph = $(this).parent().height(); - var mh = (ph - ah) / 2; - $(this).css('margin-top', mh); - }); - }; - - $.fn.stretchFormtasticInputWidthToParent = function() { - return this.each(function(){ - var p_width = $(this).closest("form").innerWidth(); - var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest('form').css('padding-right'), 10); - var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10); - $(this).css('width', p_width - p_padding - this_padding); - }); - }; - - $('form.formtastic li.string input, form.formtastic textarea').stretchFormtasticInputWidthToParent(); - - // Vertically center these paragraphs - // Parent may need a min-height for this to work.. - $('ul.downplayed li div.content p').vAlign(); - - // When a sandbox form is submitted.. - $("form.sandbox").submit(function(){ - - var error_free = true; - - // Cycle through the forms required inputs - $(this).find("input.required").each(function() { - - // Remove any existing error styles from the input - $(this).removeClass('error'); - - // Tack the error style on if the input is empty.. - if ($(this).val() === '') { - $(this).addClass('error'); - $(this).wiggle(); - error_free = false; - } - - }); - - return error_free; - }); - -}); - -function clippyCopiedCallback() { - $('#api_key_copied').fadeIn().delay(1000).fadeOut(); - - // var b = $("#clippy_tooltip_" + a); - // b.length != 0 && (b.attr("title", "copied!").trigger("tipsy.reload"), setTimeout(function() { - // b.attr("title", "copy to clipboard") - // }, - // 500)) -} - -// Logging function that accounts for browsers that don't have window.console -function log(){ - log.history = log.history || []; - log.history.push(arguments); - if(this.console){ - console.log( Array.prototype.slice.call(arguments)[0] ); - } -} - -// Handle browsers that do console incorrectly (IE9 and below, see http://stackoverflow.com/a/5539378/7913) -if (Function.prototype.bind && console && typeof console.log === "object") { - [ - "log","info","warn","error","assert","dir","clear","profile","profileEnd" - ].forEach(function (method) { - console[method] = this.bind(console[method], console); - }, Function.prototype.call); -} - -window.Docs = { - - shebang: function() { - - // If shebang has an operation nickname in it.. - // e.g. /docs/#!/words/get_search - var fragments = $.param.fragment().split('/'); - fragments.shift(); // get rid of the bang - - switch (fragments.length) { - case 1: - if (fragments[0].length > 0) { // prevent matching "#/" - // Expand all operations for the resource and scroll to it - var dom_id = 'resource_' + fragments[0]; - - Docs.expandEndpointListForResource(fragments[0]); - $("#"+dom_id).slideto({highlight: false}); - } - break; - case 2: - // Refer to the endpoint DOM element, e.g. #words_get_search - - // Expand Resource - Docs.expandEndpointListForResource(fragments[0]); - $("#"+dom_id).slideto({highlight: false}); - - // Expand operation - var li_dom_id = fragments.join('_'); - var li_content_dom_id = li_dom_id + "_content"; - - - Docs.expandOperation($('#'+li_content_dom_id)); - $('#'+li_dom_id).slideto({highlight: false}); - break; - } - }, - - toggleEndpointListForResource: function(resource) { - var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); - if (elem.is(':visible')) { - $.bbq.pushState('#/', 2); - Docs.collapseEndpointListForResource(resource); - } else { - $.bbq.pushState('#/' + resource, 2); - Docs.expandEndpointListForResource(resource); - } - }, - - // Expand resource - expandEndpointListForResource: function(resource) { - var resource = Docs.escapeResourceName(resource); - if (resource == '') { - $('.resource ul.endpoints').slideDown(); - return; - } - - $('li#resource_' + resource).addClass('active'); - - var elem = $('li#resource_' + resource + ' ul.endpoints'); - elem.slideDown(); - }, - - // Collapse resource and mark as explicitly closed - collapseEndpointListForResource: function(resource) { - var resource = Docs.escapeResourceName(resource); - if (resource == '') { - $('.resource ul.endpoints').slideUp(); - return; - } - - $('li#resource_' + resource).removeClass('active'); - - var elem = $('li#resource_' + resource + ' ul.endpoints'); - elem.slideUp(); - }, - - expandOperationsForResource: function(resource) { - // Make sure the resource container is open.. - Docs.expandEndpointListForResource(resource); - - if (resource == '') { - $('.resource ul.endpoints li.operation div.content').slideDown(); - return; - } - - $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { - Docs.expandOperation($(this)); - }); - }, - - collapseOperationsForResource: function(resource) { - // Make sure the resource container is open.. - Docs.expandEndpointListForResource(resource); - - if (resource == '') { - $('.resource ul.endpoints li.operation div.content').slideUp(); - return; - } - - $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { - Docs.collapseOperation($(this)); - }); - }, - - escapeResourceName: function(resource) { - return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&"); - }, - - expandOperation: function(elem) { - elem.slideDown(); - }, - - collapseOperation: function(elem) { - elem.slideUp(); - } -}; - -/*! - * https://github.com/es-shims/es5-shim - * @license es5-shim Copyright 2009-2015 by contributors, MIT License - * see https://github.com/es-shims/es5-shim/blob/master/LICENSE - */ - -// vim: ts=4 sts=4 sw=4 expandtab - -// Add semicolon to prevent IIFE from being passed as argument to concatenated code. -; - -// UMD (Universal Module Definition) -// see https://github.com/umdjs/umd/blob/master/templates/returnExports.js -(function (root, factory) { - 'use strict'; - - /* global define, exports, module */ - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(factory); - } else if (typeof exports === 'object') { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like enviroments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals (root is window) - root.returnExports = factory(); - } -}(this, function () { - /** - * Brings an environment as close to ECMAScript 5 compliance - * as is possible with the facilities of erstwhile engines. - * - * Annotated ES5: http://es5.github.com/ (specific links below) - * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf - * Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/ - */ - - // Shortcut to an often accessed properties, in order to avoid multiple - // dereference that costs universally. This also holds a reference to known-good - // functions. - var $Array = Array; - var ArrayPrototype = $Array.prototype; - var $Object = Object; - var ObjectPrototype = $Object.prototype; - var $Function = Function; - var FunctionPrototype = $Function.prototype; - var $String = String; - var StringPrototype = $String.prototype; - var $Number = Number; - var NumberPrototype = $Number.prototype; - var array_slice = ArrayPrototype.slice; - var array_splice = ArrayPrototype.splice; - var array_push = ArrayPrototype.push; - var array_unshift = ArrayPrototype.unshift; - var array_concat = ArrayPrototype.concat; - var array_join = ArrayPrototype.join; - var call = FunctionPrototype.call; - var apply = FunctionPrototype.apply; - var max = Math.max; - var min = Math.min; - - // Having a toString local variable name breaks in Opera so use to_string. - var to_string = ObjectPrototype.toString; - - /* global Symbol */ - /* eslint-disable one-var-declaration-per-line, no-redeclare, max-statements-per-line */ - var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - var isCallable; /* inlined from https://npmjs.com/is-callable */ var fnToStr = Function.prototype.toString, constructorRegex = /^\s*class /, isES6ClassFn = function isES6ClassFn(value) { try { var fnStr = fnToStr.call(value); var singleStripped = fnStr.replace(/\/\/.*\n/g, ''); var multiStripped = singleStripped.replace(/\/\*[.\s\S]*\*\//g, ''); var spaceStripped = multiStripped.replace(/\n/mg, ' ').replace(/ {2}/g, ' '); return constructorRegex.test(spaceStripped); } catch (e) { return false; /* not a function */ } }, tryFunctionObject = function tryFunctionObject(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }, fnClass = '[object Function]', genClass = '[object GeneratorFunction]', isCallable = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = to_string.call(value); return strClass === fnClass || strClass === genClass; }; - - var isRegex; /* inlined from https://npmjs.com/is-regex */ var regexExec = RegExp.prototype.exec, tryRegexExec = function tryRegexExec(value) { try { regexExec.call(value); return true; } catch (e) { return false; } }, regexClass = '[object RegExp]'; isRegex = function isRegex(value) { if (typeof value !== 'object') { return false; } return hasToStringTag ? tryRegexExec(value) : to_string.call(value) === regexClass; }; - var isString; /* inlined from https://npmjs.com/is-string */ var strValue = String.prototype.valueOf, tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }, stringClass = '[object String]'; isString = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : to_string.call(value) === stringClass; }; - /* eslint-enable one-var-declaration-per-line, no-redeclare, max-statements-per-line */ - - /* inlined from http://npmjs.com/define-properties */ - var supportsDescriptors = $Object.defineProperty && (function () { - try { - var obj = {}; - $Object.defineProperty(obj, 'x', { enumerable: false, value: obj }); - for (var _ in obj) { // jscs:ignore disallowUnusedVariables - return false; - } - return obj.x === obj; - } catch (e) { /* this is ES3 */ - return false; - } - }()); - var defineProperties = (function (has) { - // Define configurable, writable, and non-enumerable props - // if they don't exist. - var defineProperty; - if (supportsDescriptors) { - defineProperty = function (object, name, method, forceAssign) { - if (!forceAssign && (name in object)) { - return; - } - $Object.defineProperty(object, name, { - configurable: true, - enumerable: false, - writable: true, - value: method - }); - }; - } else { - defineProperty = function (object, name, method, forceAssign) { - if (!forceAssign && (name in object)) { - return; - } - object[name] = method; - }; - } - return function defineProperties(object, map, forceAssign) { - for (var name in map) { - if (has.call(map, name)) { - defineProperty(object, name, map[name], forceAssign); - } - } - }; - }(ObjectPrototype.hasOwnProperty)); - - // - // Util - // ====== - // - - /* replaceable with https://npmjs.com/package/es-abstract /helpers/isPrimitive */ - var isPrimitive = function isPrimitive(input) { - var type = typeof input; - return input === null || (type !== 'object' && type !== 'function'); - }; - - var isActualNaN = $Number.isNaN || function isActualNaN(x) { - return x !== x; - }; - - var ES = { - // ES5 9.4 - // http://es5.github.com/#x9.4 - // http://jsperf.com/to-integer - /* replaceable with https://npmjs.com/package/es-abstract ES5.ToInteger */ - ToInteger: function ToInteger(num) { - var n = +num; - if (isActualNaN(n)) { - n = 0; - } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } - return n; - }, - - /* replaceable with https://npmjs.com/package/es-abstract ES5.ToPrimitive */ - ToPrimitive: function ToPrimitive(input) { - var val, valueOf, toStr; - if (isPrimitive(input)) { - return input; - } - valueOf = input.valueOf; - if (isCallable(valueOf)) { - val = valueOf.call(input); - if (isPrimitive(val)) { - return val; - } - } - toStr = input.toString; - if (isCallable(toStr)) { - val = toStr.call(input); - if (isPrimitive(val)) { - return val; - } - } - throw new TypeError(); - }, - - // ES5 9.9 - // http://es5.github.com/#x9.9 - /* replaceable with https://npmjs.com/package/es-abstract ES5.ToObject */ - ToObject: function (o) { - if (o == null) { // this matches both null and undefined - throw new TypeError("can't convert " + o + ' to object'); - } - return $Object(o); - }, - - /* replaceable with https://npmjs.com/package/es-abstract ES5.ToUint32 */ - ToUint32: function ToUint32(x) { - return x >>> 0; - } - }; - - // - // Function - // ======== - // - - // ES-5 15.3.4.5 - // http://es5.github.com/#x15.3.4.5 - - var Empty = function Empty() {}; - - defineProperties(FunctionPrototype, { - bind: function bind(that) { // .length is 1 - // 1. Let Target be the this value. - var target = this; - // 2. If IsCallable(Target) is false, throw a TypeError exception. - if (!isCallable(target)) { - throw new TypeError('Function.prototype.bind called on incompatible ' + target); - } - // 3. Let A be a new (possibly empty) internal list of all of the - // argument values provided after thisArg (arg1, arg2 etc), in order. - // XXX slicedArgs will stand in for "A" if used - var args = array_slice.call(arguments, 1); // for normal call - // 4. Let F be a new native ECMAScript object. - // 11. Set the [[Prototype]] internal property of F to the standard - // built-in Function prototype object as specified in 15.3.3.1. - // 12. Set the [[Call]] internal property of F as described in - // 15.3.4.5.1. - // 13. Set the [[Construct]] internal property of F as described in - // 15.3.4.5.2. - // 14. Set the [[HasInstance]] internal property of F as described in - // 15.3.4.5.3. - var bound; - var binder = function () { - - if (this instanceof bound) { - // 15.3.4.5.2 [[Construct]] - // When the [[Construct]] internal method of a function object, - // F that was created using the bind function is called with a - // list of arguments ExtraArgs, the following steps are taken: - // 1. Let target be the value of F's [[TargetFunction]] - // internal property. - // 2. If target has no [[Construct]] internal method, a - // TypeError exception is thrown. - // 3. Let boundArgs be the value of F's [[BoundArgs]] internal - // property. - // 4. Let args be a new list containing the same values as the - // list boundArgs in the same order followed by the same - // values as the list ExtraArgs in the same order. - // 5. Return the result of calling the [[Construct]] internal - // method of target providing args as the arguments. - - var result = apply.call( - target, - this, - array_concat.call(args, array_slice.call(arguments)) - ); - if ($Object(result) === result) { - return result; - } - return this; - - } else { - // 15.3.4.5.1 [[Call]] - // When the [[Call]] internal method of a function object, F, - // which was created using the bind function is called with a - // this value and a list of arguments ExtraArgs, the following - // steps are taken: - // 1. Let boundArgs be the value of F's [[BoundArgs]] internal - // property. - // 2. Let boundThis be the value of F's [[BoundThis]] internal - // property. - // 3. Let target be the value of F's [[TargetFunction]] internal - // property. - // 4. Let args be a new list containing the same values as the - // list boundArgs in the same order followed by the same - // values as the list ExtraArgs in the same order. - // 5. Return the result of calling the [[Call]] internal method - // of target providing boundThis as the this value and - // providing args as the arguments. - - // equiv: target.call(this, ...boundArgs, ...args) - return apply.call( - target, - that, - array_concat.call(args, array_slice.call(arguments)) - ); - - } - - }; - - // 15. If the [[Class]] internal property of Target is "Function", then - // a. Let L be the length property of Target minus the length of A. - // b. Set the length own property of F to either 0 or L, whichever is - // larger. - // 16. Else set the length own property of F to 0. - - var boundLength = max(0, target.length - args.length); - - // 17. Set the attributes of the length own property of F to the values - // specified in 15.3.5.1. - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - array_push.call(boundArgs, '$' + i); - } - - // XXX Build a dynamic function with desired amount of arguments is the only - // way to set the length property of a function. - // In environments where Content Security Policies enabled (Chrome extensions, - // for ex.) all use of eval or Function costructor throws an exception. - // However in all of these environments Function.prototype.bind exists - // and so this code will never be executed. - bound = $Function('binder', 'return function (' + array_join.call(boundArgs, ',') + '){ return binder.apply(this, arguments); }')(binder); - - if (target.prototype) { - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - // Clean up dangling references. - Empty.prototype = null; - } - - // TODO - // 18. Set the [[Extensible]] internal property of F to true. - - // TODO - // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). - // 20. Call the [[DefineOwnProperty]] internal method of F with - // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: - // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and - // false. - // 21. Call the [[DefineOwnProperty]] internal method of F with - // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, - // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, - // and false. - - // TODO - // NOTE Function objects created using Function.prototype.bind do not - // have a prototype property or the [[Code]], [[FormalParameters]], and - // [[Scope]] internal properties. - // XXX can't delete prototype in pure-js. - - // 22. Return F. - return bound; - } - }); - - // _Please note: Shortcuts are defined after `Function.prototype.bind` as we - // use it in defining shortcuts. - var owns = call.bind(ObjectPrototype.hasOwnProperty); - var toStr = call.bind(ObjectPrototype.toString); - var arraySlice = call.bind(array_slice); - var arraySliceApply = apply.bind(array_slice); - var strSlice = call.bind(StringPrototype.slice); - var strSplit = call.bind(StringPrototype.split); - var strIndexOf = call.bind(StringPrototype.indexOf); - var pushCall = call.bind(array_push); - var isEnum = call.bind(ObjectPrototype.propertyIsEnumerable); - var arraySort = call.bind(ArrayPrototype.sort); - - // - // Array - // ===== - // - - var isArray = $Array.isArray || function isArray(obj) { - return toStr(obj) === '[object Array]'; - }; - - // ES5 15.4.4.12 - // http://es5.github.com/#x15.4.4.13 - // Return len+argCount. - // [bugfix, ielt8] - // IE < 8 bug: [].unshift(0) === undefined but should be "1" - var hasUnshiftReturnValueBug = [].unshift(0) !== 1; - defineProperties(ArrayPrototype, { - unshift: function () { - array_unshift.apply(this, arguments); - return this.length; - } - }, hasUnshiftReturnValueBug); - - // ES5 15.4.3.2 - // http://es5.github.com/#x15.4.3.2 - // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray - defineProperties($Array, { isArray: isArray }); - - // The IsCallable() check in the Array functions - // has been replaced with a strict check on the - // internal class of the object to trap cases where - // the provided function was actually a regular - // expression literal, which in V8 and - // JavaScriptCore is a typeof "function". Only in - // V8 are regular expression literals permitted as - // reduce parameters, so it is desirable in the - // general case for the shim to match the more - // strict and common behavior of rejecting regular - // expressions. - - // ES5 15.4.4.18 - // http://es5.github.com/#x15.4.4.18 - // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach - - // Check failure of by-index access of string characters (IE < 9) - // and failure of `0 in boxedString` (Rhino) - var boxedString = $Object('a'); - var splitString = boxedString[0] !== 'a' || !(0 in boxedString); - - var properlyBoxesContext = function properlyBoxed(method) { - // Check node 0.6.21 bug where third parameter is not boxed - var properlyBoxesNonStrict = true; - var properlyBoxesStrict = true; - var threwException = false; - if (method) { - try { - method.call('foo', function (_, __, context) { - if (typeof context !== 'object') { - properlyBoxesNonStrict = false; - } - }); - - method.call([1], function () { - 'use strict'; - - properlyBoxesStrict = typeof this === 'string'; - }, 'x'); - } catch (e) { - threwException = true; - } - } - return !!method && !threwException && properlyBoxesNonStrict && properlyBoxesStrict; - }; - - defineProperties(ArrayPrototype, { - forEach: function forEach(callbackfn/*, thisArg*/) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var i = -1; - var length = ES.ToUint32(self.length); - var T; - if (arguments.length > 1) { - T = arguments[1]; - } - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.forEach callback must be a function'); - } - - while (++i < length) { - if (i in self) { - // Invoke the callback function with call, passing arguments: - // context, property value, property key, thisArg object - if (typeof T === 'undefined') { - callbackfn(self[i], i, object); - } else { - callbackfn.call(T, self[i], i, object); - } - } - } - } - }, !properlyBoxesContext(ArrayPrototype.forEach)); - - // ES5 15.4.4.19 - // http://es5.github.com/#x15.4.4.19 - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map - defineProperties(ArrayPrototype, { - map: function map(callbackfn/*, thisArg*/) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var length = ES.ToUint32(self.length); - var result = $Array(length); - var T; - if (arguments.length > 1) { - T = arguments[1]; - } - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.map callback must be a function'); - } - - for (var i = 0; i < length; i++) { - if (i in self) { - if (typeof T === 'undefined') { - result[i] = callbackfn(self[i], i, object); - } else { - result[i] = callbackfn.call(T, self[i], i, object); - } - } - } - return result; - } - }, !properlyBoxesContext(ArrayPrototype.map)); - - // ES5 15.4.4.20 - // http://es5.github.com/#x15.4.4.20 - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter - defineProperties(ArrayPrototype, { - filter: function filter(callbackfn/*, thisArg*/) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var length = ES.ToUint32(self.length); - var result = []; - var value; - var T; - if (arguments.length > 1) { - T = arguments[1]; - } - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.filter callback must be a function'); - } - - for (var i = 0; i < length; i++) { - if (i in self) { - value = self[i]; - if (typeof T === 'undefined' ? callbackfn(value, i, object) : callbackfn.call(T, value, i, object)) { - pushCall(result, value); - } - } - } - return result; - } - }, !properlyBoxesContext(ArrayPrototype.filter)); - - // ES5 15.4.4.16 - // http://es5.github.com/#x15.4.4.16 - // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every - defineProperties(ArrayPrototype, { - every: function every(callbackfn/*, thisArg*/) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var length = ES.ToUint32(self.length); - var T; - if (arguments.length > 1) { - T = arguments[1]; - } - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.every callback must be a function'); - } - - for (var i = 0; i < length; i++) { - if (i in self && !(typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) { - return false; - } - } - return true; - } - }, !properlyBoxesContext(ArrayPrototype.every)); - - // ES5 15.4.4.17 - // http://es5.github.com/#x15.4.4.17 - // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some - defineProperties(ArrayPrototype, { - some: function some(callbackfn/*, thisArg */) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var length = ES.ToUint32(self.length); - var T; - if (arguments.length > 1) { - T = arguments[1]; - } - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.some callback must be a function'); - } - - for (var i = 0; i < length; i++) { - if (i in self && (typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) { - return true; - } - } - return false; - } - }, !properlyBoxesContext(ArrayPrototype.some)); - - // ES5 15.4.4.21 - // http://es5.github.com/#x15.4.4.21 - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce - var reduceCoercesToObject = false; - if (ArrayPrototype.reduce) { - reduceCoercesToObject = typeof ArrayPrototype.reduce.call('es5', function (_, __, ___, list) { - return list; - }) === 'object'; - } - defineProperties(ArrayPrototype, { - reduce: function reduce(callbackfn/*, initialValue*/) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var length = ES.ToUint32(self.length); - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.reduce callback must be a function'); - } - - // no value to return if no initial value and an empty array - if (length === 0 && arguments.length === 1) { - throw new TypeError('reduce of empty array with no initial value'); - } - - var i = 0; - var result; - if (arguments.length >= 2) { - result = arguments[1]; - } else { - do { - if (i in self) { - result = self[i++]; - break; - } - - // if array contains no values, no initial value to return - if (++i >= length) { - throw new TypeError('reduce of empty array with no initial value'); - } - } while (true); - } - - for (; i < length; i++) { - if (i in self) { - result = callbackfn(result, self[i], i, object); - } - } - - return result; - } - }, !reduceCoercesToObject); - - // ES5 15.4.4.22 - // http://es5.github.com/#x15.4.4.22 - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight - var reduceRightCoercesToObject = false; - if (ArrayPrototype.reduceRight) { - reduceRightCoercesToObject = typeof ArrayPrototype.reduceRight.call('es5', function (_, __, ___, list) { - return list; - }) === 'object'; - } - defineProperties(ArrayPrototype, { - reduceRight: function reduceRight(callbackfn/*, initial*/) { - var object = ES.ToObject(this); - var self = splitString && isString(this) ? strSplit(this, '') : object; - var length = ES.ToUint32(self.length); - - // If no callback function or if callback is not a callable function - if (!isCallable(callbackfn)) { - throw new TypeError('Array.prototype.reduceRight callback must be a function'); - } - - // no value to return if no initial value, empty array - if (length === 0 && arguments.length === 1) { - throw new TypeError('reduceRight of empty array with no initial value'); - } - - var result; - var i = length - 1; - if (arguments.length >= 2) { - result = arguments[1]; - } else { - do { - if (i in self) { - result = self[i--]; - break; - } - - // if array contains no values, no initial value to return - if (--i < 0) { - throw new TypeError('reduceRight of empty array with no initial value'); - } - } while (true); - } - - if (i < 0) { - return result; - } - - do { - if (i in self) { - result = callbackfn(result, self[i], i, object); - } - } while (i--); - - return result; - } - }, !reduceRightCoercesToObject); - - // ES5 15.4.4.14 - // http://es5.github.com/#x15.4.4.14 - // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf - var hasFirefox2IndexOfBug = ArrayPrototype.indexOf && [0, 1].indexOf(1, 2) !== -1; - defineProperties(ArrayPrototype, { - indexOf: function indexOf(searchElement/*, fromIndex */) { - var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this); - var length = ES.ToUint32(self.length); - - if (length === 0) { - return -1; - } - - var i = 0; - if (arguments.length > 1) { - i = ES.ToInteger(arguments[1]); - } - - // handle negative indices - i = i >= 0 ? i : max(0, length + i); - for (; i < length; i++) { - if (i in self && self[i] === searchElement) { - return i; - } - } - return -1; - } - }, hasFirefox2IndexOfBug); - - // ES5 15.4.4.15 - // http://es5.github.com/#x15.4.4.15 - // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf - var hasFirefox2LastIndexOfBug = ArrayPrototype.lastIndexOf && [0, 1].lastIndexOf(0, -3) !== -1; - defineProperties(ArrayPrototype, { - lastIndexOf: function lastIndexOf(searchElement/*, fromIndex */) { - var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this); - var length = ES.ToUint32(self.length); - - if (length === 0) { - return -1; - } - var i = length - 1; - if (arguments.length > 1) { - i = min(i, ES.ToInteger(arguments[1])); - } - // handle negative indices - i = i >= 0 ? i : length - Math.abs(i); - for (; i >= 0; i--) { - if (i in self && searchElement === self[i]) { - return i; - } - } - return -1; - } - }, hasFirefox2LastIndexOfBug); - - // ES5 15.4.4.12 - // http://es5.github.com/#x15.4.4.12 - var spliceNoopReturnsEmptyArray = (function () { - var a = [1, 2]; - var result = a.splice(); - return a.length === 2 && isArray(result) && result.length === 0; - }()); - defineProperties(ArrayPrototype, { - // Safari 5.0 bug where .splice() returns undefined - splice: function splice(start, deleteCount) { - if (arguments.length === 0) { - return []; - } else { - return array_splice.apply(this, arguments); - } - } - }, !spliceNoopReturnsEmptyArray); - - var spliceWorksWithEmptyObject = (function () { - var obj = {}; - ArrayPrototype.splice.call(obj, 0, 0, 1); - return obj.length === 1; - }()); - defineProperties(ArrayPrototype, { - splice: function splice(start, deleteCount) { - if (arguments.length === 0) { - return []; - } - var args = arguments; - this.length = max(ES.ToInteger(this.length), 0); - if (arguments.length > 0 && typeof deleteCount !== 'number') { - args = arraySlice(arguments); - if (args.length < 2) { - pushCall(args, this.length - start); - } else { - args[1] = ES.ToInteger(deleteCount); - } - } - return array_splice.apply(this, args); - } - }, !spliceWorksWithEmptyObject); - var spliceWorksWithLargeSparseArrays = (function () { - // Per https://github.com/es-shims/es5-shim/issues/295 - // Safari 7/8 breaks with sparse arrays of size 1e5 or greater - var arr = new $Array(1e5); - // note: the index MUST be 8 or larger or the test will false pass - arr[8] = 'x'; - arr.splice(1, 1); - // note: this test must be defined *after* the indexOf shim - // per https://github.com/es-shims/es5-shim/issues/313 - return arr.indexOf('x') === 7; - }()); - var spliceWorksWithSmallSparseArrays = (function () { - // Per https://github.com/es-shims/es5-shim/issues/295 - // Opera 12.15 breaks on this, no idea why. - var n = 256; - var arr = []; - arr[n] = 'a'; - arr.splice(n + 1, 0, 'b'); - return arr[n] === 'a'; - }()); - defineProperties(ArrayPrototype, { - splice: function splice(start, deleteCount) { - var O = ES.ToObject(this); - var A = []; - var len = ES.ToUint32(O.length); - var relativeStart = ES.ToInteger(start); - var actualStart = relativeStart < 0 ? max((len + relativeStart), 0) : min(relativeStart, len); - var actualDeleteCount = min(max(ES.ToInteger(deleteCount), 0), len - actualStart); - - var k = 0; - var from; - while (k < actualDeleteCount) { - from = $String(actualStart + k); - if (owns(O, from)) { - A[k] = O[from]; - } - k += 1; - } - - var items = arraySlice(arguments, 2); - var itemCount = items.length; - var to; - if (itemCount < actualDeleteCount) { - k = actualStart; - var maxK = len - actualDeleteCount; - while (k < maxK) { - from = $String(k + actualDeleteCount); - to = $String(k + itemCount); - if (owns(O, from)) { - O[to] = O[from]; - } else { - delete O[to]; - } - k += 1; - } - k = len; - var minK = len - actualDeleteCount + itemCount; - while (k > minK) { - delete O[k - 1]; - k -= 1; - } - } else if (itemCount > actualDeleteCount) { - k = len - actualDeleteCount; - while (k > actualStart) { - from = $String(k + actualDeleteCount - 1); - to = $String(k + itemCount - 1); - if (owns(O, from)) { - O[to] = O[from]; - } else { - delete O[to]; - } - k -= 1; - } - } - k = actualStart; - for (var i = 0; i < items.length; ++i) { - O[k] = items[i]; - k += 1; - } - O.length = len - actualDeleteCount + itemCount; - - return A; - } - }, !spliceWorksWithLargeSparseArrays || !spliceWorksWithSmallSparseArrays); - - var originalJoin = ArrayPrototype.join; - var hasStringJoinBug; - try { - hasStringJoinBug = Array.prototype.join.call('123', ',') !== '1,2,3'; - } catch (e) { - hasStringJoinBug = true; - } - if (hasStringJoinBug) { - defineProperties(ArrayPrototype, { - join: function join(separator) { - var sep = typeof separator === 'undefined' ? ',' : separator; - return originalJoin.call(isString(this) ? strSplit(this, '') : this, sep); - } - }, hasStringJoinBug); - } - - var hasJoinUndefinedBug = [1, 2].join(undefined) !== '1,2'; - if (hasJoinUndefinedBug) { - defineProperties(ArrayPrototype, { - join: function join(separator) { - var sep = typeof separator === 'undefined' ? ',' : separator; - return originalJoin.call(this, sep); - } - }, hasJoinUndefinedBug); - } - - var pushShim = function push(item) { - var O = ES.ToObject(this); - var n = ES.ToUint32(O.length); - var i = 0; - while (i < arguments.length) { - O[n + i] = arguments[i]; - i += 1; - } - O.length = n + i; - return n + i; - }; - - var pushIsNotGeneric = (function () { - var obj = {}; - var result = Array.prototype.push.call(obj, undefined); - return result !== 1 || obj.length !== 1 || typeof obj[0] !== 'undefined' || !owns(obj, 0); - }()); - defineProperties(ArrayPrototype, { - push: function push(item) { - if (isArray(this)) { - return array_push.apply(this, arguments); - } - return pushShim.apply(this, arguments); - } - }, pushIsNotGeneric); - - // This fixes a very weird bug in Opera 10.6 when pushing `undefined - var pushUndefinedIsWeird = (function () { - var arr = []; - var result = arr.push(undefined); - return result !== 1 || arr.length !== 1 || typeof arr[0] !== 'undefined' || !owns(arr, 0); - }()); - defineProperties(ArrayPrototype, { push: pushShim }, pushUndefinedIsWeird); - - // ES5 15.2.3.14 - // http://es5.github.io/#x15.4.4.10 - // Fix boxed string bug - defineProperties(ArrayPrototype, { - slice: function (start, end) { - var arr = isString(this) ? strSplit(this, '') : this; - return arraySliceApply(arr, arguments); - } - }, splitString); - - var sortIgnoresNonFunctions = (function () { - try { - [1, 2].sort(null); - [1, 2].sort({}); - return true; - } catch (e) {} - return false; - }()); - var sortThrowsOnRegex = (function () { - // this is a problem in Firefox 4, in which `typeof /a/ === 'function'` - try { - [1, 2].sort(/a/); - return false; - } catch (e) {} - return true; - }()); - var sortIgnoresUndefined = (function () { - // applies in IE 8, for one. - try { - [1, 2].sort(undefined); - return true; - } catch (e) {} - return false; - }()); - defineProperties(ArrayPrototype, { - sort: function sort(compareFn) { - if (typeof compareFn === 'undefined') { - return arraySort(this); - } - if (!isCallable(compareFn)) { - throw new TypeError('Array.prototype.sort callback must be a function'); - } - return arraySort(this, compareFn); - } - }, sortIgnoresNonFunctions || !sortIgnoresUndefined || !sortThrowsOnRegex); - - // - // Object - // ====== - // - - // ES5 15.2.3.14 - // http://es5.github.com/#x15.2.3.14 - - // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation - var hasDontEnumBug = !isEnum({ 'toString': null }, 'toString'); - var hasProtoEnumBug = isEnum(function () {}, 'prototype'); - var hasStringEnumBug = !owns('x', '0'); - var equalsConstructorPrototype = function (o) { - var ctor = o.constructor; - return ctor && ctor.prototype === o; - }; - var blacklistedKeys = { - $window: true, - $console: true, - $parent: true, - $self: true, - $frame: true, - $frames: true, - $frameElement: true, - $webkitIndexedDB: true, - $webkitStorageInfo: true, - $external: true - }; - var hasAutomationEqualityBug = (function () { - /* globals window */ - if (typeof window === 'undefined') { - return false; - } - for (var k in window) { - try { - if (!blacklistedKeys['$' + k] && owns(window, k) && window[k] !== null && typeof window[k] === 'object') { - equalsConstructorPrototype(window[k]); - } - } catch (e) { - return true; - } - } - return false; - }()); - var equalsConstructorPrototypeIfNotBuggy = function (object) { - if (typeof window === 'undefined' || !hasAutomationEqualityBug) { - return equalsConstructorPrototype(object); - } - try { - return equalsConstructorPrototype(object); - } catch (e) { - return false; - } - }; - var dontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ]; - var dontEnumsLength = dontEnums.length; - - // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js - // can be replaced with require('is-arguments') if we ever use a build process instead - var isStandardArguments = function isArguments(value) { - return toStr(value) === '[object Arguments]'; - }; - var isLegacyArguments = function isArguments(value) { - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - !isArray(value) && - isCallable(value.callee); - }; - var isArguments = isStandardArguments(arguments) ? isStandardArguments : isLegacyArguments; - - defineProperties($Object, { - keys: function keys(object) { - var isFn = isCallable(object); - var isArgs = isArguments(object); - var isObject = object !== null && typeof object === 'object'; - var isStr = isObject && isString(object); - - if (!isObject && !isFn && !isArgs) { - throw new TypeError('Object.keys called on a non-object'); - } - - var theKeys = []; - var skipProto = hasProtoEnumBug && isFn; - if ((isStr && hasStringEnumBug) || isArgs) { - for (var i = 0; i < object.length; ++i) { - pushCall(theKeys, $String(i)); - } - } - - if (!isArgs) { - for (var name in object) { - if (!(skipProto && name === 'prototype') && owns(object, name)) { - pushCall(theKeys, $String(name)); - } - } - } - - if (hasDontEnumBug) { - var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); - for (var j = 0; j < dontEnumsLength; j++) { - var dontEnum = dontEnums[j]; - if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) { - pushCall(theKeys, dontEnum); - } - } - } - return theKeys; - } - }); - - var keysWorksWithArguments = $Object.keys && (function () { - // Safari 5.0 bug - return $Object.keys(arguments).length === 2; - }(1, 2)); - var keysHasArgumentsLengthBug = $Object.keys && (function () { - var argKeys = $Object.keys(arguments); - return arguments.length !== 1 || argKeys.length !== 1 || argKeys[0] !== 1; - }(1)); - var originalKeys = $Object.keys; - defineProperties($Object, { - keys: function keys(object) { - if (isArguments(object)) { - return originalKeys(arraySlice(object)); - } else { - return originalKeys(object); - } - } - }, !keysWorksWithArguments || keysHasArgumentsLengthBug); - - // - // Date - // ==== - // - - var hasNegativeMonthYearBug = new Date(-3509827329600292).getUTCMonth() !== 0; - var aNegativeTestDate = new Date(-1509842289600292); - var aPositiveTestDate = new Date(1449662400000); - var hasToUTCStringFormatBug = aNegativeTestDate.toUTCString() !== 'Mon, 01 Jan -45875 11:59:59 GMT'; - var hasToDateStringFormatBug; - var hasToStringFormatBug; - var timeZoneOffset = aNegativeTestDate.getTimezoneOffset(); - if (timeZoneOffset < -720) { - hasToDateStringFormatBug = aNegativeTestDate.toDateString() !== 'Tue Jan 02 -45875'; - hasToStringFormatBug = !(/^Thu Dec 10 2015 \d\d:\d\d:\d\d GMT[-\+]\d\d\d\d(?: |$)/).test(aPositiveTestDate.toString()); - } else { - hasToDateStringFormatBug = aNegativeTestDate.toDateString() !== 'Mon Jan 01 -45875'; - hasToStringFormatBug = !(/^Wed Dec 09 2015 \d\d:\d\d:\d\d GMT[-\+]\d\d\d\d(?: |$)/).test(aPositiveTestDate.toString()); - } - - var originalGetFullYear = call.bind(Date.prototype.getFullYear); - var originalGetMonth = call.bind(Date.prototype.getMonth); - var originalGetDate = call.bind(Date.prototype.getDate); - var originalGetUTCFullYear = call.bind(Date.prototype.getUTCFullYear); - var originalGetUTCMonth = call.bind(Date.prototype.getUTCMonth); - var originalGetUTCDate = call.bind(Date.prototype.getUTCDate); - var originalGetUTCDay = call.bind(Date.prototype.getUTCDay); - var originalGetUTCHours = call.bind(Date.prototype.getUTCHours); - var originalGetUTCMinutes = call.bind(Date.prototype.getUTCMinutes); - var originalGetUTCSeconds = call.bind(Date.prototype.getUTCSeconds); - var originalGetUTCMilliseconds = call.bind(Date.prototype.getUTCMilliseconds); - var dayName = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var monthName = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var daysInMonth = function daysInMonth(month, year) { - return originalGetDate(new Date(year, month, 0)); - }; - - defineProperties(Date.prototype, { - getFullYear: function getFullYear() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var year = originalGetFullYear(this); - if (year < 0 && originalGetMonth(this) > 11) { - return year + 1; - } - return year; - }, - getMonth: function getMonth() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var year = originalGetFullYear(this); - var month = originalGetMonth(this); - if (year < 0 && month > 11) { - return 0; - } - return month; - }, - getDate: function getDate() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var year = originalGetFullYear(this); - var month = originalGetMonth(this); - var date = originalGetDate(this); - if (year < 0 && month > 11) { - if (month === 12) { - return date; - } - var days = daysInMonth(0, year + 1); - return (days - date) + 1; - } - return date; - }, - getUTCFullYear: function getUTCFullYear() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var year = originalGetUTCFullYear(this); - if (year < 0 && originalGetUTCMonth(this) > 11) { - return year + 1; - } - return year; - }, - getUTCMonth: function getUTCMonth() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var year = originalGetUTCFullYear(this); - var month = originalGetUTCMonth(this); - if (year < 0 && month > 11) { - return 0; - } - return month; - }, - getUTCDate: function getUTCDate() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var year = originalGetUTCFullYear(this); - var month = originalGetUTCMonth(this); - var date = originalGetUTCDate(this); - if (year < 0 && month > 11) { - if (month === 12) { - return date; - } - var days = daysInMonth(0, year + 1); - return (days - date) + 1; - } - return date; - } - }, hasNegativeMonthYearBug); - - defineProperties(Date.prototype, { - toUTCString: function toUTCString() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var day = originalGetUTCDay(this); - var date = originalGetUTCDate(this); - var month = originalGetUTCMonth(this); - var year = originalGetUTCFullYear(this); - var hour = originalGetUTCHours(this); - var minute = originalGetUTCMinutes(this); - var second = originalGetUTCSeconds(this); - return dayName[day] + ', ' + - (date < 10 ? '0' + date : date) + ' ' + - monthName[month] + ' ' + - year + ' ' + - (hour < 10 ? '0' + hour : hour) + ':' + - (minute < 10 ? '0' + minute : minute) + ':' + - (second < 10 ? '0' + second : second) + ' GMT'; - } - }, hasNegativeMonthYearBug || hasToUTCStringFormatBug); - - // Opera 12 has `,` - defineProperties(Date.prototype, { - toDateString: function toDateString() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var day = this.getDay(); - var date = this.getDate(); - var month = this.getMonth(); - var year = this.getFullYear(); - return dayName[day] + ' ' + - monthName[month] + ' ' + - (date < 10 ? '0' + date : date) + ' ' + - year; - } - }, hasNegativeMonthYearBug || hasToDateStringFormatBug); - - // can't use defineProperties here because of toString enumeration issue in IE <= 8 - if (hasNegativeMonthYearBug || hasToStringFormatBug) { - Date.prototype.toString = function toString() { - if (!this || !(this instanceof Date)) { - throw new TypeError('this is not a Date object.'); - } - var day = this.getDay(); - var date = this.getDate(); - var month = this.getMonth(); - var year = this.getFullYear(); - var hour = this.getHours(); - var minute = this.getMinutes(); - var second = this.getSeconds(); - var timezoneOffset = this.getTimezoneOffset(); - var hoursOffset = Math.floor(Math.abs(timezoneOffset) / 60); - var minutesOffset = Math.floor(Math.abs(timezoneOffset) % 60); - return dayName[day] + ' ' + - monthName[month] + ' ' + - (date < 10 ? '0' + date : date) + ' ' + - year + ' ' + - (hour < 10 ? '0' + hour : hour) + ':' + - (minute < 10 ? '0' + minute : minute) + ':' + - (second < 10 ? '0' + second : second) + ' GMT' + - (timezoneOffset > 0 ? '-' : '+') + - (hoursOffset < 10 ? '0' + hoursOffset : hoursOffset) + - (minutesOffset < 10 ? '0' + minutesOffset : minutesOffset); - }; - if (supportsDescriptors) { - $Object.defineProperty(Date.prototype, 'toString', { - configurable: true, - enumerable: false, - writable: true - }); - } - } - - // ES5 15.9.5.43 - // http://es5.github.com/#x15.9.5.43 - // This function returns a String value represent the instance in time - // represented by this Date object. The format of the String is the Date Time - // string format defined in 15.9.1.15. All fields are present in the String. - // The time zone is always UTC, denoted by the suffix Z. If the time value of - // this object is not a finite Number a RangeError exception is thrown. - var negativeDate = -62198755200000; - var negativeYearString = '-000001'; - var hasNegativeDateBug = Date.prototype.toISOString && new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1; - var hasSafari51DateBug = Date.prototype.toISOString && new Date(-1).toISOString() !== '1969-12-31T23:59:59.999Z'; - - var getTime = call.bind(Date.prototype.getTime); - - defineProperties(Date.prototype, { - toISOString: function toISOString() { - if (!isFinite(this) || !isFinite(getTime(this))) { - // Adope Photoshop requires the second check. - throw new RangeError('Date.prototype.toISOString called on non-finite value.'); - } - - var year = originalGetUTCFullYear(this); - - var month = originalGetUTCMonth(this); - // see https://github.com/es-shims/es5-shim/issues/111 - year += Math.floor(month / 12); - month = (month % 12 + 12) % 12; - - // the date time string format is specified in 15.9.1.15. - var result = [month + 1, originalGetUTCDate(this), originalGetUTCHours(this), originalGetUTCMinutes(this), originalGetUTCSeconds(this)]; - year = ( - (year < 0 ? '-' : (year > 9999 ? '+' : '')) + - strSlice('00000' + Math.abs(year), (0 <= year && year <= 9999) ? -4 : -6) - ); - - for (var i = 0; i < result.length; ++i) { - // pad months, days, hours, minutes, and seconds to have two digits. - result[i] = strSlice('00' + result[i], -2); - } - // pad milliseconds to have three digits. - return ( - year + '-' + arraySlice(result, 0, 2).join('-') + - 'T' + arraySlice(result, 2).join(':') + '.' + - strSlice('000' + originalGetUTCMilliseconds(this), -3) + 'Z' - ); - } - }, hasNegativeDateBug || hasSafari51DateBug); - - // ES5 15.9.5.44 - // http://es5.github.com/#x15.9.5.44 - // This function provides a String representation of a Date object for use by - // JSON.stringify (15.12.3). - var dateToJSONIsSupported = (function () { - try { - return Date.prototype.toJSON && - new Date(NaN).toJSON() === null && - new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 && - Date.prototype.toJSON.call({ // generic - toISOString: function () { return true; } - }); - } catch (e) { - return false; - } - }()); - if (!dateToJSONIsSupported) { - Date.prototype.toJSON = function toJSON(key) { - // When the toJSON method is called with argument key, the following - // steps are taken: - - // 1. Let O be the result of calling ToObject, giving it the this - // value as its argument. - // 2. Let tv be ES.ToPrimitive(O, hint Number). - var O = $Object(this); - var tv = ES.ToPrimitive(O); - // 3. If tv is a Number and is not finite, return null. - if (typeof tv === 'number' && !isFinite(tv)) { - return null; - } - // 4. Let toISO be the result of calling the [[Get]] internal method of - // O with argument "toISOString". - var toISO = O.toISOString; - // 5. If IsCallable(toISO) is false, throw a TypeError exception. - if (!isCallable(toISO)) { - throw new TypeError('toISOString property is not callable'); - } - // 6. Return the result of calling the [[Call]] internal method of - // toISO with O as the this value and an empty argument list. - return toISO.call(O); - - // NOTE 1 The argument is ignored. - - // NOTE 2 The toJSON function is intentionally generic; it does not - // require that its this value be a Date object. Therefore, it can be - // transferred to other kinds of objects for use as a method. However, - // it does require that any such object have a toISOString method. An - // object is free to use the argument key to filter its - // stringification. - }; - } - - // ES5 15.9.4.2 - // http://es5.github.com/#x15.9.4.2 - // based on work shared by Daniel Friesen (dantman) - // http://gist.github.com/303249 - var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15; - var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z')) || !isNaN(Date.parse('2012-12-31T23:59:60.000Z')); - var doesNotParseY2KNewYear = isNaN(Date.parse('2000-01-01T00:00:00.000Z')); - if (doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) { - // XXX global assignment won't work in embeddings that use - // an alternate object for the context. - /* global Date: true */ - /* eslint-disable no-undef */ - var maxSafeUnsigned32Bit = Math.pow(2, 31) - 1; - var hasSafariSignedIntBug = isActualNaN(new Date(1970, 0, 1, 0, 0, 0, maxSafeUnsigned32Bit + 1).getTime()); - /* eslint-disable no-implicit-globals */ - Date = (function (NativeDate) { - /* eslint-enable no-implicit-globals */ - /* eslint-enable no-undef */ - // Date.length === 7 - var DateShim = function Date(Y, M, D, h, m, s, ms) { - var length = arguments.length; - var date; - if (this instanceof NativeDate) { - var seconds = s; - var millis = ms; - if (hasSafariSignedIntBug && length >= 7 && ms > maxSafeUnsigned32Bit) { - // work around a Safari 8/9 bug where it treats the seconds as signed - var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit; - var sToShift = Math.floor(msToShift / 1e3); - seconds += sToShift; - millis -= sToShift * 1e3; - } - date = length === 1 && $String(Y) === Y ? // isString(Y) - // We explicitly pass it through parse: - new NativeDate(DateShim.parse(Y)) : - // We have to manually make calls depending on argument - // length here - length >= 7 ? new NativeDate(Y, M, D, h, m, seconds, millis) : - length >= 6 ? new NativeDate(Y, M, D, h, m, seconds) : - length >= 5 ? new NativeDate(Y, M, D, h, m) : - length >= 4 ? new NativeDate(Y, M, D, h) : - length >= 3 ? new NativeDate(Y, M, D) : - length >= 2 ? new NativeDate(Y, M) : - length >= 1 ? new NativeDate(Y instanceof NativeDate ? +Y : Y) : - new NativeDate(); - } else { - date = NativeDate.apply(this, arguments); - } - if (!isPrimitive(date)) { - // Prevent mixups with unfixed Date object - defineProperties(date, { constructor: DateShim }, true); - } - return date; - }; - - // 15.9.1.15 Date Time String Format. - var isoDateExpression = new RegExp('^' + - '(\\d{4}|[+-]\\d{6})' + // four-digit year capture or sign + - // 6-digit extended year - '(?:-(\\d{2})' + // optional month capture - '(?:-(\\d{2})' + // optional day capture - '(?:' + // capture hours:minutes:seconds.milliseconds - 'T(\\d{2})' + // hours capture - ':(\\d{2})' + // minutes capture - '(?:' + // optional :seconds.milliseconds - ':(\\d{2})' + // seconds capture - '(?:(\\.\\d{1,}))?' + // milliseconds capture - ')?' + - '(' + // capture UTC offset component - 'Z|' + // UTC capture - '(?:' + // offset specifier +/-hours:minutes - '([-+])' + // sign capture - '(\\d{2})' + // hours offset capture - ':(\\d{2})' + // minutes offset capture - ')' + - ')?)?)?)?' + - '$'); - - var months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]; - - var dayFromMonth = function dayFromMonth(year, month) { - var t = month > 1 ? 1 : 0; - return ( - months[month] + - Math.floor((year - 1969 + t) / 4) - - Math.floor((year - 1901 + t) / 100) + - Math.floor((year - 1601 + t) / 400) + - 365 * (year - 1970) - ); - }; - - var toUTC = function toUTC(t) { - var s = 0; - var ms = t; - if (hasSafariSignedIntBug && ms > maxSafeUnsigned32Bit) { - // work around a Safari 8/9 bug where it treats the seconds as signed - var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit; - var sToShift = Math.floor(msToShift / 1e3); - s += sToShift; - ms -= sToShift * 1e3; - } - return $Number(new NativeDate(1970, 0, 1, 0, 0, s, ms)); - }; - - // Copy any custom methods a 3rd party library may have added - for (var key in NativeDate) { - if (owns(NativeDate, key)) { - DateShim[key] = NativeDate[key]; - } - } - - // Copy "native" methods explicitly; they may be non-enumerable - defineProperties(DateShim, { - now: NativeDate.now, - UTC: NativeDate.UTC - }, true); - DateShim.prototype = NativeDate.prototype; - defineProperties(DateShim.prototype, { - constructor: DateShim - }, true); - - // Upgrade Date.parse to handle simplified ISO 8601 strings - var parseShim = function parse(string) { - var match = isoDateExpression.exec(string); - if (match) { - // parse months, days, hours, minutes, seconds, and milliseconds - // provide default values if necessary - // parse the UTC offset component - var year = $Number(match[1]), - month = $Number(match[2] || 1) - 1, - day = $Number(match[3] || 1) - 1, - hour = $Number(match[4] || 0), - minute = $Number(match[5] || 0), - second = $Number(match[6] || 0), - millisecond = Math.floor($Number(match[7] || 0) * 1000), - // When time zone is missed, local offset should be used - // (ES 5.1 bug) - // see https://bugs.ecmascript.org/show_bug.cgi?id=112 - isLocalTime = Boolean(match[4] && !match[8]), - signOffset = match[9] === '-' ? 1 : -1, - hourOffset = $Number(match[10] || 0), - minuteOffset = $Number(match[11] || 0), - result; - var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0; - if ( - hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) && - minute < 60 && second < 60 && millisecond < 1000 && - month > -1 && month < 12 && hourOffset < 24 && - minuteOffset < 60 && // detect invalid offsets - day > -1 && - day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month)) - ) { - result = ( - (dayFromMonth(year, month) + day) * 24 + - hour + - hourOffset * signOffset - ) * 60; - result = ( - (result + minute + minuteOffset * signOffset) * 60 + - second - ) * 1000 + millisecond; - if (isLocalTime) { - result = toUTC(result); - } - if (-8.64e15 <= result && result <= 8.64e15) { - return result; - } - } - return NaN; - } - return NativeDate.parse.apply(this, arguments); - }; - defineProperties(DateShim, { parse: parseShim }); - - return DateShim; - }(Date)); - /* global Date: false */ - } - - // ES5 15.9.4.4 - // http://es5.github.com/#x15.9.4.4 - if (!Date.now) { - Date.now = function now() { - return new Date().getTime(); - }; - } - - // - // Number - // ====== - // - - // ES5.1 15.7.4.5 - // http://es5.github.com/#x15.7.4.5 - var hasToFixedBugs = NumberPrototype.toFixed && ( - (0.00008).toFixed(3) !== '0.000' || - (0.9).toFixed(0) !== '1' || - (1.255).toFixed(2) !== '1.25' || - (1000000000000000128).toFixed(0) !== '1000000000000000128' - ); - - var toFixedHelpers = { - base: 1e7, - size: 6, - data: [0, 0, 0, 0, 0, 0], - multiply: function multiply(n, c) { - var i = -1; - var c2 = c; - while (++i < toFixedHelpers.size) { - c2 += n * toFixedHelpers.data[i]; - toFixedHelpers.data[i] = c2 % toFixedHelpers.base; - c2 = Math.floor(c2 / toFixedHelpers.base); - } - }, - divide: function divide(n) { - var i = toFixedHelpers.size; - var c = 0; - while (--i >= 0) { - c += toFixedHelpers.data[i]; - toFixedHelpers.data[i] = Math.floor(c / n); - c = (c % n) * toFixedHelpers.base; - } - }, - numToString: function numToString() { - var i = toFixedHelpers.size; - var s = ''; - while (--i >= 0) { - if (s !== '' || i === 0 || toFixedHelpers.data[i] !== 0) { - var t = $String(toFixedHelpers.data[i]); - if (s === '') { - s = t; - } else { - s += strSlice('0000000', 0, 7 - t.length) + t; - } - } - } - return s; - }, - pow: function pow(x, n, acc) { - return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc))); - }, - log: function log(x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } - return n; - } - }; - - var toFixedShim = function toFixed(fractionDigits) { - var f, x, s, m, e, z, j, k; - - // Test for NaN and round fractionDigits down - f = $Number(fractionDigits); - f = isActualNaN(f) ? 0 : Math.floor(f); - - if (f < 0 || f > 20) { - throw new RangeError('Number.toFixed called with invalid number of decimals'); - } - - x = $Number(this); - - if (isActualNaN(x)) { - return 'NaN'; - } - - // If it is too big or small, return the string value of the number - if (x <= -1e21 || x >= 1e21) { - return $String(x); - } - - s = ''; - - if (x < 0) { - s = '-'; - x = -x; - } - - m = '0'; - - if (x > 1e-21) { - // 1e-21 < x < 1e21 - // -70 < log2(x) < 70 - e = toFixedHelpers.log(x * toFixedHelpers.pow(2, 69, 1)) - 69; - z = (e < 0 ? x * toFixedHelpers.pow(2, -e, 1) : x / toFixedHelpers.pow(2, e, 1)); - z *= 0x10000000000000; // Math.pow(2, 52); - e = 52 - e; - - // -18 < e < 122 - // x = z / 2 ^ e - if (e > 0) { - toFixedHelpers.multiply(0, z); - j = f; - - while (j >= 7) { - toFixedHelpers.multiply(1e7, 0); - j -= 7; - } - - toFixedHelpers.multiply(toFixedHelpers.pow(10, j, 1), 0); - j = e - 1; - - while (j >= 23) { - toFixedHelpers.divide(1 << 23); - j -= 23; - } - - toFixedHelpers.divide(1 << j); - toFixedHelpers.multiply(1, 1); - toFixedHelpers.divide(2); - m = toFixedHelpers.numToString(); - } else { - toFixedHelpers.multiply(0, z); - toFixedHelpers.multiply(1 << (-e), 0); - m = toFixedHelpers.numToString() + strSlice('0.00000000000000000000', 2, 2 + f); - } - } - - if (f > 0) { - k = m.length; - - if (k <= f) { - m = s + strSlice('0.0000000000000000000', 0, f - k + 2) + m; - } else { - m = s + strSlice(m, 0, k - f) + '.' + strSlice(m, k - f); - } - } else { - m = s + m; - } - - return m; - }; - defineProperties(NumberPrototype, { toFixed: toFixedShim }, hasToFixedBugs); - - var hasToPrecisionUndefinedBug = (function () { - try { - return 1.0.toPrecision(undefined) === '1'; - } catch (e) { - return true; - } - }()); - var originalToPrecision = NumberPrototype.toPrecision; - defineProperties(NumberPrototype, { - toPrecision: function toPrecision(precision) { - return typeof precision === 'undefined' ? originalToPrecision.call(this) : originalToPrecision.call(this, precision); - } - }, hasToPrecisionUndefinedBug); - - // - // String - // ====== - // - - // ES5 15.5.4.14 - // http://es5.github.com/#x15.5.4.14 - - // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers] - // Many browsers do not split properly with regular expressions or they - // do not perform the split correctly under obscure conditions. - // See http://blog.stevenlevithan.com/archives/cross-browser-split - // I've tested in many browsers and this seems to cover the deviant ones: - // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""] - // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""] - // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not - // [undefined, "t", undefined, "e", ...] - // ''.split(/.?/) should be [], not [""] - // '.'.split(/()()/) should be ["."], not ["", "", "."] - - if ( - 'ab'.split(/(?:ab)*/).length !== 2 || - '.'.split(/(.?)(.?)/).length !== 4 || - 'tesst'.split(/(s)*/)[1] === 't' || - 'test'.split(/(?:)/, -1).length !== 4 || - ''.split(/.?/).length || - '.'.split(/()()/).length > 1 - ) { - (function () { - var compliantExecNpcg = typeof (/()??/).exec('')[1] === 'undefined'; // NPCG: nonparticipating capturing group - var maxSafe32BitInt = Math.pow(2, 32) - 1; - - StringPrototype.split = function (separator, limit) { - var string = String(this); - if (typeof separator === 'undefined' && limit === 0) { - return []; - } - - // If `separator` is not a regex, use native split - if (!isRegex(separator)) { - return strSplit(this, separator, limit); - } - - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + // in ES6 - (separator.sticky ? 'y' : ''), // Firefox 3+ and ES6 - lastLastIndex = 0, - // Make `global` and avoid `lastIndex` issues by working with a copy - separator2, match, lastIndex, lastLength; - var separatorCopy = new RegExp(separator.source, flags + 'g'); - if (!compliantExecNpcg) { - // Doesn't need flags gy, but they don't hurt - separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); - } - /* Values for `limit`, per the spec: - * If undefined: 4294967295 // maxSafe32BitInt - * If 0, Infinity, or NaN: 0 - * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; - * If negative number: 4294967296 - Math.floor(Math.abs(limit)) - * If other: Type-convert, then use the above rules - */ - var splitLimit = typeof limit === 'undefined' ? maxSafe32BitInt : ES.ToUint32(limit); - match = separatorCopy.exec(string); - while (match) { - // `separatorCopy.lastIndex` is not reliable cross-browser - lastIndex = match.index + match[0].length; - if (lastIndex > lastLastIndex) { - pushCall(output, strSlice(string, lastLastIndex, match.index)); - // Fix browsers whose `exec` methods don't consistently return `undefined` for - // nonparticipating capturing groups - if (!compliantExecNpcg && match.length > 1) { - /* eslint-disable no-loop-func */ - match[0].replace(separator2, function () { - for (var i = 1; i < arguments.length - 2; i++) { - if (typeof arguments[i] === 'undefined') { - match[i] = void 0; - } - } - }); - /* eslint-enable no-loop-func */ - } - if (match.length > 1 && match.index < string.length) { - array_push.apply(output, arraySlice(match, 1)); - } - lastLength = match[0].length; - lastLastIndex = lastIndex; - if (output.length >= splitLimit) { - break; - } - } - if (separatorCopy.lastIndex === match.index) { - separatorCopy.lastIndex++; // Avoid an infinite loop - } - match = separatorCopy.exec(string); - } - if (lastLastIndex === string.length) { - if (lastLength || !separatorCopy.test('')) { - pushCall(output, ''); - } - } else { - pushCall(output, strSlice(string, lastLastIndex)); - } - return output.length > splitLimit ? arraySlice(output, 0, splitLimit) : output; - }; - }()); - - // [bugfix, chrome] - // If separator is undefined, then the result array contains just one String, - // which is the this value (converted to a String). If limit is not undefined, - // then the output array is truncated so that it contains no more than limit - // elements. - // "0".split(undefined, 0) -> [] - } else if ('0'.split(void 0, 0).length) { - StringPrototype.split = function split(separator, limit) { - if (typeof separator === 'undefined' && limit === 0) { - return []; - } - return strSplit(this, separator, limit); - }; - } - - var str_replace = StringPrototype.replace; - var replaceReportsGroupsCorrectly = (function () { - var groups = []; - 'x'.replace(/x(.)?/g, function (match, group) { - pushCall(groups, group); - }); - return groups.length === 1 && typeof groups[0] === 'undefined'; - }()); - - if (!replaceReportsGroupsCorrectly) { - StringPrototype.replace = function replace(searchValue, replaceValue) { - var isFn = isCallable(replaceValue); - var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source); - if (!isFn || !hasCapturingGroups) { - return str_replace.call(this, searchValue, replaceValue); - } else { - var wrappedReplaceValue = function (match) { - var length = arguments.length; - var originalLastIndex = searchValue.lastIndex; - searchValue.lastIndex = 0; - var args = searchValue.exec(match) || []; - searchValue.lastIndex = originalLastIndex; - pushCall(args, arguments[length - 2], arguments[length - 1]); - return replaceValue.apply(this, args); - }; - return str_replace.call(this, searchValue, wrappedReplaceValue); - } - }; - } - - // ECMA-262, 3rd B.2.3 - // Not an ECMAScript standard, although ECMAScript 3rd Edition has a - // non-normative section suggesting uniform semantics and it should be - // normalized across all browsers - // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE - var string_substr = StringPrototype.substr; - var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b'; - defineProperties(StringPrototype, { - substr: function substr(start, length) { - var normalizedStart = start; - if (start < 0) { - normalizedStart = max(this.length + start, 0); - } - return string_substr.call(this, normalizedStart, length); - } - }, hasNegativeSubstrBug); - - // ES5 15.5.4.20 - // whitespace from: http://es5.github.io/#x15.5.4.20 - var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + - '\u2029\uFEFF'; - var zeroWidth = '\u200b'; - var wsRegexChars = '[' + ws + ']'; - var trimBeginRegexp = new RegExp('^' + wsRegexChars + wsRegexChars + '*'); - var trimEndRegexp = new RegExp(wsRegexChars + wsRegexChars + '*$'); - var hasTrimWhitespaceBug = StringPrototype.trim && (ws.trim() || !zeroWidth.trim()); - defineProperties(StringPrototype, { - // http://blog.stevenlevithan.com/archives/faster-trim-javascript - // http://perfectionkills.com/whitespace-deviations/ - trim: function trim() { - if (typeof this === 'undefined' || this === null) { - throw new TypeError("can't convert " + this + ' to object'); - } - return $String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, ''); - } - }, hasTrimWhitespaceBug); - var trim = call.bind(String.prototype.trim); - - var hasLastIndexBug = StringPrototype.lastIndexOf && 'abcあい'.lastIndexOf('あい', 2) !== -1; - defineProperties(StringPrototype, { - lastIndexOf: function lastIndexOf(searchString) { - if (typeof this === 'undefined' || this === null) { - throw new TypeError("can't convert " + this + ' to object'); - } - var S = $String(this); - var searchStr = $String(searchString); - var numPos = arguments.length > 1 ? $Number(arguments[1]) : NaN; - var pos = isActualNaN(numPos) ? Infinity : ES.ToInteger(numPos); - var start = min(max(pos, 0), S.length); - var searchLen = searchStr.length; - var k = start + searchLen; - while (k > 0) { - k = max(0, k - searchLen); - var index = strIndexOf(strSlice(S, k, start + searchLen), searchStr); - if (index !== -1) { - return k + index; - } - } - return -1; - } - }, hasLastIndexBug); - - var originalLastIndexOf = StringPrototype.lastIndexOf; - defineProperties(StringPrototype, { - lastIndexOf: function lastIndexOf(searchString) { - return originalLastIndexOf.apply(this, arguments); - } - }, StringPrototype.lastIndexOf.length !== 1); - - // ES-5 15.1.2.2 - /* eslint-disable radix */ - if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) { - /* eslint-enable radix */ - /* global parseInt: true */ - parseInt = (function (origParseInt) { - var hexRegex = /^[\-+]?0[xX]/; - return function parseInt(str, radix) { - var string = trim(String(str)); - var defaultedRadix = $Number(radix) || (hexRegex.test(string) ? 16 : 10); - return origParseInt(string, defaultedRadix); - }; - }(parseInt)); - } - - // https://es5.github.io/#x15.1.2.3 - if (1 / parseFloat('-0') !== -Infinity) { - /* global parseFloat: true */ - parseFloat = (function (origParseFloat) { - return function parseFloat(string) { - var inputString = trim(String(string)); - var result = origParseFloat(inputString); - return result === 0 && strSlice(inputString, 0, 1) === '-' ? -0 : result; - }; - }(parseFloat)); - } - - if (String(new RangeError('test')) !== 'RangeError: test') { - var errorToStringShim = function toString() { - if (typeof this === 'undefined' || this === null) { - throw new TypeError("can't convert " + this + ' to object'); - } - var name = this.name; - if (typeof name === 'undefined') { - name = 'Error'; - } else if (typeof name !== 'string') { - name = $String(name); - } - var msg = this.message; - if (typeof msg === 'undefined') { - msg = ''; - } else if (typeof msg !== 'string') { - msg = $String(msg); - } - if (!name) { - return msg; - } - if (!msg) { - return name; - } - return name + ': ' + msg; - }; - // can't use defineProperties here because of toString enumeration issue in IE <= 8 - Error.prototype.toString = errorToStringShim; - } - - if (supportsDescriptors) { - var ensureNonEnumerable = function (obj, prop) { - if (isEnum(obj, prop)) { - var desc = Object.getOwnPropertyDescriptor(obj, prop); - if (desc.configurable) { - desc.enumerable = false; - Object.defineProperty(obj, prop, desc); - } - } - }; - ensureNonEnumerable(Error.prototype, 'message'); - if (Error.prototype.message !== '') { - Error.prototype.message = ''; - } - ensureNonEnumerable(Error.prototype, 'name'); - } - - if (String(/a/mig) !== '/a/gim') { - var regexToString = function toString() { - var str = '/' + this.source + '/'; - if (this.global) { - str += 'g'; - } - if (this.ignoreCase) { - str += 'i'; - } - if (this.multiline) { - str += 'm'; - } - return str; - }; - // can't use defineProperties here because of toString enumeration issue in IE <= 8 - RegExp.prototype.toString = regexToString; - } -})); - -'use strict'; -/*jslint eqeq: true*/ - -Handlebars.registerHelper('sanitize', function (text) { - var result; - - if (text === undefined) { return ''; } - - result = sanitizeHtml(text, { - allowedTags: [ 'div', 'span', 'b', 'i', 'em', 'strong', 'a', 'br', 'table', 'tbody', 'tr', 'th', 'td' ], - allowedAttributes: { - 'div': [ 'class' ], - 'span': [ 'class' ], - 'table': [ 'class' ], - 'td': [ 'class' ], - 'th': [ 'colspan' ], - 'a': [ 'href' ] - } - }); - - return new Handlebars.SafeString(result); -}); - -Handlebars.registerHelper('renderTextParam', function(param) { - var result, type = 'text', idAtt = ''; - var paramType = param.type || param.schema && param.schema.type || ''; - var isArray = paramType.toLowerCase() === 'array' || param.allowMultiple; - var defaultValue = isArray && Array.isArray(param.default) ? param.default.join('\n') : param.default; - var name = Handlebars.Utils.escapeExpression(param.name); - var valueId = Handlebars.Utils.escapeExpression(param.valueId); - paramType = Handlebars.Utils.escapeExpression(paramType); - - var dataVendorExtensions = Object.keys(param).filter(function(property) { - // filter X-data- properties - return property.match(/^X-data-/i) !== null; - }).reduce(function(result, property) { - // remove X- from property name, so it results in html attributes like data-foo='bar' - return result += ' ' + property.substring(2, property.length) + '=\'' + param[property] + '\''; - }, ''); - - if(param.format && param.format === 'password') { - type = 'password'; - } - - if(valueId) { - idAtt = ' id=\'' + valueId + '\''; - } - - if (defaultValue) { - defaultValue = sanitizeHtml(defaultValue); - } else { - defaultValue = ''; - } - - if(isArray) { - result = ''; - } else { - var parameterClass = 'parameter'; - if(param.required) { - parameterClass += ' required'; - } - result = ''; - } - return new Handlebars.SafeString(result); -}); - -Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { - - switch (operator) { - case '==': - return (v1 == v2) ? options.fn(this) : options.inverse(this); - case '===': - return (v1 === v2) ? options.fn(this) : options.inverse(this); - case '<': - return (v1 < v2) ? options.fn(this) : options.inverse(this); - case '<=': - return (v1 <= v2) ? options.fn(this) : options.inverse(this); - case '>': - return (v1 > v2) ? options.fn(this) : options.inverse(this); - case '>=': - return (v1 >= v2) ? options.fn(this) : options.inverse(this); - case '&&': - return (v1 && v2) ? options.fn(this) : options.inverse(this); - case '||': - return (v1 || v2) ? options.fn(this) : options.inverse(this); - default: - return options.inverse(this); - } -}); - -Handlebars.registerHelper('escape', function (value) { - var text = Handlebars.Utils.escapeExpression(value); - - return new Handlebars.SafeString(text); -}); - -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.sanitizeHtml=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o=0){globRegex.push(quoteRegexp(name).replace(/\\\*/g,".*"))}else{allowedAttributesMap[tag].push(name)}});allowedAttributesGlobMap[tag]=new RegExp("^("+globRegex.join("|")+")$")})}var allowedClassesMap={};each(options.allowedClasses,function(classes,tag){if(allowedAttributesMap){if(!has(allowedAttributesMap,tag)){allowedAttributesMap[tag]=[]}allowedAttributesMap[tag].push("class")}allowedClassesMap[tag]=classes});var transformTagsMap={};var transformTagsAll;each(options.transformTags,function(transform,tag){var transFun;if(typeof transform==="function"){transFun=transform}else if(typeof transform==="string"){transFun=sanitizeHtml.simpleTransform(transform)}if(tag==="*"){transformTagsAll=transFun}else{transformTagsMap[tag]=transFun}});var depth=0;var stack=[];var skipMap={};var transformMap={};var skipText=false;var skipTextDepth=0;var parser=new htmlparser.Parser({onopentag:function(name,attribs){if(skipText){skipTextDepth++;return}var frame=new Frame(name,attribs);stack.push(frame);var skip=false;var hasText=frame.text?true:false;var transformedTag;if(has(transformTagsMap,name)){transformedTag=transformTagsMap[name](name,attribs);frame.attribs=attribs=transformedTag.attribs;if(transformedTag.text!==undefined){frame.innerText=transformedTag.text}if(name!==transformedTag.tagName){frame.name=name=transformedTag.tagName;transformMap[depth]=transformedTag.tagName}}if(transformTagsAll){transformedTag=transformTagsAll(name,attribs);frame.attribs=attribs=transformedTag.attribs;if(name!==transformedTag.tagName){frame.name=name=transformedTag.tagName;transformMap[depth]=transformedTag.tagName}}if(options.allowedTags&&options.allowedTags.indexOf(name)===-1){skip=true;if(nonTextTagsArray.indexOf(name)!==-1){skipText=true;skipTextDepth=1}skipMap[depth]=true}depth++;if(skip){return}result+="<"+name;if(!allowedAttributesMap||has(allowedAttributesMap,name)||allowedAttributesMap["*"]){each(attribs,function(value,a){if(!allowedAttributesMap||has(allowedAttributesMap,name)&&allowedAttributesMap[name].indexOf(a)!==-1||allowedAttributesMap["*"]&&allowedAttributesMap["*"].indexOf(a)!==-1||has(allowedAttributesGlobMap,name)&&allowedAttributesGlobMap[name].test(a)||allowedAttributesGlobMap["*"]&&allowedAttributesGlobMap["*"].test(a)){if(a==="href"||a==="src"){if(naughtyHref(name,value)){delete frame.attribs[a];return}}if(a==="class"){value=filterClasses(value,allowedClassesMap[name]);if(!value.length){delete frame.attribs[a];return}}result+=" "+a;if(value.length){result+='="'+escapeHtml(value)+'"'}}else{delete frame.attribs[a]}})}if(options.selfClosing.indexOf(name)!==-1){result+=" />"}else{result+=">";if(frame.innerText&&!hasText&&!options.textFilter){result+=frame.innerText}}},ontext:function(text){if(skipText){return}var lastFrame=stack[stack.length-1];var tag;if(lastFrame){tag=lastFrame.tag;text=lastFrame.innerText!==undefined?lastFrame.innerText:text}if(tag==="script"||tag==="style"){result+=text}else{var escaped=escapeHtml(text);if(options.textFilter){result+=options.textFilter(escaped)}else{result+=escaped}}if(stack.length){var frame=stack[stack.length-1];frame.text+=text}},onclosetag:function(name){if(skipText){skipTextDepth--;if(!skipTextDepth){skipText=false}else{return}}var frame=stack.pop();if(!frame){return}skipText=false;depth--;if(skipMap[depth]){delete skipMap[depth];frame.updateParentNodeText();return}if(transformMap[depth]){name=transformMap[depth];delete transformMap[depth]}if(options.exclusiveFilter&&options.exclusiveFilter(frame)){result=result.substr(0,frame.tagPosition);return}frame.updateParentNodeText();if(options.selfClosing.indexOf(name)!==-1){return}result+=""}},options.parser);parser.write(html);parser.end();return result;function escapeHtml(s){if(typeof s!=="string"){s=s+""}return s.replace(/\&/g,"&").replace(//g,">").replace(/\"/g,""")}function naughtyHref(name,href){href=href.replace(/[\x00-\x20]+/g,"");href=href.replace(/<\!\-\-.*?\-\-\>/g,"");var matches=href.match(/^([a-zA-Z]+)\:/);if(!matches){return false}var scheme=matches[1].toLowerCase();if(has(options.allowedSchemesByTag,name)){return options.allowedSchemesByTag[name].indexOf(scheme)===-1}return!options.allowedSchemes||options.allowedSchemes.indexOf(scheme)===-1}function filterClasses(classes,allowed){if(!allowed){return classes}classes=classes.split(/\s+/);return classes.filter(function(clss){return allowed.indexOf(clss)!==-1}).join(" ")}}var htmlParserDefaults={decodeEntities:true};sanitizeHtml.defaults={allowedTags:["h3","h4","h5","h6","blockquote","p","a","ul","ol","nl","li","b","i","strong","em","strike","code","hr","br","div","table","thead","caption","tbody","tr","th","td","pre"],allowedAttributes:{a:["href","name","target"],img:["src"]},selfClosing:["img","br","hr","area","base","basefont","input","link","meta"],allowedSchemes:["http","https","ftp","mailto"],allowedSchemesByTag:{}};sanitizeHtml.simpleTransform=function(newTagName,newAttribs,merge){merge=merge===undefined?true:merge;newAttribs=newAttribs||{};return function(tagName,attribs){var attrib;if(merge){for(attrib in newAttribs){attribs[attrib]=newAttribs[attrib]}}else{attribs=newAttribs}return{tagName:newTagName,attribs:attribs}}}},{htmlparser2:36,"regexp-quote":54,xtend:58}],2:[function(require,module,exports){"use strict";exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;function init(){var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}placeHolders=b64[len-2]==="="?2:b64[len-1]==="="?1:0;arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],3:[function(require,module,exports){},{}],4:[function(require,module,exports){(function(global){"use strict";var buffer=require("buffer");var Buffer=buffer.Buffer;var SlowBuffer=buffer.SlowBuffer;var MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function alloc(size,fill,encoding){if(typeof Buffer.alloc==="function"){return Buffer.alloc(size,fill,encoding)}if(typeof encoding==="number"){throw new TypeError("encoding must not be number")}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>MAX_LEN){throw new RangeError("size is too large")}var enc=encoding;var _fill=fill;if(_fill===undefined){enc=undefined;_fill=0}var buf=new Buffer(size);if(typeof _fill==="string"){var fillBuf=new Buffer(_fill,enc);var flen=fillBuf.length;var i=-1;while(++iMAX_LEN){throw new RangeError("size is too large")}return new Buffer(size)};exports.from=function from(value,encodingOrOffset,length){if(typeof Buffer.from==="function"&&(!global.Uint8Array||Uint8Array.from!==Buffer.from)){return Buffer.from(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(typeof value==="string"){return new Buffer(value,encodingOrOffset)}if(typeof ArrayBuffer!=="undefined"&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(arguments.length===1){return new Buffer(value)}if(typeof offset==="undefined"){offset=0}var len=length;if(typeof len==="undefined"){len=value.byteLength-offset}if(offset>=value.byteLength){throw new RangeError("'offset' is out of bounds")}if(len>value.byteLength-offset){throw new RangeError("'length' is out of bounds")}return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);value.copy(out,0,0,value.length);return out}if(value){if(Array.isArray(value)||typeof ArrayBuffer!=="undefined"&&value.buffer instanceof ArrayBuffer||"length"in value){return new Buffer(value)}if(value.type==="Buffer"&&Array.isArray(value.data)){return new Buffer(value.data)}}throw new TypeError("First argument must be a string, Buffer, "+"ArrayBuffer, Array, or array-like object.")};exports.allocUnsafeSlow=function allocUnsafeSlow(size){if(typeof Buffer.allocUnsafeSlow==="function"){return Buffer.allocUnsafeSlow(size)}if(typeof size!=="number"){throw new TypeError("size must be a number")}if(size>=MAX_LEN){throw new RangeError("size is too large")}return new SlowBuffer(size)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{buffer:5}],5:[function(require,module,exports){(function(global){"use strict";var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("isarray");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42&&typeof arr.subarray==="function"&&arr.subarray(1,1).byteLength===0}catch(e){return false}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength().toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError("Arguments must be Buffers")}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError("Argument must be a Buffer")}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(isNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length); -var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&255;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8}else{objectWriteUInt16(this,value,offset,true)}return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&255}else{objectWriteUInt16(this,value,offset,false)}return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else{objectWriteUInt32(this,value,offset,true)}return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255}else{objectWriteUInt32(this,value,offset,false)}return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isnan(val){return val!==val}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"base64-js":2,ieee754:37,isarray:40}],6:[function(require,module,exports){(function(Buffer){function isArray(arg){if(Array.isArray){return Array.isArray(arg)}return objectToString(arg)==="[object Array]"}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=Buffer.isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,{isBuffer:require("../../is-buffer/index.js")})},{"../../is-buffer/index.js":39}],7:[function(require,module,exports){var ElementType=require("domelementtype");var entities=require("entities");var booleanAttributes={__proto__:null,allowfullscreen:true,async:true,autofocus:true,autoplay:true,checked:true,controls:true,default:true,defer:true,disabled:true,hidden:true,ismap:true,loop:true,multiple:true,muted:true,open:true,readonly:true,required:true,reversed:true,scoped:true,seamless:true,selected:true,typemustmatch:true};var unencodedElements={__proto__:null,style:true,script:true,xmp:true,iframe:true,noembed:true,noframes:true,plaintext:true,noscript:true};function formatAttrs(attributes,opts){if(!attributes)return;var output="",value;for(var key in attributes){value=attributes[key];if(output){output+=" "}if(!value&&booleanAttributes[key]){output+=key}else{output+=key+'="'+(opts.decodeEntities?entities.encodeXML(value):value)+'"'}}return output}var singleTag={__proto__:null,area:true,base:true,basefont:true,br:true,col:true,command:true,embed:true,frame:true,hr:true,img:true,input:true,isindex:true,keygen:true,link:true,meta:true,param:true,source:true,track:true,wbr:true};var render=module.exports=function(dom,opts){if(!Array.isArray(dom)&&!dom.cheerio)dom=[dom];opts=opts||{};var output="";for(var i=0;i"}else{tag+=">";if(elem.children){tag+=render(elem.children,opts)}if(!singleTag[elem.name]||opts.xmlMode){tag+=""}}return tag}function renderDirective(elem){return"<"+elem.data+">"}function renderText(elem,opts){var data=elem.data||"";if(opts.decodeEntities&&!(elem.parent&&elem.parent.name in unencodedElements)){data=entities.encodeXML(data)}return data}function renderCdata(elem){return""}function renderComment(elem){return""}},{domelementtype:8,entities:20}],8:[function(require,module,exports){module.exports={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag",CDATA:"cdata",isTag:function(elem){return elem.type==="tag"||elem.type==="script"||elem.type==="style"}}},{}],9:[function(require,module,exports){module.exports={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag",CDATA:"cdata",Doctype:"doctype",isTag:function(elem){return elem.type==="tag"||elem.type==="script"||elem.type==="style"}}},{}],10:[function(require,module,exports){var ElementType=require("domelementtype");var re_whitespace=/\s+/g;var NodePrototype=require("./lib/node");var ElementPrototype=require("./lib/element");function DomHandler(callback,options,elementCB){if(typeof callback==="object"){elementCB=options;options=callback;callback=null}else if(typeof options==="function"){elementCB=options;options=defaultOpts}this._callback=callback;this._options=options||defaultOpts;this._elementCB=elementCB;this.dom=[];this._done=false;this._tagStack=[];this._parser=this._parser||null}var defaultOpts={normalizeWhitespace:false,withStartIndices:false};DomHandler.prototype.onparserinit=function(parser){this._parser=parser};DomHandler.prototype.onreset=function(){DomHandler.call(this,this._callback,this._options,this._elementCB)};DomHandler.prototype.onend=function(){if(this._done)return;this._done=true;this._parser=null;this._handleCallback(null)};DomHandler.prototype._handleCallback=DomHandler.prototype.onerror=function(error){if(typeof this._callback==="function"){this._callback(error,this.dom)}else{if(error)throw error}};DomHandler.prototype.onclosetag=function(){var elem=this._tagStack.pop();if(this._elementCB)this._elementCB(elem)};DomHandler.prototype._addDomElement=function(element){var parent=this._tagStack[this._tagStack.length-1];var siblings=parent?parent.children:this.dom;var previousSibling=siblings[siblings.length-1];element.next=null;if(this._options.withStartIndices){element.startIndex=this._parser.startIndex}if(this._options.withDomLvl1){element.__proto__=element.type==="tag"?ElementPrototype:NodePrototype}if(previousSibling){element.prev=previousSibling;previousSibling.next=element}else{element.prev=null}siblings.push(element);element.parent=parent||null};DomHandler.prototype.onopentag=function(name,attribs){var element={type:name==="script"?ElementType.Script:name==="style"?ElementType.Style:ElementType.Tag,name:name,attribs:attribs,children:[]};this._addDomElement(element);this._tagStack.push(element)};DomHandler.prototype.ontext=function(data){var normalize=this._options.normalizeWhitespace||this._options.ignoreWhitespace;var lastTag;if(!this._tagStack.length&&this.dom.length&&(lastTag=this.dom[this.dom.length-1]).type===ElementType.Text){if(normalize){lastTag.data=(lastTag.data+data).replace(re_whitespace," ")}else{lastTag.data+=data}}else{if(this._tagStack.length&&(lastTag=this._tagStack[this._tagStack.length-1])&&(lastTag=lastTag.children[lastTag.children.length-1])&&lastTag.type===ElementType.Text){if(normalize){lastTag.data=(lastTag.data+data).replace(re_whitespace," ")}else{lastTag.data+=data}}else{if(normalize){data=data.replace(re_whitespace," ")}this._addDomElement({data:data,type:ElementType.Text})}}};DomHandler.prototype.oncomment=function(data){var lastTag=this._tagStack[this._tagStack.length-1];if(lastTag&&lastTag.type===ElementType.Comment){lastTag.data+=data;return}var element={data:data,type:ElementType.Comment};this._addDomElement(element);this._tagStack.push(element)};DomHandler.prototype.oncdatastart=function(){var element={children:[{data:"",type:ElementType.Text}],type:ElementType.CDATA};this._addDomElement(element);this._tagStack.push(element)};DomHandler.prototype.oncommentend=DomHandler.prototype.oncdataend=function(){this._tagStack.pop()};DomHandler.prototype.onprocessinginstruction=function(name,data){this._addDomElement({name:name,data:data,type:ElementType.Directive})};module.exports=DomHandler},{"./lib/element":11,"./lib/node":12,domelementtype:9}],11:[function(require,module,exports){var NodePrototype=require("./node");var ElementPrototype=module.exports=Object.create(NodePrototype);var domLvl1={tagName:"name"};Object.keys(domLvl1).forEach(function(key){var shorthand=domLvl1[key];Object.defineProperty(ElementPrototype,key,{get:function(){return this[shorthand]||null},set:function(val){this[shorthand]=val;return val}})})},{"./node":12}],12:[function(require,module,exports){var NodePrototype=module.exports={get firstChild(){var children=this.children;return children&&children[0]||null},get lastChild(){var children=this.children;return children&&children[children.length-1]||null},get nodeType(){return nodeTypes[this.type]||nodeTypes.element}};var domLvl1={tagName:"name",childNodes:"children",parentNode:"parent",previousSibling:"prev",nextSibling:"next",nodeValue:"data"};var nodeTypes={element:1,text:3,cdata:4,comment:8};Object.keys(domLvl1).forEach(function(key){var shorthand=domLvl1[key];Object.defineProperty(NodePrototype,key,{get:function(){return this[shorthand]||null},set:function(val){this[shorthand]=val;return val}})})},{}],13:[function(require,module,exports){var DomUtils=module.exports;[require("./lib/stringify"),require("./lib/traversal"),require("./lib/manipulation"),require("./lib/querying"),require("./lib/legacy"),require("./lib/helpers")].forEach(function(ext){Object.keys(ext).forEach(function(key){DomUtils[key]=ext[key].bind(DomUtils)})})},{"./lib/helpers":14,"./lib/legacy":15,"./lib/manipulation":16,"./lib/querying":17,"./lib/stringify":18,"./lib/traversal":19}],14:[function(require,module,exports){exports.removeSubsets=function(nodes){var idx=nodes.length,node,ancestor,replace;while(--idx>-1){node=ancestor=nodes[idx];nodes[idx]=null;replace=true;while(ancestor){if(nodes.indexOf(ancestor)>-1){replace=false;nodes.splice(idx,1);break}ancestor=ancestor.parent}if(replace){nodes[idx]=node}}return nodes};var POSITION={DISCONNECTED:1,PRECEDING:2,FOLLOWING:4,CONTAINS:8,CONTAINED_BY:16};var comparePos=exports.compareDocumentPosition=function(nodeA,nodeB){var aParents=[];var bParents=[];var current,sharedParent,siblings,aSibling,bSibling,idx;if(nodeA===nodeB){return 0}current=nodeA;while(current){aParents.unshift(current);current=current.parent}current=nodeB;while(current){bParents.unshift(current);current=current.parent}idx=0;while(aParents[idx]===bParents[idx]){idx++}if(idx===0){return POSITION.DISCONNECTED}sharedParent=aParents[idx-1];siblings=sharedParent.children;aSibling=aParents[idx];bSibling=bParents[idx];if(siblings.indexOf(aSibling)>siblings.indexOf(bSibling)){if(sharedParent===nodeB){return POSITION.FOLLOWING|POSITION.CONTAINED_BY}return POSITION.FOLLOWING}else{if(sharedParent===nodeA){return POSITION.PRECEDING|POSITION.CONTAINS}return POSITION.PRECEDING}};exports.uniqueSort=function(nodes){var idx=nodes.length,node,position;nodes=nodes.slice();while(--idx>-1){node=nodes[idx];position=nodes.indexOf(node);if(position>-1&&position0){childs=find(test,childs,recurse,limit);result=result.concat(childs);limit-=childs.length;if(limit<=0)break}}return result}function findOneChild(test,elems){for(var i=0,l=elems.length;i0){elem=findOne(test,elems[i].children)}}return elem}function existsOne(test,elems){for(var i=0,l=elems.length;i0&&existsOne(test,elems[i].children))){return true}}return false}function findAll(test,elems){var result=[];for(var i=0,j=elems.length;i0){result=result.concat(findAll(test,elems[i].children))}}return result}},{domelementtype:9}],18:[function(require,module,exports){var ElementType=require("domelementtype"),getOuterHTML=require("dom-serializer"),isTag=ElementType.isTag;module.exports={getInnerHTML:getInnerHTML,getOuterHTML:getOuterHTML,getText:getText};function getInnerHTML(elem,opts){return elem.children?elem.children.map(function(elem){return getOuterHTML(elem,opts)}).join(""):""}function getText(elem){if(Array.isArray(elem))return elem.map(getText).join("");if(isTag(elem)||elem.type===ElementType.CDATA)return getText(elem.children);if(elem.type===ElementType.Text)return elem.data;return""}},{"dom-serializer":7,domelementtype:9}],19:[function(require,module,exports){var getChildren=exports.getChildren=function(elem){return elem.children};var getParent=exports.getParent=function(elem){return elem.parent};exports.getSiblings=function(elem){var parent=getParent(elem);return parent?getChildren(parent):[elem]};exports.getAttributeValue=function(elem,name){return elem.attribs&&elem.attribs[name]};exports.hasAttrib=function(elem,name){return!!elem.attribs&&hasOwnProperty.call(elem.attribs,name)};exports.getName=function(elem){return elem.name}},{}],20:[function(require,module,exports){var encode=require("./lib/encode.js"),decode=require("./lib/decode.js");exports.decode=function(data,level){return(!level||level<=0?decode.XML:decode.HTML)(data)};exports.decodeStrict=function(data,level){return(!level||level<=0?decode.XML:decode.HTMLStrict)(data)};exports.encode=function(data,level){return(!level||level<=0?encode.XML:encode.HTML)(data)};exports.encodeXML=encode.XML;exports.encodeHTML4=exports.encodeHTML5=exports.encodeHTML=encode.HTML;exports.decodeXML=exports.decodeXMLStrict=decode.XML;exports.decodeHTML4=exports.decodeHTML5=exports.decodeHTML=decode.HTML;exports.decodeHTML4Strict=exports.decodeHTML5Strict=exports.decodeHTMLStrict=decode.HTMLStrict;exports.escape=encode.escape},{"./lib/decode.js":21,"./lib/encode.js":23}],21:[function(require,module,exports){var entityMap=require("../maps/entities.json"),legacyMap=require("../maps/legacy.json"),xmlMap=require("../maps/xml.json"),decodeCodePoint=require("./decode_codepoint.js");var decodeXMLStrict=getStrictDecoder(xmlMap),decodeHTMLStrict=getStrictDecoder(entityMap);function getStrictDecoder(map){var keys=Object.keys(map).join("|"),replace=getReplacer(map);keys+="|#[xX][\\da-fA-F]+|#\\d+";var re=new RegExp("&(?:"+keys+");","g");return function(str){return String(str).replace(re,replace)}}var decodeHTML=function(){var legacy=Object.keys(legacyMap).sort(sorter);var keys=Object.keys(entityMap).sort(sorter);for(var i=0,j=0;i=55296&&codePoint<=57343||codePoint>1114111){return"�"}if(codePoint in decodeMap){codePoint=decodeMap[codePoint]}var output="";if(codePoint>65535){codePoint-=65536;output+=String.fromCharCode(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}output+=String.fromCharCode(codePoint);return output}},{"../maps/decode.json":24}],23:[function(require,module,exports){var inverseXML=getInverseObj(require("../maps/xml.json")),xmlReplacer=getInverseReplacer(inverseXML);exports.XML=getInverse(inverseXML,xmlReplacer);var inverseHTML=getInverseObj(require("../maps/entities.json")),htmlReplacer=getInverseReplacer(inverseHTML);exports.HTML=getInverse(inverseHTML,htmlReplacer);function getInverseObj(obj){return Object.keys(obj).sort().reduce(function(inverse,name){inverse[obj[name]]="&"+name+";";return inverse},{})}function getInverseReplacer(inverse){var single=[],multiple=[];Object.keys(inverse).forEach(function(k){if(k.length===1){single.push("\\"+k)}else{multiple.push(k)}});multiple.unshift("["+single.join("")+"]");return new RegExp(multiple.join("|"),"g")}var re_nonASCII=/[^\0-\x7F]/g,re_astralSymbols=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;function singleCharReplacer(c){return"&#x"+c.charCodeAt(0).toString(16).toUpperCase()+";"}function astralReplacer(c){var high=c.charCodeAt(0);var low=c.charCodeAt(1);var codePoint=(high-55296)*1024+low-56320+65536;return"&#x"+codePoint.toString(16).toUpperCase()+";"}function getInverse(inverse,re){function func(name){return inverse[name]}return function(data){return data.replace(re,func).replace(re_astralSymbols,astralReplacer).replace(re_nonASCII,singleCharReplacer)}}var re_xmlChars=getInverseReplacer(inverseXML);function escapeXML(data){return data.replace(re_xmlChars,singleCharReplacer).replace(re_astralSymbols,astralReplacer).replace(re_nonASCII,singleCharReplacer)}exports.escape=escapeXML},{"../maps/entities.json":25,"../maps/xml.json":27}],24:[function(require,module,exports){module.exports={0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376}},{}],25:[function(require,module,exports){module.exports={Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",amp:"&",AMP:"&",andand:"⩕",And:"⩓",and:"∧",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angmsd:"∡",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",apacir:"⩯",ap:"≈",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",barwed:"⌅",Barwed:"⌆",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",because:"∵",Because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxdl:"┐",boxdL:"╕",boxDl:"╖",boxDL:"╗",boxdr:"┌",boxdR:"╒",boxDr:"╓",boxDR:"╔",boxh:"─",boxH:"═",boxhd:"┬",boxHd:"╤",boxhD:"╥",boxHD:"╦",boxhu:"┴",boxHu:"╧",boxhU:"╨",boxHU:"╩",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxul:"┘",boxuL:"╛",boxUl:"╜",boxUL:"╝",boxur:"└",boxuR:"╘",boxUr:"╙",boxUR:"╚",boxv:"│",boxV:"║",boxvh:"┼",boxvH:"╪",boxVh:"╫",boxVH:"╬",boxvl:"┤",boxvL:"╡",boxVl:"╢",boxVL:"╣",boxvr:"├",boxvR:"╞",boxVr:"╟",boxVR:"╠",bprime:"‵",breve:"˘",Breve:"˘",brvbar:"¦",bscr:"𝒷",Bscr:"ℬ",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsolb:"⧅",bsol:"\\",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",capand:"⩄",capbrcup:"⩉",capcap:"⩋",cap:"∩",Cap:"⋒",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",centerdot:"·",CenterDot:"·",cfr:"𝔠",Cfr:"ℭ",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cir:"○",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",colon:":",Colon:"∷",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",conint:"∮",Conint:"∯",ContourIntegral:"∮",copf:"𝕔",Copf:"ℂ",coprod:"∐",Coproduct:"∐",copy:"©",COPY:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",cross:"✗",Cross:"⨯",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",cupbrcap:"⩈",cupcap:"⩆",CupCap:"≍",cup:"∪",Cup:"⋓",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",dagger:"†",Dagger:"‡",daleth:"ℸ",darr:"↓",Darr:"↡",dArr:"⇓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",ddagger:"‡",ddarr:"⇊",DD:"ⅅ",dd:"ⅆ",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",diamond:"⋄",Diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrowBar:"⤓",downarrow:"↓",DownArrow:"↓",Downarrow:"⇓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVectorBar:"⥖",DownLeftVector:"↽",DownRightTeeVector:"⥟",DownRightVectorBar:"⥗",DownRightVector:"⇁",DownTeeArrow:"↧",DownTee:"⊤",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",Ecirc:"Ê",ecirc:"ê",ecir:"≖",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",edot:"ė",eDot:"≑",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp13:" ",emsp14:" ",emsp:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",escr:"ℯ",Escr:"ℰ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",exponentiale:"ⅇ",ExponentialE:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",forall:"∀",ForAll:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",fscr:"𝒻",Fscr:"ℱ",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",ge:"≥",gE:"≧",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",gescc:"⪩",ges:"⩾",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",gg:"≫",Gg:"⋙",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gla:"⪥",gl:"≷",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gne:"⪈",gnE:"≩",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",gtcc:"⪧",gtcir:"⩺",gt:">",GT:">",Gt:"≫",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",harrcir:"⥈",harr:"↔",hArr:"⇔",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",hfr:"𝔥",Hfr:"ℌ",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",hopf:"𝕙",Hopf:"ℍ",horbar:"―",HorizontalLine:"─",hscr:"𝒽",Hscr:"ℋ",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",ifr:"𝔦",Ifr:"ℑ",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",Im:"ℑ",imof:"⊷",imped:"Ƶ",Implies:"⇒",incare:"℅",in:"∈",infin:"∞",infintie:"⧝",inodot:"ı",intcal:"⊺",int:"∫",Int:"∬",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",iscr:"𝒾",Iscr:"ℐ",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",lang:"⟨",Lang:"⟪",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",larrb:"⇤",larrbfs:"⤟",larr:"←",Larr:"↞",lArr:"⇐",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",latail:"⤙",lAtail:"⤛",lat:"⪫",late:"⪭",lates:"⪭︀",lbarr:"⤌",lBarr:"⤎",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",le:"≤",lE:"≦",LeftAngleBracket:"⟨",LeftArrowBar:"⇤",leftarrow:"←",LeftArrow:"←",Leftarrow:"⇐",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVectorBar:"⥙",LeftDownVector:"⇃",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",leftrightarrow:"↔",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTeeArrow:"↤",LeftTee:"⊣",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangleBar:"⧏",LeftTriangle:"⊲",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVectorBar:"⥘",LeftUpVector:"↿",LeftVectorBar:"⥒",LeftVector:"↼",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",lescc:"⪨",les:"⩽",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",llarr:"⇇",ll:"≪",Ll:"⋘",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoustache:"⎰",lmoust:"⎰",lnap:"⪉",lnapprox:"⪉",lne:"⪇",lnE:"≨",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",longleftarrow:"⟵",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftrightarrow:"⟷",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longmapsto:"⟼",longrightarrow:"⟶",LongRightArrow:"⟶",Longrightarrow:"⟹",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",lscr:"𝓁",Lscr:"ℒ",lsh:"↰",Lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",ltcc:"⪦",ltcir:"⩹",lt:"<",LT:"<",Lt:"≪",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",midast:"*",midcir:"⫰",mid:"∣",middot:"·",minusb:"⊟",minus:"−",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",mscr:"𝓂",Mscr:"ℳ",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natural:"♮",naturals:"ℕ",natur:"♮",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",nearhk:"⤤",nearr:"↗",neArr:"⇗",nearrow:"↗",ne:"≠",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nharr:"↮",nhArr:"⇎",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlarr:"↚",nlArr:"⇍",nldr:"‥",nlE:"≦̸",nle:"≰",nleftarrow:"↚",nLeftarrow:"⇍",nleftrightarrow:"↮",nLeftrightarrow:"⇎",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",nopf:"𝕟",Nopf:"ℕ",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangleBar:"⧏̸",NotLeftTriangle:"⋪",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangleBar:"⧐̸",NotRightTriangle:"⋫",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",nparallel:"∦",npar:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",nprec:"⊀",npreceq:"⪯̸",npre:"⪯̸",nrarrc:"⤳̸",nrarr:"↛",nrArr:"⇏",nrarrw:"↝̸",nrightarrow:"↛",nRightarrow:"⇏",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nvdash:"⊬",nvDash:"⊭",nVdash:"⊮",nVDash:"⊯",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwarr:"↖",nwArr:"⇖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",Ocirc:"Ô",ocirc:"ô",ocir:"⊚",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",orarr:"↻",Or:"⩔",or:"∨",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",otimesas:"⨶",Otimes:"⨷",otimes:"⊗",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",para:"¶",parallel:"∥",par:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plus:"+",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",popf:"𝕡",Popf:"ℙ",pound:"£",prap:"⪷",Pr:"⪻",pr:"≺",prcue:"≼",precapprox:"⪷",prec:"≺",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",pre:"⪯",prE:"⪳",precsim:"≾",prime:"′",Prime:"″",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportional:"∝",Proportion:"∷",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",qopf:"𝕢",Qopf:"ℚ",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",quot:'"',QUOT:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",rang:"⟩",Rang:"⟫",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarr:"→",Rarr:"↠",rArr:"⇒",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",ratail:"⤚",rAtail:"⤜",ratio:"∶",rationals:"ℚ",rbarr:"⤍",rBarr:"⤏",RBarr:"⤐",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",Re:"ℜ",rect:"▭",reg:"®",REG:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",rfr:"𝔯",Rfr:"ℜ",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrowBar:"⇥",rightarrow:"→",RightArrow:"→",Rightarrow:"⇒",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVectorBar:"⥕",RightDownVector:"⇂",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTeeArrow:"↦",RightTee:"⊢",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangleBar:"⧐",RightTriangle:"⊳",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVectorBar:"⥔",RightUpVector:"↾",RightVectorBar:"⥓",RightVector:"⇀",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoustache:"⎱",rmoust:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",ropf:"𝕣",Ropf:"ℝ",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",rscr:"𝓇",Rscr:"ℛ",rsh:"↱",Rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",scap:"⪸",Scaron:"Š",scaron:"š",Sc:"⪼",sc:"≻",sccue:"≽",sce:"⪰",scE:"⪴",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdotb:"⊡",sdot:"⋅",sdote:"⩦",searhk:"⤥",searr:"↘",seArr:"⇘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",solbar:"⌿",solb:"⧄",sol:"/",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",square:"□",Square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squ:"□",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",sub:"⊂",Sub:"⋐",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",subset:"⊂",Subset:"⋐",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succapprox:"⪸",succ:"≻",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",sum:"∑",Sum:"∑",sung:"♪",sup1:"¹",sup2:"²",sup3:"³",sup:"⊃",Sup:"⋑",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",supset:"⊃",Supset:"⋑",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swarr:"↙",swArr:"⇙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",therefore:"∴",Therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",ThinSpace:" ",thinsp:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",tilde:"˜",Tilde:"∼",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",timesbar:"⨱",timesb:"⊠",times:"×",timesd:"⨰",tint:"∭",toea:"⤨",topbot:"⌶",topcir:"⫱",top:"⊤",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",trade:"™",TRADE:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",uarr:"↑",Uarr:"↟",uArr:"⇑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrowBar:"⤒",uparrow:"↑",UpArrow:"↑",Uparrow:"⇑",UpArrowDownArrow:"⇅",updownarrow:"↕",UpDownArrow:"↕",Updownarrow:"⇕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",upsi:"υ",Upsi:"ϒ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTeeArrow:"↥",UpTee:"⊥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",varr:"↕",vArr:"⇕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",vBar:"⫨",Vbar:"⫫",vBarv:"⫩",Vcy:"В",vcy:"в",vdash:"⊢",vDash:"⊨",Vdash:"⊩",VDash:"⊫",Vdashl:"⫦",veebar:"⊻",vee:"∨",Vee:"⋁",veeeq:"≚",vellip:"⋮",verbar:"|",Verbar:"‖",vert:"|",Vert:"‖",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",wedge:"∧",Wedge:"⋀",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xharr:"⟷",xhArr:"⟺",Xi:"Ξ",xi:"ξ",xlarr:"⟵",xlArr:"⟸",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrarr:"⟶",xrArr:"⟹",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",yuml:"ÿ",Yuml:"Ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",zfr:"𝔷",Zfr:"ℨ",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",zopf:"𝕫",Zopf:"ℤ",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}},{}],26:[function(require,module,exports){module.exports={Aacute:"Á",aacute:"á",Acirc:"Â",acirc:"â",acute:"´",AElig:"Æ",aelig:"æ",Agrave:"À",agrave:"à",amp:"&",AMP:"&",Aring:"Å",aring:"å",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",brvbar:"¦",Ccedil:"Ç",ccedil:"ç",cedil:"¸",cent:"¢",copy:"©",COPY:"©",curren:"¤",deg:"°",divide:"÷",Eacute:"É",eacute:"é",Ecirc:"Ê",ecirc:"ê",Egrave:"È",egrave:"è",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",frac12:"½",frac14:"¼",frac34:"¾",gt:">",GT:">",Iacute:"Í",iacute:"í",Icirc:"Î",icirc:"î",iexcl:"¡",Igrave:"Ì",igrave:"ì",iquest:"¿",Iuml:"Ï",iuml:"ï",laquo:"«",lt:"<",LT:"<",macr:"¯",micro:"µ",middot:"·",nbsp:" ",not:"¬",Ntilde:"Ñ",ntilde:"ñ",Oacute:"Ó",oacute:"ó",Ocirc:"Ô",ocirc:"ô",Ograve:"Ò",ograve:"ò",ordf:"ª",ordm:"º",Oslash:"Ø",oslash:"ø",Otilde:"Õ",otilde:"õ",Ouml:"Ö",ouml:"ö",para:"¶",plusmn:"±",pound:"£",quot:'"',QUOT:'"',raquo:"»",reg:"®",REG:"®",sect:"§",shy:"­",sup1:"¹",sup2:"²",sup3:"³",szlig:"ß",THORN:"Þ",thorn:"þ",times:"×",Uacute:"Ú",uacute:"ú",Ucirc:"Û",ucirc:"û",Ugrave:"Ù",ugrave:"ù",uml:"¨",Uuml:"Ü",uuml:"ü",Yacute:"Ý",yacute:"ý",yen:"¥",yuml:"ÿ"}},{}],27:[function(require,module,exports){module.exports={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}},{}],28:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Uncaught, unspecified "error" event. ('+er+")");err.context=er;throw err}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args)}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1); -}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],29:[function(require,module,exports){module.exports=CollectingHandler;function CollectingHandler(cbs){this._cbs=cbs||{};this.events=[]}var EVENTS=require("./").EVENTS;Object.keys(EVENTS).forEach(function(name){if(EVENTS[name]===0){name="on"+name;CollectingHandler.prototype[name]=function(){this.events.push([name]);if(this._cbs[name])this._cbs[name]()}}else if(EVENTS[name]===1){name="on"+name;CollectingHandler.prototype[name]=function(a){this.events.push([name,a]);if(this._cbs[name])this._cbs[name](a)}}else if(EVENTS[name]===2){name="on"+name;CollectingHandler.prototype[name]=function(a,b){this.events.push([name,a,b]);if(this._cbs[name])this._cbs[name](a,b)}}else{throw Error("wrong number of arguments")}});CollectingHandler.prototype.onreset=function(){this.events=[];if(this._cbs.onreset)this._cbs.onreset()};CollectingHandler.prototype.restart=function(){if(this._cbs.onreset)this._cbs.onreset();for(var i=0,len=this.events.length;i0;this._cbs.onclosetag(this._stack[--i]));}if(this._cbs.onend)this._cbs.onend()};Parser.prototype.reset=function(){if(this._cbs.onreset)this._cbs.onreset();this._tokenizer.reset();this._tagname="";this._attribname="";this._attribs=null;this._stack=[];if(this._cbs.onparserinit)this._cbs.onparserinit(this)};Parser.prototype.parseComplete=function(data){this.reset();this.end(data)};Parser.prototype.write=function(chunk){this._tokenizer.write(chunk)};Parser.prototype.end=function(chunk){this._tokenizer.end(chunk)};Parser.prototype.pause=function(){this._tokenizer.pause()};Parser.prototype.resume=function(){this._tokenizer.resume()};Parser.prototype.parseChunk=Parser.prototype.write;Parser.prototype.done=Parser.prototype.end;module.exports=Parser},{"./Tokenizer.js":34,events:28,inherits:38}],32:[function(require,module,exports){module.exports=ProxyHandler;function ProxyHandler(cbs){this._cbs=cbs||{}}var EVENTS=require("./").EVENTS;Object.keys(EVENTS).forEach(function(name){if(EVENTS[name]===0){name="on"+name;ProxyHandler.prototype[name]=function(){if(this._cbs[name])this._cbs[name]()}}else if(EVENTS[name]===1){name="on"+name;ProxyHandler.prototype[name]=function(a){if(this._cbs[name])this._cbs[name](a)}}else if(EVENTS[name]===2){name="on"+name;ProxyHandler.prototype[name]=function(a,b){if(this._cbs[name])this._cbs[name](a,b)}}else{throw Error("wrong number of arguments")}})},{"./":36}],33:[function(require,module,exports){module.exports=Stream;var Parser=require("./WritableStream.js");function Stream(options){Parser.call(this,new Cbs(this),options)}require("inherits")(Stream,Parser);Stream.prototype.readable=true;function Cbs(scope){this.scope=scope}var EVENTS=require("../").EVENTS;Object.keys(EVENTS).forEach(function(name){if(EVENTS[name]===0){Cbs.prototype["on"+name]=function(){this.scope.emit(name)}}else if(EVENTS[name]===1){Cbs.prototype["on"+name]=function(a){this.scope.emit(name,a)}}else if(EVENTS[name]===2){Cbs.prototype["on"+name]=function(a,b){this.scope.emit(name,a,b)}}else{throw Error("wrong number of arguments!")}})},{"../":36,"./WritableStream.js":35,inherits:38}],34:[function(require,module,exports){module.exports=Tokenizer;var decodeCodePoint=require("entities/lib/decode_codepoint.js"),entityMap=require("entities/maps/entities.json"),legacyMap=require("entities/maps/legacy.json"),xmlMap=require("entities/maps/xml.json"),i=0,TEXT=i++,BEFORE_TAG_NAME=i++,IN_TAG_NAME=i++,IN_SELF_CLOSING_TAG=i++,BEFORE_CLOSING_TAG_NAME=i++,IN_CLOSING_TAG_NAME=i++,AFTER_CLOSING_TAG_NAME=i++,BEFORE_ATTRIBUTE_NAME=i++,IN_ATTRIBUTE_NAME=i++,AFTER_ATTRIBUTE_NAME=i++,BEFORE_ATTRIBUTE_VALUE=i++,IN_ATTRIBUTE_VALUE_DQ=i++,IN_ATTRIBUTE_VALUE_SQ=i++,IN_ATTRIBUTE_VALUE_NQ=i++,BEFORE_DECLARATION=i++,IN_DECLARATION=i++,IN_PROCESSING_INSTRUCTION=i++,BEFORE_COMMENT=i++,IN_COMMENT=i++,AFTER_COMMENT_1=i++,AFTER_COMMENT_2=i++,BEFORE_CDATA_1=i++,BEFORE_CDATA_2=i++,BEFORE_CDATA_3=i++,BEFORE_CDATA_4=i++,BEFORE_CDATA_5=i++,BEFORE_CDATA_6=i++,IN_CDATA=i++,AFTER_CDATA_1=i++,AFTER_CDATA_2=i++,BEFORE_SPECIAL=i++,BEFORE_SPECIAL_END=i++,BEFORE_SCRIPT_1=i++,BEFORE_SCRIPT_2=i++,BEFORE_SCRIPT_3=i++,BEFORE_SCRIPT_4=i++,BEFORE_SCRIPT_5=i++,AFTER_SCRIPT_1=i++,AFTER_SCRIPT_2=i++,AFTER_SCRIPT_3=i++,AFTER_SCRIPT_4=i++,AFTER_SCRIPT_5=i++,BEFORE_STYLE_1=i++,BEFORE_STYLE_2=i++,BEFORE_STYLE_3=i++,BEFORE_STYLE_4=i++,AFTER_STYLE_1=i++,AFTER_STYLE_2=i++,AFTER_STYLE_3=i++,AFTER_STYLE_4=i++,BEFORE_ENTITY=i++,BEFORE_NUMERIC_ENTITY=i++,IN_NAMED_ENTITY=i++,IN_NUMERIC_ENTITY=i++,IN_HEX_ENTITY=i++,j=0,SPECIAL_NONE=j++,SPECIAL_SCRIPT=j++,SPECIAL_STYLE=j++;function whitespace(c){return c===" "||c==="\n"||c==="\t"||c==="\f"||c==="\r"}function characterState(char,SUCCESS){return function(c){if(c===char)this._state=SUCCESS}}function ifElseState(upper,SUCCESS,FAILURE){var lower=upper.toLowerCase();if(upper===lower){return function(c){if(c===lower){this._state=SUCCESS}else{this._state=FAILURE;this._index--}}}else{return function(c){if(c===lower||c===upper){this._state=SUCCESS}else{this._state=FAILURE;this._index--}}}}function consumeSpecialNameChar(upper,NEXT_STATE){var lower=upper.toLowerCase();return function(c){if(c===lower||c===upper){this._state=NEXT_STATE}else{this._state=IN_TAG_NAME;this._index--}}}function Tokenizer(options,cbs){this._state=TEXT;this._buffer="";this._sectionStart=0;this._index=0;this._bufferOffset=0;this._baseState=TEXT;this._special=SPECIAL_NONE;this._cbs=cbs;this._running=true;this._ended=false;this._xmlMode=!!(options&&options.xmlMode);this._decodeEntities=!!(options&&options.decodeEntities)}Tokenizer.prototype._stateText=function(c){if(c==="<"){if(this._index>this._sectionStart){this._cbs.ontext(this._getSection())}this._state=BEFORE_TAG_NAME;this._sectionStart=this._index}else if(this._decodeEntities&&this._special===SPECIAL_NONE&&c==="&"){if(this._index>this._sectionStart){this._cbs.ontext(this._getSection())}this._baseState=TEXT;this._state=BEFORE_ENTITY;this._sectionStart=this._index}};Tokenizer.prototype._stateBeforeTagName=function(c){if(c==="/"){this._state=BEFORE_CLOSING_TAG_NAME}else if(c==="<"){this._cbs.ontext(this._getSection());this._sectionStart=this._index}else if(c===">"||this._special!==SPECIAL_NONE||whitespace(c)){this._state=TEXT}else if(c==="!"){this._state=BEFORE_DECLARATION;this._sectionStart=this._index+1}else if(c==="?"){this._state=IN_PROCESSING_INSTRUCTION;this._sectionStart=this._index+1}else{this._state=!this._xmlMode&&(c==="s"||c==="S")?BEFORE_SPECIAL:IN_TAG_NAME;this._sectionStart=this._index}};Tokenizer.prototype._stateInTagName=function(c){if(c==="/"||c===">"||whitespace(c)){this._emitToken("onopentagname");this._state=BEFORE_ATTRIBUTE_NAME;this._index--}};Tokenizer.prototype._stateBeforeCloseingTagName=function(c){if(whitespace(c));else if(c===">"){this._state=TEXT}else if(this._special!==SPECIAL_NONE){if(c==="s"||c==="S"){this._state=BEFORE_SPECIAL_END}else{this._state=TEXT;this._index--}}else{this._state=IN_CLOSING_TAG_NAME;this._sectionStart=this._index}};Tokenizer.prototype._stateInCloseingTagName=function(c){if(c===">"||whitespace(c)){this._emitToken("onclosetag");this._state=AFTER_CLOSING_TAG_NAME;this._index--}};Tokenizer.prototype._stateAfterCloseingTagName=function(c){if(c===">"){this._state=TEXT;this._sectionStart=this._index+1}};Tokenizer.prototype._stateBeforeAttributeName=function(c){if(c===">"){this._cbs.onopentagend();this._state=TEXT;this._sectionStart=this._index+1}else if(c==="/"){this._state=IN_SELF_CLOSING_TAG}else if(!whitespace(c)){this._state=IN_ATTRIBUTE_NAME;this._sectionStart=this._index}};Tokenizer.prototype._stateInSelfClosingTag=function(c){if(c===">"){this._cbs.onselfclosingtag();this._state=TEXT;this._sectionStart=this._index+1}else if(!whitespace(c)){this._state=BEFORE_ATTRIBUTE_NAME;this._index--}};Tokenizer.prototype._stateInAttributeName=function(c){if(c==="="||c==="/"||c===">"||whitespace(c)){this._cbs.onattribname(this._getSection());this._sectionStart=-1;this._state=AFTER_ATTRIBUTE_NAME;this._index--}};Tokenizer.prototype._stateAfterAttributeName=function(c){if(c==="="){this._state=BEFORE_ATTRIBUTE_VALUE}else if(c==="/"||c===">"){this._cbs.onattribend();this._state=BEFORE_ATTRIBUTE_NAME;this._index--}else if(!whitespace(c)){this._cbs.onattribend();this._state=IN_ATTRIBUTE_NAME;this._sectionStart=this._index}};Tokenizer.prototype._stateBeforeAttributeValue=function(c){if(c==='"'){this._state=IN_ATTRIBUTE_VALUE_DQ;this._sectionStart=this._index+1}else if(c==="'"){this._state=IN_ATTRIBUTE_VALUE_SQ;this._sectionStart=this._index+1}else if(!whitespace(c)){this._state=IN_ATTRIBUTE_VALUE_NQ;this._sectionStart=this._index;this._index--}};Tokenizer.prototype._stateInAttributeValueDoubleQuotes=function(c){if(c==='"'){this._emitToken("onattribdata");this._cbs.onattribend();this._state=BEFORE_ATTRIBUTE_NAME}else if(this._decodeEntities&&c==="&"){this._emitToken("onattribdata");this._baseState=this._state;this._state=BEFORE_ENTITY;this._sectionStart=this._index}};Tokenizer.prototype._stateInAttributeValueSingleQuotes=function(c){if(c==="'"){this._emitToken("onattribdata");this._cbs.onattribend();this._state=BEFORE_ATTRIBUTE_NAME}else if(this._decodeEntities&&c==="&"){this._emitToken("onattribdata");this._baseState=this._state;this._state=BEFORE_ENTITY;this._sectionStart=this._index}};Tokenizer.prototype._stateInAttributeValueNoQuotes=function(c){if(whitespace(c)||c===">"){this._emitToken("onattribdata");this._cbs.onattribend();this._state=BEFORE_ATTRIBUTE_NAME;this._index--}else if(this._decodeEntities&&c==="&"){this._emitToken("onattribdata");this._baseState=this._state;this._state=BEFORE_ENTITY;this._sectionStart=this._index}};Tokenizer.prototype._stateBeforeDeclaration=function(c){this._state=c==="["?BEFORE_CDATA_1:c==="-"?BEFORE_COMMENT:IN_DECLARATION};Tokenizer.prototype._stateInDeclaration=function(c){if(c===">"){this._cbs.ondeclaration(this._getSection());this._state=TEXT;this._sectionStart=this._index+1}};Tokenizer.prototype._stateInProcessingInstruction=function(c){if(c===">"){this._cbs.onprocessinginstruction(this._getSection());this._state=TEXT;this._sectionStart=this._index+1}};Tokenizer.prototype._stateBeforeComment=function(c){if(c==="-"){this._state=IN_COMMENT;this._sectionStart=this._index+1}else{this._state=IN_DECLARATION}};Tokenizer.prototype._stateInComment=function(c){if(c==="-")this._state=AFTER_COMMENT_1};Tokenizer.prototype._stateAfterComment1=function(c){if(c==="-"){this._state=AFTER_COMMENT_2}else{this._state=IN_COMMENT}};Tokenizer.prototype._stateAfterComment2=function(c){if(c===">"){this._cbs.oncomment(this._buffer.substring(this._sectionStart,this._index-2));this._state=TEXT;this._sectionStart=this._index+1}else if(c!=="-"){this._state=IN_COMMENT}};Tokenizer.prototype._stateBeforeCdata1=ifElseState("C",BEFORE_CDATA_2,IN_DECLARATION);Tokenizer.prototype._stateBeforeCdata2=ifElseState("D",BEFORE_CDATA_3,IN_DECLARATION);Tokenizer.prototype._stateBeforeCdata3=ifElseState("A",BEFORE_CDATA_4,IN_DECLARATION);Tokenizer.prototype._stateBeforeCdata4=ifElseState("T",BEFORE_CDATA_5,IN_DECLARATION);Tokenizer.prototype._stateBeforeCdata5=ifElseState("A",BEFORE_CDATA_6,IN_DECLARATION);Tokenizer.prototype._stateBeforeCdata6=function(c){if(c==="["){this._state=IN_CDATA;this._sectionStart=this._index+1}else{this._state=IN_DECLARATION;this._index--}};Tokenizer.prototype._stateInCdata=function(c){if(c==="]")this._state=AFTER_CDATA_1};Tokenizer.prototype._stateAfterCdata1=characterState("]",AFTER_CDATA_2);Tokenizer.prototype._stateAfterCdata2=function(c){if(c===">"){this._cbs.oncdata(this._buffer.substring(this._sectionStart,this._index-2));this._state=TEXT;this._sectionStart=this._index+1}else if(c!=="]"){this._state=IN_CDATA}};Tokenizer.prototype._stateBeforeSpecial=function(c){if(c==="c"||c==="C"){this._state=BEFORE_SCRIPT_1}else if(c==="t"||c==="T"){this._state=BEFORE_STYLE_1}else{this._state=IN_TAG_NAME;this._index--}};Tokenizer.prototype._stateBeforeSpecialEnd=function(c){if(this._special===SPECIAL_SCRIPT&&(c==="c"||c==="C")){this._state=AFTER_SCRIPT_1}else if(this._special===SPECIAL_STYLE&&(c==="t"||c==="T")){this._state=AFTER_STYLE_1}else this._state=TEXT};Tokenizer.prototype._stateBeforeScript1=consumeSpecialNameChar("R",BEFORE_SCRIPT_2);Tokenizer.prototype._stateBeforeScript2=consumeSpecialNameChar("I",BEFORE_SCRIPT_3);Tokenizer.prototype._stateBeforeScript3=consumeSpecialNameChar("P",BEFORE_SCRIPT_4);Tokenizer.prototype._stateBeforeScript4=consumeSpecialNameChar("T",BEFORE_SCRIPT_5);Tokenizer.prototype._stateBeforeScript5=function(c){if(c==="/"||c===">"||whitespace(c)){this._special=SPECIAL_SCRIPT}this._state=IN_TAG_NAME;this._index--};Tokenizer.prototype._stateAfterScript1=ifElseState("R",AFTER_SCRIPT_2,TEXT);Tokenizer.prototype._stateAfterScript2=ifElseState("I",AFTER_SCRIPT_3,TEXT);Tokenizer.prototype._stateAfterScript3=ifElseState("P",AFTER_SCRIPT_4,TEXT);Tokenizer.prototype._stateAfterScript4=ifElseState("T",AFTER_SCRIPT_5,TEXT);Tokenizer.prototype._stateAfterScript5=function(c){if(c===">"||whitespace(c)){this._special=SPECIAL_NONE;this._state=IN_CLOSING_TAG_NAME;this._sectionStart=this._index-6;this._index--}else this._state=TEXT};Tokenizer.prototype._stateBeforeStyle1=consumeSpecialNameChar("Y",BEFORE_STYLE_2);Tokenizer.prototype._stateBeforeStyle2=consumeSpecialNameChar("L",BEFORE_STYLE_3);Tokenizer.prototype._stateBeforeStyle3=consumeSpecialNameChar("E",BEFORE_STYLE_4);Tokenizer.prototype._stateBeforeStyle4=function(c){if(c==="/"||c===">"||whitespace(c)){this._special=SPECIAL_STYLE}this._state=IN_TAG_NAME;this._index--};Tokenizer.prototype._stateAfterStyle1=ifElseState("Y",AFTER_STYLE_2,TEXT);Tokenizer.prototype._stateAfterStyle2=ifElseState("L",AFTER_STYLE_3,TEXT);Tokenizer.prototype._stateAfterStyle3=ifElseState("E",AFTER_STYLE_4,TEXT);Tokenizer.prototype._stateAfterStyle4=function(c){if(c===">"||whitespace(c)){this._special=SPECIAL_NONE;this._state=IN_CLOSING_TAG_NAME;this._sectionStart=this._index-5;this._index--}else this._state=TEXT};Tokenizer.prototype._stateBeforeEntity=ifElseState("#",BEFORE_NUMERIC_ENTITY,IN_NAMED_ENTITY);Tokenizer.prototype._stateBeforeNumericEntity=ifElseState("X",IN_HEX_ENTITY,IN_NUMERIC_ENTITY);Tokenizer.prototype._parseNamedEntityStrict=function(){if(this._sectionStart+16)limit=6;while(limit>=2){var entity=this._buffer.substr(start,limit);if(legacyMap.hasOwnProperty(entity)){this._emitPartial(legacyMap[entity]);this._sectionStart+=limit+1;return}else{limit--}}};Tokenizer.prototype._stateInNamedEntity=function(c){if(c===";"){this._parseNamedEntityStrict();if(this._sectionStart+1"z")&&(c<"A"||c>"Z")&&(c<"0"||c>"9")){if(this._xmlMode);else if(this._sectionStart+1===this._index);else if(this._baseState!==TEXT){if(c!=="="){this._parseNamedEntityStrict()}}else{this._parseLegacyEntity()}this._state=this._baseState;this._index--}};Tokenizer.prototype._decodeNumericEntity=function(offset,base){var sectionStart=this._sectionStart+offset;if(sectionStart!==this._index){var entity=this._buffer.substring(sectionStart,this._index);var parsed=parseInt(entity,base);this._emitPartial(decodeCodePoint(parsed));this._sectionStart=this._index}else{this._sectionStart--}this._state=this._baseState};Tokenizer.prototype._stateInNumericEntity=function(c){if(c===";"){this._decodeNumericEntity(2,10);this._sectionStart++}else if(c<"0"||c>"9"){if(!this._xmlMode){this._decodeNumericEntity(2,10)}else{this._state=this._baseState}this._index--}};Tokenizer.prototype._stateInHexEntity=function(c){if(c===";"){this._decodeNumericEntity(3,16);this._sectionStart++}else if((c<"a"||c>"f")&&(c<"A"||c>"F")&&(c<"0"||c>"9")){if(!this._xmlMode){this._decodeNumericEntity(3,16)}else{this._state=this._baseState}this._index--}};Tokenizer.prototype._cleanup=function(){if(this._sectionStart<0){this._buffer="";this._index=0;this._bufferOffset+=this._index}else if(this._running){if(this._state===TEXT){if(this._sectionStart!==this._index){this._cbs.ontext(this._buffer.substr(this._sectionStart))}this._buffer="";this._bufferOffset+=this._index;this._index=0}else if(this._sectionStart===this._index){this._buffer="";this._bufferOffset+=this._index;this._index=0}else{this._buffer=this._buffer.substr(this._sectionStart);this._index-=this._sectionStart;this._bufferOffset+=this._sectionStart}this._sectionStart=0}};Tokenizer.prototype.write=function(chunk){if(this._ended)this._cbs.onerror(Error(".write() after done!"));this._buffer+=chunk;this._parse()};Tokenizer.prototype._parse=function(){while(this._index>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],38:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],39:[function(require,module,exports){module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],40:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=="[object Array]"}},{}],41:[function(require,module,exports){(function(process){"use strict";if(!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){module.exports=nextTick}else{module.exports=process.nextTick}function nextTick(fn,arg1,arg2,arg3){if(typeof fn!=="function"){throw new TypeError('"callback" argument must be a function')}var len=arguments.length;var args,i;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:args=new Array(len-1);i=0;while(i1){for(var i=1;i0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;if(state.decoder&&!addToFront&&!encoding){chunk=state.decoder.write(chunk);skipAdd=!state.objectMode&&chunk.length===0}if(!addToFront)state.reading=false;if(!skipAdd){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}}maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}else{state.length-=n}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var _i=0;_i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n);var p=list.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream;(function(){try{Stream=require("st"+"ream")}catch(_){}finally{if(!Stream)Stream=require("events").EventEmitter}})();var Buffer=require("buffer").Buffer;var bufferShim=require("buffer-shims");util.inherits(Writable,Stream);function nop(){}function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb;this.next=null}var Duplex;function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};this.objectMode=!!options.objectMode;if(stream instanceof Duplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var defaultHwm=this.objectMode?16:16*1024;this.highWaterMark=hwm||hwm===0?hwm:defaultHwm;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function writableStateGetBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.")})}catch(_){}})();var Duplex;function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(!Buffer.isBuffer(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(validChunk(this,state,chunk,cb)){ -state.pendingcb++;ret=writeOrBuffer(this,state,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=bufferShim.from(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length};BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=function(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret};BufferList.prototype.clear=function(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret};BufferList.prototype.concat=function(n){if(this.length===0)return bufferShim.alloc(0);if(this.length===1)return this.head.data;var ret=bufferShim.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){p.data.copy(ret,i);i+=p.data.length;p=p.next}return ret}},{buffer:5,"buffer-shims":4}],50:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":45}],51:[function(require,module,exports){(function(process){var Stream=function(){try{return require("st"+"ream")}catch(_){}}();exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream||exports;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js");if(!process.browser&&process.env.READABLE_STREAM==="disable"&&Stream){module.exports=Stream}}).call(this,require("_process"))},{"./lib/_stream_duplex.js":44,"./lib/_stream_passthrough.js":45,"./lib/_stream_readable.js":46,"./lib/_stream_transform.js":47,"./lib/_stream_writable.js":48,_process:42}],52:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":47}],53:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":48}],54:[function(require,module,exports){module.exports=function(string){return string.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")}},{}],55:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:28,inherits:38,"readable-stream/duplex.js":43,"readable-stream/passthrough.js":50,"readable-stream/readable.js":51,"readable-stream/transform.js":52,"readable-stream/writable.js":53}],56:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:5}],57:[function(require,module,exports){(function(global){module.exports=deprecate;function deprecate(fn,msg){if(config("noDeprecation")){return fn}var warned=false;function deprecated(){if(!warned){if(config("throwDeprecation")){throw new Error(msg)}else if(config("traceDeprecation")){console.trace(msg)}else{console.warn(msg)}warned=true}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return false}catch(_){return false}var val=global.localStorage[name];if(null==val)return false;return String(val).toLowerCase()==="true"}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],58:[function(require,module,exports){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(){var target={};for(var i=0;i 0) { - qp = obj.url.substring(obj.url.indexOf('?') + 1); - var parts = qp.split('&'); - if(parts && parts.length > 0) { - for(var i = 0; i < parts.length; i++) { - var kv = parts[i].split('='); - if(kv && kv.length > 0) { - if (kv[0] === this.name) { - // skip it - return false; - } - } - } - } - } - - if (obj.url.indexOf('?') > 0) { - obj.url = obj.url + '&' + this.name + '=' + this.value; - } else { - obj.url = obj.url + '?' + this.name + '=' + this.value; - } - - return true; - } else if (this.type === 'header') { - if(typeof obj.headers[this.name] === 'undefined') { - obj.headers[this.name] = this.value; - } - - return true; - } -}; - -var CookieAuthorization = module.exports.CookieAuthorization = function (cookie) { - this.cookie = cookie; -}; - -CookieAuthorization.prototype.apply = function (obj) { - obj.cookieJar = obj.cookieJar || new CookieJar(); - obj.cookieJar.setCookie(this.cookie); - - return true; -}; - -/** - * Password Authorization is a basic auth implementation - */ -var PasswordAuthorization = module.exports.PasswordAuthorization = function (username, password) { - if (arguments.length === 3) { - helpers.log('PasswordAuthorization: the \'name\' argument has been removed, pass only username and password'); - username = arguments[1]; - password = arguments[2]; - } - this.username = username; - this.password = password; -}; - -PasswordAuthorization.prototype.apply = function (obj) { - if(typeof obj.headers.Authorization === 'undefined') { - obj.headers.Authorization = 'Basic ' + btoa(this.username + ':' + this.password); - } - - return true; -}; - -},{"./helpers":4,"btoa":13,"cookiejar":18,"lodash-compat/collection/each":52,"lodash-compat/collection/includes":55,"lodash-compat/lang/isArray":140,"lodash-compat/lang/isObject":144}],3:[function(require,module,exports){ -'use strict'; - -var _ = { - bind: require('lodash-compat/function/bind'), - cloneDeep: require('lodash-compat/lang/cloneDeep'), - find: require('lodash-compat/collection/find'), - forEach: require('lodash-compat/collection/forEach'), - indexOf: require('lodash-compat/array/indexOf'), - isArray: require('lodash-compat/lang/isArray'), - isObject: require('lodash-compat/lang/isObject'), - isFunction: require('lodash-compat/lang/isFunction'), - isPlainObject: require('lodash-compat/lang/isPlainObject'), - isUndefined: require('lodash-compat/lang/isUndefined') -}; -var auth = require('./auth'); -var helpers = require('./helpers'); -var Model = require('./types/model'); -var Operation = require('./types/operation'); -var OperationGroup = require('./types/operationGroup'); -var Resolver = require('./resolver'); -var SwaggerHttp = require('./http'); -var SwaggerSpecConverter = require('./spec-converter'); -var Q = require('q'); - -// We have to keep track of the function/property names to avoid collisions for tag names which are used to allow the -// following usage: 'client.{tagName}' -var reservedClientTags = [ - 'apis', - 'authorizationScheme', - 'authorizations', - 'basePath', - 'build', - 'buildFrom1_1Spec', - 'buildFrom1_2Spec', - 'buildFromSpec', - 'clientAuthorizations', - 'convertInfo', - 'debug', - 'defaultErrorCallback', - 'defaultSuccessCallback', - 'enableCookies', - 'fail', - 'failure', - 'finish', - 'help', - 'host', - 'idFromOp', - 'info', - 'initialize', - 'isBuilt', - 'isValid', - 'modelPropertyMacro', - 'models', - 'modelsArray', - 'options', - 'parameterMacro', - 'parseUri', - 'progress', - 'resourceCount', - 'sampleModels', - 'selfReflect', - 'setConsolidatedModels', - 'spec', - 'supportedSubmitMethods', - 'swaggerRequestHeaders', - 'tagFromLabel', - 'title', - 'url', - 'useJQuery', - 'jqueryAjaxCache' -]; -// We have to keep track of the function/property names to avoid collisions for tag names which are used to allow the -// following usage: 'client.apis.{tagName}' -var reservedApiTags = [ - 'apis', - 'asCurl', - 'description', - 'externalDocs', - 'help', - 'label', - 'name', - 'operation', - 'operations', - 'operationsArray', - 'path', - 'tag' -]; -var supportedOperationMethods = ['delete', 'get', 'head', 'options', 'patch', 'post', 'put']; -var SwaggerClient = module.exports = function (url, options) { - this.authorizations = null; - this.authorizationScheme = null; - this.basePath = null; - this.debug = false; - this.enableCookies = false; - this.info = null; - this.isBuilt = false; - this.isValid = false; - this.modelsArray = []; - this.resourceCount = 0; - this.url = null; - this.useJQuery = false; - this.jqueryAjaxCache = false; - this.swaggerObject = {}; - this.deferredClient = undefined; - - this.clientAuthorizations = new auth.SwaggerAuthorizations(); - - if (typeof url !== 'undefined') { - return this.initialize(url, options); - } else { - return this; - } -}; - -SwaggerClient.prototype.initialize = function (url, options) { - this.models = {}; - this.sampleModels = {}; - - if (typeof url === 'string') { - this.url = url; - } else if (_.isObject(url)) { - options = url; - this.url = options.url; - } - - if(this.url && this.url.indexOf('http:') === -1 && this.url.indexOf('https:') === -1) { - // no protocol, so we can only use window if it exists - if(typeof(window) !== 'undefined' && window && window.location) { - this.url = window.location.origin + this.url; - } - } - - options = options || {}; - this.clientAuthorizations.add(options.authorizations); - this.swaggerRequestHeaders = options.swaggerRequestHeaders || 'application/json;charset=utf-8,*/*'; - this.defaultSuccessCallback = options.defaultSuccessCallback || null; - this.defaultErrorCallback = options.defaultErrorCallback || null; - this.modelPropertyMacro = options.modelPropertyMacro || null; - this.connectionAgent = options.connectionAgent || null; - this.parameterMacro = options.parameterMacro || null; - this.usePromise = options.usePromise || null; - - // operation request timeout default - this.timeout = options.timeout || null; - // default to request timeout when not specified - this.fetchSpecTimeout = typeof options.fetchSpecTimeout !== 'undefined' ? - options.fetchSpecTimeout : options.timeout || null; - - if(this.usePromise) { - this.deferredClient = Q.defer(); - } - - if (typeof options.success === 'function') { - this.success = options.success; - } - if (options.useJQuery) { - this.useJQuery = options.useJQuery; - } - - if (options.jqueryAjaxCache) { - this.jqueryAjaxCache = options.jqueryAjaxCache; - } - - if (options.enableCookies) { - this.enableCookies = options.enableCookies; - } - - this.options = options || {}; - - // maybe don't need this? - this.options.timeout = this.timeout; - this.options.fetchSpecTimeout = this.fetchSpecTimeout; - - this.supportedSubmitMethods = options.supportedSubmitMethods || []; - this.failure = options.failure || function (err) { throw err; }; - this.progress = options.progress || function () {}; - this.spec = _.cloneDeep(options.spec); // Clone so we do not alter the provided document - - if (options.scheme) { - this.scheme = options.scheme; - } - - if (this.usePromise || typeof options.success === 'function') { - this.ready = true; - return this.build(); - } -}; - -SwaggerClient.prototype.build = function (mock) { - if (this.isBuilt) { - return this; - } - - var self = this; - - if (this.spec) { - this.progress('fetching resource list; Please wait.'); - } else { - this.progress('fetching resource list: ' + this.url + '; Please wait.'); - } - - var obj = { - useJQuery: this.useJQuery, - jqueryAjaxCache: this.jqueryAjaxCache, - connectionAgent: this.connectionAgent, - enableCookies: this.enableCookies, - url: this.url, - method: 'get', - headers: { - accept: this.swaggerRequestHeaders - }, - on: { - error: function (response) { - if (self.url.substring(0, 4) !== 'http') { - return self.fail('Please specify the protocol for ' + self.url); - } else if (response.errObj && (response.errObj.code === 'ECONNABORTED' || response.errObj.message.indexOf('timeout') !== -1)) { - return self.fail('Request timed out after ' + self.fetchSpecTimeout + 'ms'); - } else if (response.status === 0) { - return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.'); - } else if (response.status === 404) { - return self.fail('Can\'t read swagger JSON from ' + self.url); - } else { - return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url); - } - }, - response: function (resp) { - - var responseObj = resp.obj; - if(!responseObj) { - return self.fail('failed to parse JSON/YAML response'); - } - - self.swaggerVersion = responseObj.swaggerVersion; - self.swaggerObject = responseObj; - - if (responseObj.swagger && parseInt(responseObj.swagger) === 2) { - self.swaggerVersion = responseObj.swagger; - - new Resolver().resolve(responseObj, self.url, self.buildFromSpec, self); - - self.isValid = true; - } else { - var converter = new SwaggerSpecConverter(); - self.oldSwaggerObject = self.swaggerObject; - - converter.setDocumentationLocation(self.url); - converter.convert(responseObj, self.clientAuthorizations, self.options, function(spec) { - self.swaggerObject = spec; - new Resolver().resolve(spec, self.url, self.buildFromSpec, self); - self.isValid = true; - }); - } - } - } - }; - - // only set timeout when specified - if (this.fetchSpecTimeout) { - obj.timeout = this.fetchSpecTimeout; - } - - if (this.spec) { - self.swaggerObject = this.spec; - setTimeout(function () { - new Resolver().resolve(self.spec, self.url, self.buildFromSpec, self); - }, 10); - } else { - this.clientAuthorizations.apply(obj); - - if (mock) { - return obj; - } - - new SwaggerHttp().execute(obj, this.options); - } - - return (this.usePromise) ? this.deferredClient.promise : this; -}; - -SwaggerClient.prototype.buildFromSpec = function (response) { - if (this.isBuilt) { - return this; - } - - this.apis = {}; - this.apisArray = []; - this.basePath = response.basePath || ''; - this.consumes = response.consumes; - this.host = response.host || ''; - this.info = response.info || {}; - this.produces = response.produces; - this.schemes = response.schemes || []; - this.securityDefinitions = _.cloneDeep(response.securityDefinitions); - this.security = response.security; - this.title = response.title || ''; - - var key, definedTags = {}, k, location, self = this, i; - - if (response.externalDocs) { - this.externalDocs = response.externalDocs; - } - - // legacy support - this.authSchemes = this.securityDefinitions; - - if(this.securityDefinitions) { - for(key in this.securityDefinitions) { - var securityDefinition = this.securityDefinitions[key]; - securityDefinition.vendorExtensions = {}; - for(var ext in securityDefinition) { - helpers.extractExtensions(ext, securityDefinition); - if (ext === 'scopes') { - var scopes = securityDefinition[ext]; - if(typeof scopes === 'object') { - scopes.vendorExtensions = {}; - for (var s in scopes) { - helpers.extractExtensions(s, scopes); - if(s.indexOf('x-') === 0) { - delete scopes[s]; - } - } - } - } - } - } - } - - if (Array.isArray(response.tags)) { - definedTags = {}; - - for (k = 0; k < response.tags.length; k++) { - var t = _.cloneDeep(response.tags[k]); - definedTags[t.name] = t; - for(i in t) { - if(i === 'externalDocs' && typeof t[i] === 'object') { - for(var j in t[i]) { - helpers.extractExtensions(j, t[i]); - } - } - helpers.extractExtensions(i, t); - } - } - } - - - if (typeof this.url === 'string') { - location = this.parseUri(this.url); - if (typeof this.scheme === 'undefined' && typeof this.schemes === 'undefined' || this.schemes.length === 0) { - if(typeof window !== 'undefined') { - // use the window scheme - this.scheme = window.location.protocol.replace(':',''); - } - else { - this.scheme = location.scheme || 'http'; - } - } else if (typeof window !== 'undefined' && window.location.protocol.indexOf('chrome-extension') === 0) { - // if it is chrome swagger ui extension scheme then let swagger doc url scheme decide the protocol - this.scheme = location.scheme; - } else if (typeof this.scheme === 'undefined') { - if(typeof window !== 'undefined') { - var scheme = window.location.protocol.replace(':',''); - if(scheme === 'https' && this.schemes.indexOf(scheme) === -1) { - // can't call http from https served page in a browser! - helpers.log('Cannot call a http server from https inside a browser!'); - this.scheme = 'http'; - } - else if(this.schemes.indexOf(scheme) !== -1) { - this.scheme = scheme; - } - else { - if(this.schemes.indexOf('https') !== -1) { - this.scheme = 'https'; - } - else { - this.scheme = 'http'; - } - } - } - else { - this.scheme = this.schemes[0] || location.scheme; - } - } - - if (typeof this.host === 'undefined' || this.host === '') { - this.host = location.host; - - if (location.port) { - this.host = this.host + ':' + location.port; - } - } - } - else { - if (typeof this.schemes === 'undefined' || this.schemes.length === 0) { - this.scheme = 'http'; - } - else if (typeof this.scheme === 'undefined') { - this.scheme = this.schemes[0]; - } - } - - this.definitions = response.definitions; - - for (key in this.definitions) { - var model = new Model(key, this.definitions[key], this.models, this.modelPropertyMacro); - - if (model) { - this.models[key] = model; - } - } - - // get paths, create functions for each operationId - - // Bind help to 'client.apis' - self.apis.help = _.bind(self.help, self); - - _.forEach(response.paths, function (pathObj, path) { - // Only process a path if it's an object - if (!_.isPlainObject(pathObj)) { - return; - } - - _.forEach(supportedOperationMethods, function (method) { - var operation = pathObj[method]; - - if (_.isUndefined(operation)) { - // Operation does not exist - return; - } else if (!_.isPlainObject(operation)) { - // Operation exists but it is not an Operation Object. Since this is invalid, log it. - helpers.log('The \'' + method + '\' operation for \'' + path + '\' path is not an Operation Object'); - - return; - } - - var tags = operation.tags; - - if (_.isUndefined(tags) || !_.isArray(tags) || tags.length === 0) { - tags = operation.tags = [ 'default' ]; - } - - var operationId = self.idFromOp(path, method, operation); - - var operationObject = new Operation(self, - operation.scheme, - operationId, - method, - path, - operation, - self.definitions, - self.models, - self.clientAuthorizations); - - operationObject.connectionAgent = self.connectionAgent; - operationObject.vendorExtensions = {}; - for(i in operation) { - helpers.extractExtensions(i, operationObject, operation[i]); - } - operationObject.externalDocs = operation.externalDocs; - if(operationObject.externalDocs) { - operationObject.externalDocs = _.cloneDeep(operationObject.externalDocs); - operationObject.externalDocs.vendorExtensions = {}; - for(i in operationObject.externalDocs) { - helpers.extractExtensions(i, operationObject.externalDocs); - } - } - - // bind self operation's execute command to the api - _.forEach(tags, function (tag) { - var clientProperty = _.indexOf(reservedClientTags, tag) > -1 ? '_' + tag : tag; - var apiProperty = _.indexOf(reservedApiTags, tag) > -1 ? '_' + tag : tag; - var operationGroup = self[clientProperty]; - - if (clientProperty !== tag) { - helpers.log('The \'' + tag + '\' tag conflicts with a SwaggerClient function/property name. Use \'client.' + - clientProperty + '\' or \'client.apis.' + tag + '\' instead of \'client.' + tag + '\'.'); - } - - if (apiProperty !== tag) { - helpers.log('The \'' + tag + '\' tag conflicts with a SwaggerClient operation function/property name. Use ' + - '\'client.apis.' + apiProperty + '\' instead of \'client.apis.' + tag + '\'.'); - } - - if (_.indexOf(reservedApiTags, operationId) > -1) { - helpers.log('The \'' + operationId + '\' operationId conflicts with a SwaggerClient operation ' + - 'function/property name. Use \'client.apis.' + apiProperty + '._' + operationId + - '\' instead of \'client.apis.' + apiProperty + '.' + operationId + '\'.'); - - operationId = '_' + operationId; - operationObject.nickname = operationId; // So 'client.apis.[tag].operationId.help() works properly - } - - if (_.isUndefined(operationGroup)) { - operationGroup = self[clientProperty] = self.apis[apiProperty] = {}; - - operationGroup.operations = {}; - operationGroup.label = apiProperty; - operationGroup.apis = {}; - - var tagDef = definedTags[tag]; - - if (!_.isUndefined(tagDef)) { - operationGroup.description = tagDef.description; - operationGroup.externalDocs = tagDef.externalDocs; - operationGroup.vendorExtensions = tagDef.vendorExtensions; - } - - self[clientProperty].help = _.bind(self.help, operationGroup); - self.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject)); - } - - operationId = self.makeUniqueOperationId(operationId, self.apis[apiProperty]); - - // Bind tag help - if (!_.isFunction(operationGroup.help)) { - operationGroup.help = _.bind(self.help, operationGroup); - } - - // bind to the apis object - self.apis[apiProperty][operationId] = operationGroup[operationId] = _.bind(operationObject.execute, - operationObject); - self.apis[apiProperty][operationId].help = operationGroup[operationId].help = _.bind(operationObject.help, - operationObject); - self.apis[apiProperty][operationId].asCurl = operationGroup[operationId].asCurl = _.bind(operationObject.asCurl, - operationObject); - - operationGroup.apis[operationId] = operationGroup.operations[operationId] = operationObject; - - // legacy UI feature - var api = _.find(self.apisArray, function (api) { - return api.tag === tag; - }); - - if (api) { - api.operationsArray.push(operationObject); - } - }); - }); - }); - - // sort the apisArray according to the tags - var sortedApis = []; - _.forEach(Object.keys(definedTags), function (tag) { - var pos; - for(pos in self.apisArray) { - var _api = self.apisArray[pos]; - if(_api && tag === _api.name) { - sortedApis.push(_api); - self.apisArray[pos] = null; - } - } - }); - // add anything left - _.forEach(self.apisArray, function (api) { - if(api) { - sortedApis.push(api); - } - }); - self.apisArray = sortedApis; - - _.forEach(response.definitions, function (definitionObj, definition) { - definitionObj.id = definition.toLowerCase(); - definitionObj.name = definition; - self.modelsArray.push(definitionObj); - }); - - this.isBuilt = true; - - if (this.usePromise) { - this.isValid = true; - this.isBuilt = true; - this.deferredClient.resolve(this); - - return this.deferredClient.promise; - } - - if (this.success) { - this.success(); - } - - return this; -}; - -SwaggerClient.prototype.makeUniqueOperationId = function(operationId, api) { - var count = 0; - var name = operationId; - - // make unique across this operation group - while(true) { - var matched = false; - _.forEach(api.operations, function (operation) { - if(operation.nickname === name) { - matched = true; - } - }); - if(!matched) { - return name; - } - name = operationId + '_' + count; - count ++; - } - - return operationId; -}; - -SwaggerClient.prototype.parseUri = function (uri) { - var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/; - var parts = urlParseRE.exec(uri); - - return { - scheme: parts[4] ? parts[4].replace(':','') : undefined, - host: parts[11], - port: parts[12], - path: parts[15] - }; -}; - -SwaggerClient.prototype.help = function (dontPrint) { - var output = ''; - - if (this instanceof SwaggerClient) { - _.forEach(this.apis, function (api, name) { - if (_.isPlainObject(api)) { - output += 'operations for the \'' + name + '\' tag\n'; - - _.forEach(api.operations, function (operation, name) { - output += ' * ' + name + ': ' + operation.summary + '\n'; - }); - } - }); - } else if (this instanceof OperationGroup || _.isPlainObject(this)) { - output += 'operations for the \'' + this.label + '\' tag\n'; - - _.forEach(this.apis, function (operation, name) { - output += ' * ' + name + ': ' + operation.summary + '\n'; - }); - } - - if (dontPrint) { - return output; - } else { - helpers.log(output); - - return output; - } -}; - -SwaggerClient.prototype.tagFromLabel = function (label) { - return label; -}; - -SwaggerClient.prototype.idFromOp = function (path, httpMethod, op) { - if(!op || !op.operationId) { - op = op || {}; - op.operationId = httpMethod + '_' + path; - } - var opId = op.operationId.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_') || (path.substring(1) + '_' + httpMethod); - - opId = opId.replace(/((_){2,})/g, '_'); - opId = opId.replace(/^(_)*/g, ''); - opId = opId.replace(/([_])*$/g, ''); - - return opId; -}; - -SwaggerClient.prototype.setHost = function (host) { - this.host = host; - - if(this.apis) { - _.forEach(this.apis, function(api) { - if(api.operations) { - _.forEach(api.operations, function(operation) { - operation.host = host; - }); - } - }); - } -}; - -SwaggerClient.prototype.setBasePath = function (basePath) { - this.basePath = basePath; - - if(this.apis) { - _.forEach(this.apis, function(api) { - if(api.operations) { - _.forEach(api.operations, function(operation) { - operation.basePath = basePath; - }); - } - }); - } -}; - -SwaggerClient.prototype.setSchemes = function (schemes) { - this.schemes = schemes; - - if(schemes && schemes.length > 0) { - if(this.apis) { - _.forEach(this.apis, function (api) { - if (api.operations) { - _.forEach(api.operations, function (operation) { - operation.scheme = schemes[0]; - }); - } - }); - } - } -}; - -SwaggerClient.prototype.fail = function (message) { - if (this.usePromise) { - this.deferredClient.reject(message); - return this.deferredClient.promise; - } else { - if (this.failure) { - this.failure(message); - } - else { - this.failure(message); - } - } -}; - -},{"./auth":2,"./helpers":4,"./http":5,"./resolver":6,"./spec-converter":8,"./types/model":9,"./types/operation":10,"./types/operationGroup":11,"lodash-compat/array/indexOf":49,"lodash-compat/collection/find":53,"lodash-compat/collection/forEach":54,"lodash-compat/function/bind":58,"lodash-compat/lang/cloneDeep":138,"lodash-compat/lang/isArray":140,"lodash-compat/lang/isFunction":142,"lodash-compat/lang/isObject":144,"lodash-compat/lang/isPlainObject":145,"lodash-compat/lang/isUndefined":148,"q":157}],4:[function(require,module,exports){ -(function (process){ -'use strict'; - -var _ = { - isPlainObject: require('lodash-compat/lang/isPlainObject'), - indexOf: require('lodash-compat/array/indexOf') -}; - -module.exports.__bind = function (fn, me) { - return function(){ - return fn.apply(me, arguments); - }; -}; - -var log = module.exports.log = function() { - // Only log if available and we're not testing - if (console && process.env.NODE_ENV !== 'test') { - console.log(Array.prototype.slice.call(arguments)[0]); - } -}; - -module.exports.fail = function (message) { - log(message); -}; - -module.exports.optionHtml = function (label, value) { - return '' + label + ':' + value + ''; -}; - -var resolveSchema = module.exports.resolveSchema = function (schema) { - if (_.isPlainObject(schema.schema)) { - schema = resolveSchema(schema.schema); - } - - return schema; -}; - -module.exports.simpleRef = function (name) { - if (typeof name === 'undefined') { - return null; - } - - if (name.indexOf('#/definitions/') === 0) { - return name.substring('#/definitions/'.length); - } else { - return name; - } -}; - -/** - * helper to remove extensions and add them to an object - * - * @param keyname - * @param obj - */ -module.exports.extractExtensions = function (keyname, obj, value) { - if(!keyname || !obj) { - return; - } - - if (typeof keyname === 'string' && keyname.indexOf('x-') === 0) { - obj.vendorExtensions = obj.vendorExtensions || {}; - if(value) { - obj.vendorExtensions[keyname] = value; - } - else { - obj.vendorExtensions[keyname] = obj[keyname]; - } - } -}; -}).call(this,require('_process')) - -},{"_process":12,"lodash-compat/array/indexOf":49,"lodash-compat/lang/isPlainObject":145}],5:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var helpers = require('./helpers'); -var request = require('superagent'); -var jsyaml = require('js-yaml'); -var _ = { - isObject: require('lodash-compat/lang/isObject'), - keys: require('lodash-compat/object/keys') -}; - -/* - * JQueryHttpClient is a light-weight, node or browser HTTP client - */ -var JQueryHttpClient = function () { - this.type = 'JQueryHttpClient'; -}; - -/* - * SuperagentHttpClient is a light-weight, node or browser HTTP client - */ -var SuperagentHttpClient = function () { - this.type = 'SuperagentHttpClient'; -}; - -/** - * SwaggerHttp is a wrapper for executing requests - */ -var SwaggerHttp = module.exports = function () {}; - -SwaggerHttp.prototype.execute = function (obj, opts) { - var client; - - if(opts && opts.client) { - client = opts.client; - } - else { - client = new SuperagentHttpClient(opts); - } - client.opts = opts || {}; - - if (opts && opts.requestAgent) { - request = opts.requestAgent; - } - - // legacy support - var hasJQuery = false; - if(typeof window !== 'undefined') { - if(typeof window.jQuery !== 'undefined') { - hasJQuery = true; - } - } - // OPTIONS support - if(obj.method.toLowerCase() === 'options' && client.type === 'SuperagentHttpClient') { - log('forcing jQuery as OPTIONS are not supported by SuperAgent'); - obj.useJQuery = true; - } - if(this.isInternetExplorer() && (obj.useJQuery === false || !hasJQuery )) { - throw new Error('Unsupported configuration! JQuery is required but not available'); - } - if ((obj && obj.useJQuery === true) || this.isInternetExplorer() && hasJQuery) { - client = new JQueryHttpClient(opts); - } - - var success = obj.on.response; - var error = obj.on.error; - - var requestInterceptor = function(data) { - if(opts && opts.requestInterceptor) { - data = opts.requestInterceptor.apply(data); - } - return data; - }; - - var responseInterceptor = function(data) { - if(opts && opts.responseInterceptor) { - data = opts.responseInterceptor.apply(data, [obj]); - } - return success(data); - }; - - var errorInterceptor = function(data) { - if(opts && opts.responseInterceptor) { - data = opts.responseInterceptor.apply(data, [obj]); - } - error(data); - }; - - obj.on.error = function(data) { - errorInterceptor(data); - }; - - obj.on.response = function(data) { - if(data && data.status >= 400) { - errorInterceptor(data); - } - else { - responseInterceptor(data); - } - }; - - if (_.isObject(obj) && _.isObject(obj.body)) { - // special processing for file uploads via jquery - if (obj.body.type && obj.body.type === 'formData'){ - if(opts.useJQuery) { - obj.contentType = false; - obj.processData = false; - delete obj.headers['Content-Type']; - } - } - } - - obj = requestInterceptor(obj) || obj; - if (obj.beforeSend) { - obj.beforeSend(function(_obj) { - client.execute(_obj || obj); - }); - } else { - client.execute(obj); - } - - return (obj.deferred) ? obj.deferred.promise : obj; -}; - -SwaggerHttp.prototype.isInternetExplorer = function () { - var detectedIE = false; - - if (typeof navigator !== 'undefined' && navigator.userAgent) { - var nav = navigator.userAgent.toLowerCase(); - - if (nav.indexOf('msie') !== -1) { - var version = parseInt(nav.split('msie')[1]); - - if (version <= 8) { - detectedIE = true; - } - } - } - - return detectedIE; -}; - -JQueryHttpClient.prototype.execute = function (obj) { - var jq = this.jQuery || (typeof window !== 'undefined' && window.jQuery); - var cb = obj.on; - var request = obj; - - if(typeof jq === 'undefined' || jq === false) { - throw new Error('Unsupported configuration! JQuery is required but not available'); - } - - obj.type = obj.method; - obj.cache = obj.jqueryAjaxCache; - obj.data = obj.body; - delete obj.jqueryAjaxCache; - delete obj.useJQuery; - delete obj.body; - - obj.complete = function (response) { - var headers = {}; - var headerArray = response.getAllResponseHeaders().split('\n'); - - for (var i = 0; i < headerArray.length; i++) { - var toSplit = headerArray[i].trim(); - - if (toSplit.length === 0) { - continue; - } - - var separator = toSplit.indexOf(':'); - - if (separator === -1) { - // Name but no value in the header - headers[toSplit] = null; - - continue; - } - - var name = toSplit.substring(0, separator).trim(); - var value = toSplit.substring(separator + 1).trim(); - - headers[name] = value; - } - - var out = { - url: request.url, - method: request.method, - status: response.status, - statusText: response.statusText, - data: response.responseText, - headers: headers - }; - - try { - var possibleObj = response.responseJSON || jsyaml.safeLoad(response.responseText); - out.obj = (typeof possibleObj === 'string') ? {} : possibleObj; - } catch (ex) { - // do not set out.obj - helpers.log('unable to parse JSON/YAML content'); - } - - // I can throw, or parse null? - out.obj = out.obj || null; - - if (response.status >= 200 && response.status < 300) { - cb.response(out); - } else if (response.status === 0 || (response.status >= 400 && response.status < 599)) { - cb.error(out); - } else { - return cb.response(out); - } - }; - - jq.support.cors = true; - - return jq.ajax(obj); -}; - -SuperagentHttpClient.prototype.execute = function (obj) { - var method = obj.method.toLowerCase(); - var timeout = obj.timeout; - - if (method === 'delete') { - method = 'del'; - } - var headers = obj.headers || {}; - - var r = request[method](obj.url); - - if (obj.connectionAgent) { - r.agent(obj.connectionAgent); - } - - if (timeout) { - r.timeout(timeout); - } - - if (obj.enableCookies) { - r.withCredentials(); - } - - var accept = obj.headers.Accept; - - if(this.binaryRequest(accept)) { - r.on('request', function () { - if(this.xhr) { - this.xhr.responseType = 'blob'; - } - }); - } - - if(obj.body) { - if(_.isObject(obj.body)) { - var contentType = obj.headers['Content-Type'] || ''; - if (contentType.indexOf('multipart/form-data') === 0) { - delete headers['Content-Type']; - if({}.toString.apply(obj.body) === '[object FormData]') { - r.send(obj.body); - } - else { - var keyname, value, v; - for (keyname in obj.body) { - value = obj.body[keyname]; - if(Array.isArray(value)) { - for(v in value) { - r.field(keyname, v); - } - } - else { - r.field(keyname, value); - } - } - } - } - else if (_.isObject(obj.body)) { - // non multipart/form-data - obj.body = JSON.stringify(obj.body); - r.send(obj.body); - } - } - else { - r.send(obj.body); - } - } - - var name; - for (name in headers) { - r.set(name, headers[name]); - } - - if(typeof r.buffer === 'function') { - r.buffer(); // force superagent to populate res.text with the raw response data - } - - r.end(function (err, res) { - res = res || { - status: 0, - headers: {error: 'no response from server'} - }; - var response = { - url: obj.url, - method: obj.method, - headers: res.headers - }; - var cb; - - if (!err && res.error) { - err = res.error; - } - - if (err && obj.on && obj.on.error) { - response.errObj = err; - response.status = res ? res.status : 500; - response.statusText = res ? res.text : err.message; - if (res.headers && res.headers['content-type']) { - if (res.headers['content-type'].indexOf('application/json') >= 0) { - try { - response.obj = JSON.parse(response.statusText); - } - catch (e) { - response.obj = null; - } - } - } - cb = obj.on.error; - } else if (res && obj.on && obj.on.response) { - var possibleObj; - - // Already parsed by by superagent? - if (res.body && _.keys(res.body).length > 0) { - possibleObj = res.body; - } else { - try { - possibleObj = jsyaml.safeLoad(res.text); - // can parse into a string... which we don't need running around in the system - possibleObj = (typeof possibleObj === 'string') ? null : possibleObj; - } catch (e) { - helpers.log('cannot parse JSON/YAML content'); - } - } - - // null means we can't parse into object - if(typeof Buffer === 'function' && Buffer.isBuffer(possibleObj)) { - response.data = possibleObj; - } - else { - response.obj = (typeof possibleObj === 'object') ? possibleObj : null; - } - - response.status = res.status; - response.statusText = res.text; - cb = obj.on.response; - } - if (res.xhr && res.xhr.response) { - response.data = res.xhr.response; - } - else if(!response.data) { - response.data = response.statusText; - } - - if (cb) { - cb(response); - } - }); -}; - -SuperagentHttpClient.prototype. binaryRequest = function (accept) { - if(!accept) { - return false; - } - return (/^image/i).test(accept) - || (/^application\/pdf/).test(accept) - || (/^application\/octet-stream/).test(accept); -}; - -}).call(this,require("buffer").Buffer) - -},{"./helpers":4,"buffer":14,"js-yaml":19,"lodash-compat/lang/isObject":144,"lodash-compat/object/keys":149,"superagent":158}],6:[function(require,module,exports){ -'use strict'; - -var SwaggerHttp = require('./http'); -var _ = { - isObject: require('lodash-compat/lang/isObject'), - cloneDeep: require('lodash-compat/lang/cloneDeep'), - isArray: require('lodash-compat/lang/isArray'), - isString: require('lodash-compat/lang/isString') -}; - - -/** - * Resolves a spec's remote references - */ -var Resolver = module.exports = function () { - this.failedUrls = []; - this.resolverCache = {}; - this.pendingUrls = {}; -}; - -Resolver.prototype.processAllOf = function(root, name, definition, resolutionTable, unresolvedRefs, spec) { - var i, location, property; - - definition['x-resolved-from'] = [ '#/definitions/' + name ]; - var allOf = definition.allOf; - // the refs go first - allOf.sort(function(a, b) { - if(a.$ref && b.$ref) { return 0; } - else if(a.$ref) { return -1; } - else { return 1; } - }); - for (i = 0; i < allOf.length; i++) { - property = allOf[i]; - location = '/definitions/' + name + '/allOf'; - this.resolveInline(root, spec, property, resolutionTable, unresolvedRefs, location); - } -}; - -Resolver.prototype.resolve = function (spec, arg1, arg2, arg3) { - this.spec = spec; - var root = arg1, callback = arg2, scope = arg3, opts = {}, location, i; - if(typeof arg1 === 'function') { - root = null; - callback = arg1; - scope = arg2; - } - var _root = root, modelName; - this.scope = (scope || this); - this.iteration = this.iteration || 0; - - if(this.scope.options && this.scope.options.requestInterceptor){ - opts.requestInterceptor = this.scope.options.requestInterceptor; - } - - if(this.scope.options && this.scope.options.responseInterceptor){ - opts.responseInterceptor = this.scope.options.responseInterceptor; - } - - var name, path, property, propertyName, parameter, done, counter; - var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {}; - var resolutionTable = []; // store objects for dereferencing - - spec.definitions = spec.definitions || {}; - // definitions - for (name in spec.definitions) { - var definition = spec.definitions[name]; - if(definition.$ref) { - this.resolveInline(root, spec, definition, resolutionTable, unresolvedRefs, definition); - } - else { - for (propertyName in definition.properties) { - property = definition.properties[propertyName]; - if (_.isArray(property.allOf)) { - this.processAllOf(root, name, property, resolutionTable, unresolvedRefs, spec); - } - else { - this.resolveTo(root, property, resolutionTable, '/definitions'); - } - } - - if (definition.allOf) { - this.processAllOf(root, name, definition, resolutionTable, unresolvedRefs, spec); - } - } - } - - // shared parameters - spec.parameters = spec.parameters || {}; - for(name in spec.parameters) { - parameter = spec.parameters[name]; - if (parameter.in === 'body' && parameter.schema) { - if(_.isArray(parameter.schema.allOf)) { - // move to a definition - modelName = 'inline_model'; - var _name = modelName; - done = false; counter = 0; - while(!done) { - if(typeof spec.definitions[_name] === 'undefined') { - done = true; - break; - } - _name = modelName + '_' + counter; - counter ++; - } - spec.definitions[_name] = { allOf: parameter.schema.allOf }; - delete parameter.schema.allOf; - parameter.schema.$ref = '#/definitions/' + _name; - this.processAllOf(root, _name, spec.definitions[_name], resolutionTable, unresolvedRefs, spec); - } - else { - this.resolveTo(root, parameter.schema, resolutionTable, location); - } - } - - if (parameter.$ref) { - // parameter reference - this.resolveInline(root, spec, parameter, resolutionTable, unresolvedRefs, parameter.$ref); - } - } - - // operations - for (name in spec.paths) { - var method, operation, responseCode; - path = spec.paths[name]; - - if(typeof path === 'object') { - for (method in path) { - // operation reference - if (method === '$ref') { - // location = path[method]; - location = '/paths' + name; - this.resolveInline(root, spec, path, resolutionTable, unresolvedRefs, location); - } - else { - operation = path[method]; - var sharedParameters = path.parameters || []; - var parameters = operation.parameters || []; - - sharedParameters.forEach(function(parameter) { - parameters.unshift(parameter); - }); - - if (method !== 'parameters' && _.isObject(operation)) { - operation.parameters = operation.parameters || parameters; - } - - for (i in parameters) { - parameter = parameters[i]; - location = '/paths' + name + '/' + method + '/parameters'; - - if (parameter.in === 'body' && parameter.schema) { - if (_.isArray(parameter.schema.allOf)) { - // move to a definition - modelName = 'inline_model'; - name = modelName; - done = false; - counter = 0; - while (!done) { - if (typeof spec.definitions[name] === 'undefined') { - done = true; - break; - } - name = modelName + '_' + counter; - counter++; - } - spec.definitions[name] = {allOf: parameter.schema.allOf}; - delete parameter.schema.allOf; - parameter.schema.$ref = '#/definitions/' + name; - this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec); - } - else { - this.resolveTo(root, parameter.schema, resolutionTable, location); - } - } - - if (parameter.$ref) { - // parameter reference - this.resolveInline(root, spec, parameter, resolutionTable, unresolvedRefs, parameter.$ref); - } - } - - for (responseCode in operation.responses) { - var response = operation.responses[responseCode]; - location = '/paths' + name + '/' + method + '/responses/' + responseCode; - - if (_.isObject(response)) { - if (response.$ref) { - // response reference - this.resolveInline(root, spec, response, resolutionTable, unresolvedRefs, location); - } - if (response.schema) { - var responseObj = response; - if (_.isArray(responseObj.schema.allOf)) { - // move to a definition - modelName = 'inline_model'; - name = modelName; - done = false; - counter = 0; - while (!done) { - if (typeof spec.definitions[name] === 'undefined') { - done = true; - break; - } - name = modelName + '_' + counter; - counter++; - } - spec.definitions[name] = {allOf: responseObj.schema.allOf}; - delete responseObj.schema.allOf; - delete responseObj.schema.type; - responseObj.schema.$ref = '#/definitions/' + name; - this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec); - } - else if ('array' === responseObj.schema.type) { - if (responseObj.schema.items && responseObj.schema.items.$ref) { - // response reference - this.resolveInline(root, spec, responseObj.schema.items, resolutionTable, unresolvedRefs, location); - } - } - else { - this.resolveTo(root, response.schema, resolutionTable, location); - } - } - } - } - } - } - // clear them out to avoid multiple resolutions - path.parameters = []; - } - } - - var expectedCalls = 0, toResolve = []; - // if the root is same as obj[i].root we can resolve locally - var all = resolutionTable; - - var parts; - for(i = 0; i < all.length; i++) { - var a = all[i]; - if(root === a.root) { - if(a.resolveAs === 'ref') { - // resolve any path walking - var joined = ((a.root || '') + '/' + a.key).split('/'); - var normalized = []; - var url = ''; - var k; - - if(a.key.indexOf('../') >= 0) { - for(var j = 0; j < joined.length; j++) { - if(joined[j] === '..') { - normalized = normalized.slice(0, normalized.length-1); - } - else { - normalized.push(joined[j]); - } - } - for(k = 0; k < normalized.length; k ++) { - if(k > 0) { - url += '/'; - } - url += normalized[k]; - } - // we now have to remote resolve this because the path has changed - a.root = url; - toResolve.push(a); - } - else { - parts = a.key.split('#'); - if(parts.length === 2) { - if(parts[0].indexOf('http:') === 0 || parts[0].indexOf('https:') === 0) { - a.root = parts[0]; - } - location = parts[1].split('/'); - var r; - var s = spec; - for(k = 0; k < location.length; k++) { - var part = location[k]; - if(part !== '') { - s = s[part]; - if(typeof s !== 'undefined') { - r = s; - } - else { - r = null; - break; - } - } - } - if(r === null) { - // must resolve this too - toResolve.push(a); - } - } - } - } - else { - if (a.resolveAs === 'inline') { - if(a.key && a.key.indexOf('#') === -1 && a.key.charAt(0) !== '/') { - // handle relative schema - parts = a.root.split('/'); - location = ''; - for(i = 0; i < parts.length - 1; i++) { - location += parts[i] + '/'; - } - location += a.key; - a.root = location; - a.location = ''; - } - toResolve.push(a); - } - } - } - else { - toResolve.push(a); - } - } - expectedCalls = toResolve.length; - - // resolve anything that is local - - var lock = {}; - for(var ii = 0; ii < toResolve.length; ii++) { - (function(item, spec, self, lock, ii) { - if(!item.root || item.root === root) { - // local resolve - self.resolveItem(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, item); - processedCalls += 1; - - if(processedCalls === expectedCalls) { - self.finish(spec, root, resolutionTable, resolvedRefs, unresolvedRefs, callback, true); - } - } - else if(self.failedUrls.indexOf(item.root) === -1) { - var obj = { - useJQuery: false, // TODO - url: item.root, - method: 'get', - headers: { - accept: self.scope.swaggerRequestHeaders || 'application/json' - }, - on: { - error: function (error) { - processedCalls += 1; - console.log('failed url: ' + obj.url); - self.failedUrls.push(obj.url); - if (lock) { - delete lock[item.root]; - } - unresolvedRefs[item.key] = { - root: item.root, - location: item.location - }; - - if (processedCalls === expectedCalls) { - self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback); - } - }, // jshint ignore:line - response: function (response) { - var swagger = response.obj; - if (lock) { - delete lock[item.root]; - } - if (self.resolverCache) { - self.resolverCache[item.root] = swagger; - } - self.resolveItem(swagger, item.root, resolutionTable, resolvedRefs, unresolvedRefs, item); - processedCalls += 1; - - if (processedCalls === expectedCalls) { - self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback); - } - } - } // jshint ignore:line - }; - - // apply timeout only when specified - if (scope && scope.fetchSpecTimeout) { - obj.timeout = scope.fetchSpecTimeout; - } - - if (scope && scope.clientAuthorizations) { - scope.clientAuthorizations.apply(obj); - } - - (function waitForUnlock() { - setTimeout(function() { - if (lock[obj.url]) { - waitForUnlock(); - } - else { - var cached = self.resolverCache[obj.url]; - if (_.isObject(cached)) { - obj.on.response({obj: cached}); - } - else { - lock[obj.url] = true; - new SwaggerHttp().execute(obj, opts); - } - } - }, 0); - })(); - } - - else { - processedCalls += 1; - unresolvedRefs[item.key] = { - root: item.root, - location: item.location - }; - if (processedCalls === expectedCalls) { - self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback); - } - } - }(toResolve[ii], spec, this, lock, ii)); - } - - if (Object.keys(toResolve).length === 0) { - this.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback); - } -}; - -Resolver.prototype.resolveItem = function(spec, root, resolutionTable, resolvedRefs, unresolvedRefs, item) { - var path = item.location; - var location = spec, parts = path.split('/'); - if(path !== '') { - for (var j = 0; j < parts.length; j++) { - var segment = parts[j]; - if (segment.indexOf('~1') !== -1) { - segment = parts[j].replace(/~0/g, '~').replace(/~1/g, '/'); - if (segment.charAt(0) !== '/') { - segment = '/' + segment; - } - } - if (typeof location === 'undefined' || location === null) { - break; - } - if (segment === '' && j === (parts.length - 1) && parts.length > 1) { - location = null; - break; - } - if (segment.length > 0) { - location = location[segment]; - } - } - } - var resolved = item.key; - parts = item.key.split('/'); - var resolvedName = parts[parts.length-1]; - - if(resolvedName.indexOf('#') >= 0) { - resolvedName = resolvedName.split('#')[1]; - } - - if (location !== null && typeof location !== 'undefined') { - resolvedRefs[resolved] = { - name: resolvedName, - obj: location, - key: item.key, - root: item.root - }; - } else { - unresolvedRefs[resolved] = { - root: item.root, - location: item.location - }; - } -}; - -Resolver.prototype.finish = function (spec, root, resolutionTable, resolvedRefs, unresolvedRefs, callback, localResolve) { - // walk resolution table and replace with resolved refs - var ref, abs; - for (ref in resolutionTable) { - var item = resolutionTable[ref]; - - var key = item.key; - var resolvedTo = resolvedRefs[key]; - if (resolvedTo) { - spec.definitions = spec.definitions || {}; - if (item.resolveAs === 'ref') { - if (localResolve !== true) { - // don't retain root for local definitions - for (key in resolvedTo.obj) { - abs = this.retainRoot(key, resolvedTo.obj[key], item.root); - resolvedTo.obj[key] = abs; - } - } - spec.definitions[resolvedTo.name] = resolvedTo.obj; - item.obj.$ref = '#/definitions/' + resolvedTo.name; - } else if (item.resolveAs === 'inline') { - var targetObj = item.obj; - targetObj['x-resolved-from'] = [ item.key ]; - delete targetObj.$ref; - - for (key in resolvedTo.obj) { - abs = resolvedTo.obj[key]; - - if (localResolve !== true) { - // don't retain root for local definitions - abs = this.retainRoot(key, resolvedTo.obj[key], item.root); - } - targetObj[key] = abs; - } - } - } - } - var existingUnresolved = this.countUnresolvedRefs(spec); - - if(existingUnresolved === 0 || this.iteration > 5) { - this.resolveAllOf(spec.definitions); - this.resolverCache = null; - callback.call(this.scope, spec, unresolvedRefs); - } - else { - this.iteration += 1; - this.resolve(spec, root, callback, this.scope); - } -}; - -Resolver.prototype.countUnresolvedRefs = function(spec) { - var i; - var refs = this.getRefs(spec); - var keys = []; - var unresolvedKeys = []; - for(i in refs) { - if(i.indexOf('#') === 0) { - keys.push(i.substring(1)); - } - else { - unresolvedKeys.push(i); - } - } - - // verify possible keys - for (i = 0; i < keys.length; i++) { - var part = keys[i]; - var parts = part.split('/'); - var obj = spec; - - for (var k = 0; k < parts.length; k++) { - var key = parts[k]; - if(key !== '') { - obj = obj[key]; - if(typeof obj === 'undefined') { - unresolvedKeys.push(part); - break; - } - } - } - } - return unresolvedKeys.length; -}; - -Resolver.prototype.getRefs = function(spec, obj) { - obj = obj || spec; - var output = {}; - for(var key in obj) { - if (!obj.hasOwnProperty(key)) { - continue; - } - var item = obj[key]; - if(key === '$ref' && typeof item === 'string') { - output[item] = null; - } - else if(_.isObject(item)) { - var o = this.getRefs(item); - for(var k in o) { - output[k] = null; - } - } - } - return output; -}; - -function splitUrl(url) { - var result = {}; - var proto = /[a-z]+:\/\//i.exec(url); - if (proto) { - result.proto = proto[0].slice(0, -3); - url = url.slice(result.proto.length + 1); - } - if (url.slice(0, 2) === '//') { - result.domain = url.slice(2).split('/')[0]; - url = url.slice(2 + result.domain.length); - } - var p = url.split('#'); - if (p[0].length) { - result.path = p[0]; - } - if (p.length > 1) { - result.fragment = p.slice(1).join('#'); - } - return result; -} - -function unsplitUrl(url) { - var result = url.path; - if (result === undefined) { - result = ''; - } - if (url.fragment !== undefined) { - result += '#' + url.fragment; - } - if (url.domain !== undefined) { - if (result.slice(0, 1) === '/') { - result = result.slice(1); - } - result = '//' + url.domain + '/' + result; - if (url.proto !== undefined) { - result = url.proto + ':' + result; - } - } - return result; -} - -function joinUrl(base, rel) { - var relsp = splitUrl(rel); - if (relsp.domain !== undefined) { - return rel; - } - var result = splitUrl(base); - if (relsp.path === undefined) { - // change only fragment part - result.fragment = relsp.fragment; - } else if (relsp.path.slice(0, 1) === '/') { - // relative to domain - result.path = relsp.path; - result.fragment = relsp.fragment; - } else { - // relative to path - var path = result.path === undefined ? [] : result.path.split('/'); - var relpath = relsp.path.split('/'); - if (path.length) { - path.pop(); - } - while (relpath[0] === '..' || relpath[0] === '.') { - if (relpath[0] === '..') { - path.pop(); - } - relpath.shift(); - } - result.path = path.concat(relpath).join('/'); - result.fragment = relsp.fragment; - } - return unsplitUrl(result); -} - -Resolver.prototype.retainRoot = function(origKey, obj, root) { - // walk object and look for relative $refs - if(_.isObject(obj)) { - for(var key in obj) { - var item = obj[key]; - if (key === '$ref' && typeof item === 'string') { - obj[key] = joinUrl(root, item); - } - else if (_.isObject(item)) { - this.retainRoot(key, item, root); - } - } - } - else if(_.isString(obj) && origKey === '$ref') { - obj = joinUrl(root, obj); - } - return obj; -}; - -/** - * immediately in-lines local refs, queues remote refs - * for inline resolution - */ -Resolver.prototype.resolveInline = function (root, spec, property, resolutionTable, unresolvedRefs, location) { - var key = property.$ref, ref = property.$ref, i, p, p2, rs; - var rootTrimmed = false; - - root = root || ''; // Guard against .split. @fehguy, you'll need to check if this logic fits - // More imporantly is how do we gracefully handle relative urls, when provided just a 'spec', not a 'url' ? - - if (ref) { - if(ref.indexOf('../') === 0) { - // reset root - p = ref.split('../'); - p2 = root.split('/'); - ref = ''; - for(i = 0; i < p.length; i++) { - if(p[i] === '') { - p2 = p2.slice(0, p2.length-1); - } - else { - ref += p[i]; - } - } - root = ''; - for(i = 0; i < p2.length - 1; i++) { - if(i > 0) { root += '/'; } - root += p2[i]; - } - rootTrimmed = true; - } - if(ref.indexOf('#') >= 0) { - if(ref.indexOf('/') === 0) { - rs = ref.split('#'); - p = root.split('//'); - p2 = p[1].split('/'); - root = p[0] + '//' + p2[0] + rs[0]; - location = rs[1]; - } - else { - rs = ref.split('#'); - if(rs[0] !== '') { - p2 = root.split('/'); - p2 = p2.slice(0, p2.length - 1); - if(!rootTrimmed) { - root = ''; - for (var k = 0; k < p2.length; k++) { - if(k > 0) { root += '/'; } - root += p2[k]; - } - } - root += '/' + ref.split('#')[0]; - } - location = rs[1]; - } - } - if (ref.indexOf('http:') === 0 || ref.indexOf('https:') === 0) { - if(ref.indexOf('#') >= 0) { - root = ref.split('#')[0]; - location = ref.split('#')[1]; - } - else { - root = ref; - location = ''; - } - resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location}); - } else if (ref.indexOf('#') === 0) { - location = ref.split('#')[1]; - resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location}); - } else if (ref.indexOf('/') === 0 && ref.indexOf('#') === -1) { - location = ref; - var matches = root.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i); - if(matches) { - root = matches[0] + ref.substring(1); - location = ''; - } - resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location}); - } - else { - resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location}); - } - } - else if (property.type === 'array') { - this.resolveTo(root, property.items, resolutionTable, location); - } -}; - -Resolver.prototype.resolveTo = function (root, property, resolutionTable, location) { - var sp, i; - var ref = property.$ref; - var lroot = root; - if ((typeof ref !== 'undefined') && (ref !== null)) { - if(ref.indexOf('#') >= 0) { - var parts = ref.split('#'); - - // #/definitions/foo - // foo.json#/bar - if(parts[0] && ref.indexOf('/') === 0) { - - } - else if(parts[0] && (parts[0].indexOf('http:') === 0 || parts[0].indexOf('https:') === 0)) { - lroot = parts[0]; - ref = parts[1]; - } - else if(parts[0] && parts[0].length > 0) { - // relative file - sp = root.split('/'); - lroot = ''; - for(i = 0; i < sp.length - 1; i++) { - lroot += sp[i] + '/'; - } - lroot += parts[0]; - } - else { - - } - - location = parts[1]; - } - else if (ref.indexOf('http:') === 0 || ref.indexOf('https:') === 0) { - lroot = ref; - location = ''; - } - else { - // relative file - sp = root.split('/'); - lroot = ''; - for(i = 0; i < sp.length - 1; i++) { - lroot += sp[i] + '/'; - } - lroot += ref; - location = ''; - } - resolutionTable.push({ - obj: property, resolveAs: 'ref', root: lroot, key: ref, location: location - }); - } else if (property.type === 'array') { - var items = property.items; - this.resolveTo(root, items, resolutionTable, location); - } else { - if(property && (property.properties || property.additionalProperties)) { - var name = this.uniqueName('inline_model'); - if (property.title) { - name = this.uniqueName(property.title); - } - delete property.title; - this.spec.definitions[name] = _.cloneDeep(property); - property.$ref = '#/definitions/' + name; - delete property.type; - delete property.properties; - } - } -}; - -Resolver.prototype.uniqueName = function(base) { - var name = base; - var count = 0; - while(true) { - if(!_.isObject(this.spec.definitions[name])) { - return name; - } - name = base + '_' + count; - count++; - } -}; - -Resolver.prototype.resolveAllOf = function(spec, obj, depth) { - depth = depth || 0; - obj = obj || spec; - var name; - for(var key in obj) { - if (!obj.hasOwnProperty(key)) { - continue; - } - var item = obj[key]; - if(item === null) { - throw new TypeError('Swagger 2.0 does not support null types (' + obj + '). See https://github.com/swagger-api/swagger-spec/issues/229.'); - } - if(typeof item === 'object') { - this.resolveAllOf(spec, item, depth + 1); - } - if(item && typeof item.allOf !== 'undefined') { - var allOf = item.allOf; - if(_.isArray(allOf)) { - var output = _.cloneDeep(item); - delete output.allOf; - - output['x-composed'] = true; - if (typeof item['x-resolved-from'] !== 'undefined') { - output['x-resolved-from'] = item['x-resolved-from']; - } - - for(var i = 0; i < allOf.length; i++) { - var component = allOf[i]; - var source = 'self'; - if(typeof component['x-resolved-from'] !== 'undefined') { - source = component['x-resolved-from'][0]; - } - - for(var part in component) { - if(!output.hasOwnProperty(part)) { - output[part] = _.cloneDeep(component[part]); - if(part === 'properties') { - for(name in output[part]) { - output[part][name]['x-resolved-from'] = source; - } - } - } - else { - if(part === 'properties') { - var properties = component[part]; - for(name in properties) { - output.properties[name] = _.cloneDeep(properties[name]); - var resolvedFrom = properties[name]['x-resolved-from']; - if (typeof resolvedFrom === 'undefined' || resolvedFrom === 'self') { - resolvedFrom = source; - } - output.properties[name]['x-resolved-from'] = resolvedFrom; - } - } - else if(part === 'required') { - // merge & dedup the required array - var a = output.required.concat(component[part]); - for(var k = 0; k < a.length; ++k) { - for(var j = k + 1; j < a.length; ++j) { - if(a[k] === a[j]) { a.splice(j--, 1); } - } - } - output.required = a; - } - else if(part === 'x-resolved-from') { - output['x-resolved-from'].push(source); - } - else { - // TODO: need to merge this property - // console.log('what to do with ' + part) - } - } - } - } - obj[key] = output; - } - } - } -}; - -},{"./http":5,"lodash-compat/lang/cloneDeep":138,"lodash-compat/lang/isArray":140,"lodash-compat/lang/isObject":144,"lodash-compat/lang/isString":146}],7:[function(require,module,exports){ -'use strict'; - -var Helpers = require('./helpers'); - -var _ = { - isPlainObject: require('lodash-compat/lang/isPlainObject'), - isUndefined: require('lodash-compat/lang/isUndefined'), - isArray: require('lodash-compat/lang/isArray'), - isObject: require('lodash-compat/lang/isObject'), - isEmpty: require('lodash-compat/lang/isEmpty'), - map: require('lodash-compat/collection/map'), - indexOf: require('lodash-compat/array/indexOf'), - cloneDeep: require('lodash-compat/lang/cloneDeep'), - keys: require('lodash-compat/object/keys'), - forEach: require('lodash-compat/collection/forEach') -}; - -var optionHtml = module.exports.optionHtml = function (label, value) { - return '' + label + ':' + value + ''; -}; - -module.exports.typeFromJsonSchema = function (type, format) { - var str; - - if (type === 'integer' && format === 'int32') { - str = 'integer'; - } else if (type === 'integer' && format === 'int64') { - str = 'long'; - } else if (type === 'integer' && typeof format === 'undefined') { - str = 'long'; - } else if (type === 'string' && format === 'date-time') { - str = 'date-time'; - } else if (type === 'string' && format === 'date') { - str = 'date'; - } else if (type === 'number' && format === 'float') { - str = 'float'; - } else if (type === 'number' && format === 'double') { - str = 'double'; - } else if (type === 'number' && typeof format === 'undefined') { - str = 'double'; - } else if (type === 'boolean') { - str = 'boolean'; - } else if (type === 'string') { - str = 'string'; - } - - return str; -}; - -var getStringSignature = module.exports.getStringSignature = function (obj, baseComponent) { - var str = ''; - - if (typeof obj.$ref !== 'undefined') { - str += Helpers.simpleRef(obj.$ref); - } else if (typeof obj.type === 'undefined') { - str += 'object'; - } else if (obj.type === 'array') { - if (baseComponent) { - str += getStringSignature((obj.items || obj.$ref || {})); - } else { - str += 'Array['; - str += getStringSignature((obj.items || obj.$ref || {})); - str += ']'; - } - } else if (obj.type === 'integer' && obj.format === 'int32') { - str += 'integer'; - } else if (obj.type === 'integer' && obj.format === 'int64') { - str += 'long'; - } else if (obj.type === 'integer' && typeof obj.format === 'undefined') { - str += 'long'; - } else if (obj.type === 'string' && obj.format === 'date-time') { - str += 'date-time'; - } else if (obj.type === 'string' && obj.format === 'date') { - str += 'date'; - } else if (obj.type === 'string' && typeof obj.format === 'undefined') { - str += 'string'; - } else if (obj.type === 'number' && obj.format === 'float') { - str += 'float'; - } else if (obj.type === 'number' && obj.format === 'double') { - str += 'double'; - } else if (obj.type === 'number' && typeof obj.format === 'undefined') { - str += 'double'; - } else if (obj.type === 'boolean') { - str += 'boolean'; - } else if (obj.$ref) { - str += Helpers.simpleRef(obj.$ref); - } else { - str += obj.type; - } - - return str; -}; - -var schemaToJSON = module.exports.schemaToJSON = function (schema, models, modelsToIgnore, modelPropertyMacro) { - // Resolve the schema (Handle nested schemas) - schema = Helpers.resolveSchema(schema); - - if(typeof modelPropertyMacro !== 'function') { - modelPropertyMacro = function(prop){ - return (prop || {}).default; - }; - } - - modelsToIgnore= modelsToIgnore || {}; - - var type = schema.type || 'object'; - var format = schema.format; - var model; - var output; - - if (!_.isUndefined(schema.example)) { - output = schema.example; - } else if (_.isUndefined(schema.items) && _.isArray(schema.enum)) { - output = schema.enum[0]; - } - - if (_.isUndefined(output)) { - if (schema.$ref) { - model = models[Helpers.simpleRef(schema.$ref)]; - - if (!_.isUndefined(model)) { - if (_.isUndefined(modelsToIgnore[model.name])) { - modelsToIgnore[model.name] = model; - output = schemaToJSON(model.definition, models, modelsToIgnore, modelPropertyMacro); - delete modelsToIgnore[model.name]; - } else { - if (model.type === 'array') { - output = []; - } else { - output = {}; - } - } - } - } else if (!_.isUndefined(schema.default)) { - output = schema.default; - } else if (type === 'string') { - if (format === 'date-time') { - output = new Date().toISOString(); - } else if (format === 'date') { - output = new Date().toISOString().split('T')[0]; - } else { - output = 'string'; - } - } else if (type === 'integer') { - output = 0; - } else if (type === 'number') { - output = 0.0; - } else if (type === 'boolean') { - output = true; - } else if (type === 'object') { - output = {}; - - _.forEach(schema.properties, function (property, name) { - var cProperty = _.cloneDeep(property); - - // Allow macro to set the default value - cProperty.default = modelPropertyMacro(property); - - output[name] = schemaToJSON(cProperty, models, modelsToIgnore, modelPropertyMacro); - }); - } else if (type === 'array') { - output = []; - - if (_.isArray(schema.items)) { - _.forEach(schema.items, function (item) { - output.push(schemaToJSON(item, models, modelsToIgnore, modelPropertyMacro)); - }); - } else if (_.isPlainObject(schema.items)) { - output.push(schemaToJSON(schema.items, models, modelsToIgnore, modelPropertyMacro)); - } else if (_.isUndefined(schema.items)) { - output.push({}); - } else { - Helpers.log('Array type\'s \'items\' property is not an array or an object, cannot process'); - } - } - } - - return output; -}; - -module.exports.schemaToHTML =function (name, schema, models, modelPropertyMacro) { - var strongOpen = ''; - var strongClose = ''; - - // Allow for ignoring the 'name' argument.... shifting the rest - if(_.isObject(arguments[0])) { - name = void 0; - schema = arguments[0]; - models = arguments[1]; - modelPropertyMacro = arguments[2]; - } - - models = models || {}; - - // Resolve the schema (Handle nested schemas) - schema = Helpers.resolveSchema(schema); - - // Return for empty object - if(_.isEmpty(schema)) { - return strongOpen + 'Empty' + strongClose; - } - - // Dereference $ref from 'models' - if(typeof schema.$ref === 'string') { - name = Helpers.simpleRef(schema.$ref); - schema = models[name]; - if(typeof schema === 'undefined') - { - return strongOpen + name + ' is not defined!' + strongClose; - } - } - - if(typeof name !== 'string') { - name = schema.title || 'Inline Model'; - } - - // If we are a Model object... adjust accordingly - if(schema.definition) { - schema = schema.definition; - } - - if(typeof modelPropertyMacro !== 'function') { - modelPropertyMacro = function(prop){ - return (prop || {}).default; - }; - } - - var references = {}; - var seenModels = []; - var inlineModels = 0; - - - - // Generate current HTML - var html = processModel(schema, name); - - // Generate references HTML - while (_.keys(references).length > 0) { - /* jshint ignore:start */ - _.forEach(references, function (schema, name) { - var seenModel = _.indexOf(seenModels, name) > -1; - - delete references[name]; - - if (!seenModel) { - seenModels.push(name); - - html += '
    ' + processModel(schema, name); - } - }); - /* jshint ignore:end */ - } - - return html; - - ///////////////////////////////// - - function addReference(schema, name, skipRef) { - var modelName = name; - var model; - - if (schema.$ref) { - modelName = schema.title || Helpers.simpleRef(schema.$ref); - model = models[modelName]; - } else if (_.isUndefined(name)) { - modelName = schema.title || 'Inline Model ' + (++inlineModels); - model = {definition: schema}; - } - - if (skipRef !== true) { - references[modelName] = _.isUndefined(model) ? {} : model.definition; - } - - return modelName; - } - - function primitiveToHTML(schema) { - var html = ''; - var type = schema.type || 'object'; - - if (schema.$ref) { - html += addReference(schema, Helpers.simpleRef(schema.$ref)); - } else if (type === 'object') { - if (!_.isUndefined(schema.properties)) { - html += addReference(schema); - } else { - html += 'object'; - } - } else if (type === 'array') { - html += 'Array['; - - if (_.isArray(schema.items)) { - html += _.map(schema.items, addReference).join(','); - } else if (_.isPlainObject(schema.items)) { - if (_.isUndefined(schema.items.$ref)) { - if (!_.isUndefined(schema.items.type) && _.indexOf(['array', 'object'], schema.items.type) === -1) { - html += schema.items.type; - } else { - html += addReference(schema.items); - } - } else { - html += addReference(schema.items, Helpers.simpleRef(schema.items.$ref)); - } - } else { - Helpers.log('Array type\'s \'items\' schema is not an array or an object, cannot process'); - html += 'object'; - } - - html += ']'; - } else { - html += schema.type; - } - - html += ''; - - return html; - } - - function primitiveToOptionsHTML(schema, html) { - var options = ''; - var type = schema.type || 'object'; - var isArray = type === 'array'; - - if (isArray) { - if (_.isPlainObject(schema.items) && !_.isUndefined(schema.items.type)) { - type = schema.items.type; - } else { - type = 'object'; - } - } - - if (!_.isUndefined(schema.default)) { - options += optionHtml('Default', schema.default); - } - - switch (type) { - case 'string': - if (schema.minLength) { - options += optionHtml('Min. Length', schema.minLength); - } - - if (schema.maxLength) { - options += optionHtml('Max. Length', schema.maxLength); - } - - if (schema.pattern) { - options += optionHtml('Reg. Exp.', schema.pattern); - } - break; - case 'integer': - case 'number': - if (schema.minimum) { - options += optionHtml('Min. Value', schema.minimum); - } - - if (schema.exclusiveMinimum) { - options += optionHtml('Exclusive Min.', 'true'); - } - - if (schema.maximum) { - options += optionHtml('Max. Value', schema.maximum); - } - - if (schema.exclusiveMaximum) { - options += optionHtml('Exclusive Max.', 'true'); - } - - if (schema.multipleOf) { - options += optionHtml('Multiple Of', schema.multipleOf); - } - - break; - } - - if (isArray) { - if (schema.minItems) { - options += optionHtml('Min. Items', schema.minItems); - } - - if (schema.maxItems) { - options += optionHtml('Max. Items', schema.maxItems); - } - - if (schema.uniqueItems) { - options += optionHtml('Unique Items', 'true'); - } - - if (schema.collectionFormat) { - options += optionHtml('Coll. Format', schema.collectionFormat); - } - } - - if (_.isUndefined(schema.items)) { - if (_.isArray(schema.enum)) { - var enumString; - - if (type === 'number' || type === 'integer') { - enumString = schema.enum.join(', '); - } else { - enumString = '"' + schema.enum.join('", "') + '"'; - } - - options += optionHtml('Enum', enumString); - } - } - - if (options.length > 0) { - html = '' + html + '' + options + '
    ' + type + '
    '; - } - - return html; - } - - function processModel(schema, name) { - var type = schema.type || 'object'; - var isArray = schema.type === 'array'; - var html = strongOpen + name + ' ' + (isArray ? '[' : '{') + strongClose; - - if (name) { - seenModels.push(name); - } - - if (isArray) { - if (_.isArray(schema.items)) { - html += '
    ' + _.map(schema.items, function (item) { - var type = item.type || 'object'; - - if (_.isUndefined(item.$ref)) { - if (_.indexOf(['array', 'object'], type) > -1) { - if (type === 'object' && _.isUndefined(item.properties)) { - return 'object'; - } else { - return addReference(item); - } - } else { - return primitiveToOptionsHTML(item, type); - } - } else { - return addReference(item, Helpers.simpleRef(item.$ref)); - } - }).join(',
    '); - } else if (_.isPlainObject(schema.items)) { - if (_.isUndefined(schema.items.$ref)) { - if (_.indexOf(['array', 'object'], schema.items.type || 'object') > -1) { - if ((_.isUndefined(schema.items.type) || schema.items.type === 'object') && _.isUndefined(schema.items.properties)) { - html += '
    object
    '; - } else { - html += '
    ' + addReference(schema.items) + '
    '; - } - } else { - html += '
    ' + primitiveToOptionsHTML(schema.items, schema.items.type) + '
    '; - } - } else { - html += '
    ' + addReference(schema.items, Helpers.simpleRef(schema.items.$ref)) + '
    '; - } - } else { - Helpers.log('Array type\'s \'items\' property is not an array or an object, cannot process'); - html += '
    object
    '; - } - } else { - if (schema.$ref) { - html += '
    ' + addReference(schema, name) + '
    '; - } else if (type === 'object') { - if (_.isPlainObject(schema.properties)) { - var contents = _.map(schema.properties, function (property, name) { - var propertyIsRequired = (_.indexOf(schema.required, name) >= 0); - var cProperty = _.cloneDeep(property); - - var requiredClass = propertyIsRequired ? 'required' : ''; - var html = '' + name + ' ('; - var model; - var propDescription; - - // Allow macro to set the default value - cProperty.default = modelPropertyMacro(cProperty); - - // Resolve the schema (Handle nested schemas) - cProperty = Helpers.resolveSchema(cProperty); - - propDescription = property.description || cProperty.description; - - // We need to handle property references to primitives (Issue 339) - if (!_.isUndefined(cProperty.$ref)) { - model = models[Helpers.simpleRef(cProperty.$ref)]; - - if (!_.isUndefined(model) && _.indexOf([undefined, 'array', 'object'], model.definition.type) === -1) { - // Use referenced schema - cProperty = Helpers.resolveSchema(model.definition); - } - } - - html += primitiveToHTML(cProperty); - - if(!propertyIsRequired) { - html += ', optional'; - } - - if(property.readOnly) { - html += ', read only'; - } - - html += ')'; - - if (!_.isUndefined(propDescription)) { - html += ': ' + '' + propDescription + ''; - } - - if (cProperty.enum) { - html += ' = [\'' + cProperty.enum.join('\', \'') + '\']'; - } - - return '' + primitiveToOptionsHTML(cProperty, html); - }).join(',
    '); - - if (contents) { - html += contents + '
    '; - } - } - } else { - html += '
    ' + primitiveToOptionsHTML(schema, type) + '
    '; - } - } - - return html + strongOpen + (isArray ? ']' : '}') + strongClose; - } -}; -},{"./helpers":4,"lodash-compat/array/indexOf":49,"lodash-compat/collection/forEach":54,"lodash-compat/collection/map":56,"lodash-compat/lang/cloneDeep":138,"lodash-compat/lang/isArray":140,"lodash-compat/lang/isEmpty":141,"lodash-compat/lang/isObject":144,"lodash-compat/lang/isPlainObject":145,"lodash-compat/lang/isUndefined":148,"lodash-compat/object/keys":149}],8:[function(require,module,exports){ -'use strict'; - -var SwaggerHttp = require('./http'); -var _ = { - isObject: require('lodash-compat/lang/isObject') -}; - -var SwaggerSpecConverter = module.exports = function () { - this.errors = []; - this.warnings = []; - this.modelMap = {}; -}; - -SwaggerSpecConverter.prototype.setDocumentationLocation = function (location) { - this.docLocation = location; -}; - -/** - * converts a resource listing OR api declaration - **/ -SwaggerSpecConverter.prototype.convert = function (obj, clientAuthorizations, opts, callback) { - // not a valid spec - if(!obj || !Array.isArray(obj.apis)) { - return this.finish(callback, null); - } - this.clientAuthorizations = clientAuthorizations; - - // create a new swagger object to return - var swagger = { swagger: '2.0' }; - - swagger.originalVersion = obj.swaggerVersion; - - // add the info - this.apiInfo(obj, swagger); - - // add security definitions - this.securityDefinitions(obj, swagger); - - // take basePath into account - if (obj.basePath) { - this.setDocumentationLocation(obj.basePath); - } - - // see if this is a single-file swagger definition - var isSingleFileSwagger = false; - var i; - for(i = 0; i < obj.apis.length; i++) { - var api = obj.apis[i]; - if(Array.isArray(api.operations)) { - isSingleFileSwagger = true; - } - } - if(isSingleFileSwagger) { - this.declaration(obj, swagger); - this.finish(callback, swagger); - } - else { - this.resourceListing(obj, swagger, opts, callback); - } -}; - -SwaggerSpecConverter.prototype.declaration = function(obj, swagger) { - var name, i, p, pos; - if(!obj.apis) { - return; - } - - if (obj.basePath.indexOf('http://') === 0) { - p = obj.basePath.substring('http://'.length); - pos = p.indexOf('/'); - if (pos > 0) { - swagger.host = p.substring(0, pos); - swagger.basePath = p.substring(pos); - } - else { - swagger.host = p; - swagger.basePath = '/'; - } - } else if (obj.basePath.indexOf('https://') === 0) { - p = obj.basePath.substring('https://'.length); - pos = p.indexOf('/'); - if (pos > 0) { - swagger.host = p.substring(0, pos); - swagger.basePath = p.substring(pos); - } - else { - swagger.host = p; - swagger.basePath = '/'; - } - } else { - swagger.basePath = obj.basePath; - } - - var resourceLevelAuth; - if(obj.authorizations) { - resourceLevelAuth = obj.authorizations; - } - if(obj.consumes) { - swagger.consumes = obj.consumes; - } - if(obj.produces) { - swagger.produces = obj.produces; - } - - // build a mapping of id to name for 1.0 model resolutions - if(_.isObject(obj)) { - for(name in obj.models) { - var existingModel = obj.models[name]; - var key = (existingModel.id || name); - this.modelMap[key] = name; - } - } - - for(i = 0; i < obj.apis.length; i++) { - var api = obj.apis[i]; - var path = api.path; - var operations = api.operations; - this.operations(path, obj.resourcePath, operations, resourceLevelAuth, swagger); - } - - var models = obj.models || {}; - this.models(models, swagger); -}; - -SwaggerSpecConverter.prototype.models = function(obj, swagger) { - if(!_.isObject(obj)) { - return; - } - var name; - - swagger.definitions = swagger.definitions || {}; - for(name in obj) { - var existingModel = obj[name]; - var _required = []; - var schema = { properties: {}}; - var propertyName; - for(propertyName in existingModel.properties) { - var existingProperty = existingModel.properties[propertyName]; - var property = {}; - this.dataType(existingProperty, property); - if(existingProperty.description) { - property.description = existingProperty.description; - } - if(existingProperty['enum']) { - property['enum'] = existingProperty['enum']; - } - if(typeof existingProperty.required === 'boolean' && existingProperty.required === true) { - _required.push(propertyName); - } - if(typeof existingProperty.required === 'string' && existingProperty.required === 'true') { - _required.push(propertyName); - } - schema.properties[propertyName] = property; - } - if(_required.length > 0) { - schema.required = _required; - } else { - schema.required = existingModel.required; - } - swagger.definitions[name] = schema; - } -}; - -SwaggerSpecConverter.prototype.extractTag = function(resourcePath) { - var pathString = resourcePath || 'default'; - if(pathString.indexOf('http:') === 0 || pathString.indexOf('https:') === 0) { - pathString = pathString.split(['/']); - pathString = pathString[pathString.length -1].substring(); - } - if(pathString.endsWith('.json')) { - pathString = pathString.substring(0, pathString.length - '.json'.length); - } - return pathString.replace('/',''); -}; - -SwaggerSpecConverter.prototype.operations = function(path, resourcePath, obj, resourceLevelAuth, swagger) { - if(!Array.isArray(obj)) { - return; - } - var i; - - if(!swagger.paths) { - swagger.paths = {}; - } - - var pathObj = swagger.paths[path] || {}; - var tag = this.extractTag(resourcePath); - swagger.tags = swagger.tags || []; - var matched = false; - for(i = 0; i < swagger.tags.length; i++) { - var tagObject = swagger.tags[i]; - if(tagObject.name === tag) { - matched = true; - } - } - if(!matched) { - swagger.tags.push({name: tag}); - } - - for(i = 0; i < obj.length; i++) { - var existingOperation = obj[i]; - var method = (existingOperation.method || existingOperation.httpMethod).toLowerCase(); - var operation = {tags: [tag]}; - var existingAuthorizations = existingOperation.authorizations; - - if(existingAuthorizations && Object.keys(existingAuthorizations).length === 0) { - existingAuthorizations = resourceLevelAuth; - } - - if(typeof existingAuthorizations !== 'undefined') { - var scopesObject; - for(var key in existingAuthorizations) { - operation.security = operation.security || []; - var scopes = existingAuthorizations[key]; - if(scopes) { - var securityScopes = []; - for(var j in scopes) { - securityScopes.push(scopes[j].scope); - } - scopesObject = {}; - scopesObject[key] = securityScopes; - operation.security.push(scopesObject); - } - else { - scopesObject = {}; - scopesObject[key] = []; - operation.security.push(scopesObject); - } - } - } - - if(existingOperation.consumes) { - operation.consumes = existingOperation.consumes; - } - else if(swagger.consumes) { - operation.consumes = swagger.consumes; - } - if(existingOperation.produces) { - operation.produces = existingOperation.produces; - } - else if(swagger.produces) { - operation.produces = swagger.produces; - } - if(existingOperation.summary) { - operation.summary = existingOperation.summary; - } - if(existingOperation.notes) { - operation.description = existingOperation.notes; - } - if(existingOperation.nickname) { - operation.operationId = existingOperation.nickname; - } - if(existingOperation.deprecated) { - operation.deprecated = existingOperation.deprecated; - } - - this.authorizations(existingAuthorizations, swagger); - this.parameters(operation, existingOperation.parameters, swagger); - this.responseMessages(operation, existingOperation, swagger); - - pathObj[method] = operation; - } - - swagger.paths[path] = pathObj; -}; - -SwaggerSpecConverter.prototype.responseMessages = function(operation, existingOperation) { - if(!_.isObject(existingOperation)) { - return; - } - // build default response from the operation (1.x) - var defaultResponse = {}; - this.dataType(existingOperation, defaultResponse); - // TODO: look into the real problem of rendering responses in swagger-ui - // ....should reponseType have an implicit schema? - if(!defaultResponse.schema && defaultResponse.type) { - defaultResponse = {schema: defaultResponse}; - } - - operation.responses = operation.responses || {}; - - // grab from responseMessages (1.2) - var has200 = false; - if(Array.isArray(existingOperation.responseMessages)) { - var i; - var existingResponses = existingOperation.responseMessages; - for(i = 0; i < existingResponses.length; i++) { - var existingResponse = existingResponses[i]; - var response = { description: existingResponse.message }; - if(existingResponse.code === 200) { - has200 = true; - } - // Convert responseModel -> schema{$ref: responseModel} - if(existingResponse.responseModel) { - response.schema = {'$ref': '#/definitions/' + existingResponse.responseModel}; - } - operation.responses['' + existingResponse.code] = response; - } - } - - if(has200) { - operation.responses['default'] = defaultResponse; - } - else { - operation.responses['200'] = defaultResponse; - } -}; - -SwaggerSpecConverter.prototype.authorizations = function(obj) { - // TODO - if(!_.isObject(obj)) { - return; - } -}; - -SwaggerSpecConverter.prototype.parameters = function(operation, obj) { - if(!Array.isArray(obj)) { - return; - } - var i; - for(i = 0; i < obj.length; i++) { - var existingParameter = obj[i]; - var parameter = {}; - parameter.name = existingParameter.name; - parameter.description = existingParameter.description; - parameter.required = existingParameter.required; - parameter.in = existingParameter.paramType; - - // per #168 - if(parameter.in === 'body') { - parameter.name = 'body'; - } - if(parameter.in === 'form') { - parameter.in = 'formData'; - } - - if(existingParameter.enum) { - parameter.enum = existingParameter.enum; - } - - if(existingParameter.allowMultiple === true || existingParameter.allowMultiple === 'true') { - var innerType = {}; - this.dataType(existingParameter, innerType); - parameter.type = 'array'; - parameter.items = innerType; - - if(existingParameter.allowableValues) { - var av = existingParameter.allowableValues; - if(av.valueType === 'LIST') { - parameter['enum'] = av.values; - } - } - } - else { - this.dataType(existingParameter, parameter); - } - if(typeof existingParameter.defaultValue !== 'undefined') { - parameter.default = existingParameter.defaultValue; - } - - operation.parameters = operation.parameters || []; - operation.parameters.push(parameter); - } -}; - -SwaggerSpecConverter.prototype.dataType = function(source, target) { - if(!_.isObject(source)) { - return; - } - - if(source.minimum) { - target.minimum = source.minimum; - } - if(source.maximum) { - target.maximum = source.maximum; - } - if (source.format) { - target.format = source.format; - } - - // default can be 'false' - if(typeof source.defaultValue !== 'undefined') { - target.default = source.defaultValue; - } - - var jsonSchemaType = this.toJsonSchema(source); - if(jsonSchemaType) { - target = target || {}; - if(jsonSchemaType.type) { - target.type = jsonSchemaType.type; - } - if(jsonSchemaType.format) { - target.format = jsonSchemaType.format; - } - if(jsonSchemaType.$ref) { - target.schema = {$ref: jsonSchemaType.$ref}; - } - if(jsonSchemaType.items) { - target.items = jsonSchemaType.items; - } - } -}; - -SwaggerSpecConverter.prototype.toJsonSchema = function(source) { - if(!source) { - return 'object'; - } - var detectedType = (source.type || source.dataType || source.responseClass || ''); - var lcType = detectedType.toLowerCase(); - var format = (source.format || '').toLowerCase(); - - if(lcType.indexOf('list[') === 0) { - var innerType = detectedType.substring(5, detectedType.length - 1); - var jsonType = this.toJsonSchema({type: innerType}); - return {type: 'array', items: jsonType}; - } else if(lcType === 'int' || (lcType === 'integer' && format === 'int32')) { - {return {type: 'integer', format: 'int32'};} - } else if(lcType === 'long' || (lcType === 'integer' && format === 'int64')) { - {return {type: 'integer', format: 'int64'};} - } else if(lcType === 'integer') { - {return {type: 'integer', format: 'int64'};} - } else if(lcType === 'float' || (lcType === 'number' && format === 'float')) { - {return {type: 'number', format: 'float'};} - } else if(lcType === 'double' || (lcType === 'number' && format === 'double')) { - {return {type: 'number', format: 'double'};} - } else if((lcType === 'string' && format === 'date-time') || (lcType === 'date')) { - {return {type: 'string', format: 'date-time'};} - } else if(lcType === 'string') { - {return {type: 'string'};} - } else if(lcType === 'file') { - {return {type: 'file'};} - } else if(lcType === 'boolean') { - {return {type: 'boolean'};} - } else if(lcType === 'boolean') { - {return {type: 'boolean'};} - } else if(lcType === 'array' || lcType === 'list') { - if(source.items) { - var it = this.toJsonSchema(source.items); - return {type: 'array', items: it}; - } - else { - return {type: 'array', items: {type: 'object'}}; - } - } else if(source.$ref) { - return {$ref: this.modelMap[source.$ref] ? '#/definitions/' + this.modelMap[source.$ref] : source.$ref}; - } else if(lcType === 'void' || lcType === '') { - {return {};} - } else if (this.modelMap[source.type]) { - // If this a model using `type` instead of `$ref`, that's fine. - return {$ref: '#/definitions/' + this.modelMap[source.type]}; - } else { - // Unknown model type or 'object', pass it along. - return {type: source.type}; - } -}; - -SwaggerSpecConverter.prototype.resourceListing = function(obj, swagger, opts, callback) { - var i; - var processedCount = 0; // jshint ignore:line - var self = this; // jshint ignore:line - var expectedCount = obj.apis.length; - var _swagger = swagger; // jshint ignore:line - var _opts = {}; - - if(opts && opts.requestInterceptor){ - _opts.requestInterceptor = opts.requestInterceptor; - } - - if(opts && opts.responseInterceptor){ - _opts.responseInterceptor = opts.responseInterceptor; - } - - var swaggerRequestHeaders = 'application/json'; - - if(opts && opts.swaggerRequestHeaders) { - swaggerRequestHeaders = opts.swaggerRequestHeaders; - } - - if(expectedCount === 0) { - this.finish(callback, swagger); - } - - for(i = 0; i < expectedCount; i++) { - var api = obj.apis[i]; - var path = api.path; - var absolutePath = this.getAbsolutePath(obj.swaggerVersion, this.docLocation, path); - - if(api.description) { - swagger.tags = swagger.tags || []; - swagger.tags.push({ - name : this.extractTag(api.path), - description : api.description || '' - }); - } - var http = { - url: absolutePath, - headers: { accept: swaggerRequestHeaders }, - on: {}, - method: 'get', - timeout: opts.timeout - }; - /* jshint ignore:start */ - http.on.response = function(data) { - processedCount += 1; - var obj = data.obj; - if(obj) { - self.declaration(obj, _swagger); - } - if(processedCount === expectedCount) { - self.finish(callback, _swagger); - } - }; - http.on.error = function(data) { - console.error(data); - processedCount += 1; - if(processedCount === expectedCount) { - self.finish(callback, _swagger); - } - }; - /* jshint ignore:end */ - - if(this.clientAuthorizations && typeof this.clientAuthorizations.apply === 'function') { - this.clientAuthorizations.apply(http); - } - - new SwaggerHttp().execute(http, _opts); - } -}; - -SwaggerSpecConverter.prototype.getAbsolutePath = function(version, docLocation, path) { - if(version === '1.0') { - if(docLocation.endsWith('.json')) { - // get root path - var pos = docLocation.lastIndexOf('/'); - if(pos > 0) { - docLocation = docLocation.substring(0, pos); - } - } - } - - var location = docLocation; - if(path.indexOf('http:') === 0 || path.indexOf('https:') === 0) { - location = path; - } - else { - if(docLocation.endsWith('/')) { - location = docLocation.substring(0, docLocation.length - 1); - } - location += path; - } - location = location.replace('{format}', 'json'); - return location; -}; - -SwaggerSpecConverter.prototype.securityDefinitions = function(obj, swagger) { - if(obj.authorizations) { - var name; - for(name in obj.authorizations) { - var isValid = false; - var securityDefinition = { - vendorExtensions: {} - }; - var definition = obj.authorizations[name]; - if(definition.type === 'apiKey') { - securityDefinition.type = 'apiKey'; - securityDefinition.in = definition.passAs; - securityDefinition.name = definition.keyname || name; - isValid = true; - } - else if(definition.type === 'basicAuth') { - securityDefinition.type = 'basicAuth'; - isValid = true; - } - else if(definition.type === 'oauth2') { - var existingScopes = definition.scopes || []; - var scopes = {}; - var i; - for(i in existingScopes) { - var scope = existingScopes[i]; - scopes[scope.scope] = scope.description; - } - securityDefinition.type = 'oauth2'; - if(i > 0) { - securityDefinition.scopes = scopes; - } - if(definition.grantTypes) { - if(definition.grantTypes.implicit) { - var implicit = definition.grantTypes.implicit; - securityDefinition.flow = 'implicit'; - securityDefinition.authorizationUrl = implicit.loginEndpoint; - isValid = true; - } - /* jshint ignore:start */ - if(definition.grantTypes['authorization_code']) { - if(!securityDefinition.flow) { - // cannot set if flow is already defined - var authCode = definition.grantTypes['authorization_code']; - securityDefinition.flow = 'accessCode'; - securityDefinition.authorizationUrl = authCode.tokenRequestEndpoint.url; - securityDefinition.tokenUrl = authCode.tokenEndpoint.url; - isValid = true; - } - } - /* jshint ignore:end */ - } - } - if(isValid) { - swagger.securityDefinitions = swagger.securityDefinitions || {}; - swagger.securityDefinitions[name] = securityDefinition; - } - } - } -}; - -SwaggerSpecConverter.prototype.apiInfo = function(obj, swagger) { - // info section - if(obj.info) { - var info = obj.info; - swagger.info = {}; - - if(info.contact) { - swagger.info.contact = {}; - swagger.info.contact.email = info.contact; - } - if(info.description) { - swagger.info.description = info.description; - } - if(info.title) { - swagger.info.title = info.title; - } - if(info.termsOfServiceUrl) { - swagger.info.termsOfService = info.termsOfServiceUrl; - } - if(info.license || info.licenseUrl) { - swagger.license = {}; - if(info.license) { - swagger.license.name = info.license; - } - if(info.licenseUrl) { - swagger.license.url = info.licenseUrl; - } - } - } - else { - this.warnings.push('missing info section'); - } -}; - -SwaggerSpecConverter.prototype.finish = function (callback, obj) { - callback(obj); -}; - -},{"./http":5,"lodash-compat/lang/isObject":144}],9:[function(require,module,exports){ -'use strict'; - -var log = require('../helpers').log; -var _ = { - isPlainObject: require('lodash-compat/lang/isPlainObject'), - isString: require('lodash-compat/lang/isString'), -}; - -var SchemaMarkup = require('../schema-markup.js'); -var jsyaml = require('js-yaml'); - -var Model = module.exports = function (name, definition, models, modelPropertyMacro) { - this.definition = definition || {}; - this.isArray = definition.type === 'array'; - this.models = models || {}; - this.name = name || definition.title || 'Inline Model'; - this.modelPropertyMacro = modelPropertyMacro || function (property) { - return property.default; - }; - - return this; -}; - -// Note! This function will be removed in 2.2.x! -Model.prototype.createJSONSample = Model.prototype.getSampleValue = function (modelsToIgnore) { - modelsToIgnore = modelsToIgnore || {}; - - modelsToIgnore[this.name] = this; - - // Response support - if (this.examples && _.isPlainObject(this.examples) && this.examples['application/json']) { - this.definition.example = this.examples['application/json']; - - if (_.isString(this.definition.example)) { - this.definition.example = jsyaml.safeLoad(this.definition.example); - } - } else if (!this.definition.example) { - this.definition.example = this.examples; - } - - return SchemaMarkup.schemaToJSON(this.definition, this.models, modelsToIgnore, this.modelPropertyMacro); -}; - -Model.prototype.getMockSignature = function () { - return SchemaMarkup.schemaToHTML(this.name, this.definition, this.models, this.modelPropertyMacro); -}; - -},{"../helpers":4,"../schema-markup.js":7,"js-yaml":19,"lodash-compat/lang/isPlainObject":145,"lodash-compat/lang/isString":146}],10:[function(require,module,exports){ -'use strict'; - -var _ = { - cloneDeep: require('lodash-compat/lang/cloneDeep'), - isUndefined: require('lodash-compat/lang/isUndefined'), - isEmpty: require('lodash-compat/lang/isEmpty'), - isObject: require('lodash-compat/lang/isObject') -}; -var helpers = require('../helpers'); -var Model = require('./model'); -var SwaggerHttp = require('../http'); -var Q = require('q'); - -var Operation = module.exports = function (parent, scheme, operationId, httpMethod, path, args, definitions, models, clientAuthorizations) { - var errors = []; - - parent = parent || {}; - args = args || {}; - - if(parent && parent.options) { - this.client = parent.options.client || null; - this.requestInterceptor = parent.options.requestInterceptor || null; - this.responseInterceptor = parent.options.responseInterceptor || null; - this.requestAgent = parent.options.requestAgent; - } - this.authorizations = args.security; - this.basePath = parent.basePath || '/'; - this.clientAuthorizations = clientAuthorizations; - this.consumes = args.consumes || parent.consumes || ['application/json']; - this.produces = args.produces || parent.produces || ['application/json']; - this.deprecated = args.deprecated; - this.description = args.description; - this.host = parent.host; - this.method = (httpMethod || errors.push('Operation ' + operationId + ' is missing method.')); - this.models = models || {}; - this.nickname = (operationId || errors.push('Operations must have a nickname.')); - this.operation = args; - this.operations = {}; - this.parameters = args !== null ? (args.parameters || []) : {}; - this.parent = parent; - this.path = (path || errors.push('Operation ' + this.nickname + ' is missing path.')); - this.responses = (args.responses || {}); - this.scheme = scheme || parent.scheme || 'http'; - this.schemes = args.schemes || parent.schemes; - this.security = args.security || parent.security; - this.summary = args.summary || ''; - this.timeout = parent.timeout; - this.type = null; - this.useJQuery = parent.useJQuery; - this.jqueryAjaxCache = parent.jqueryAjaxCache; - this.enableCookies = parent.enableCookies; - - var key; - - if(!this.host) { - if(typeof window !== 'undefined') { - this.host = window.location.host; - } - else { - this.host = 'localhost'; - } - } - this.parameterMacro = parent.parameterMacro || function (operation, parameter) { - return parameter.default; - }; - - this.inlineModels = []; - - if(this.basePath !== '/' && this.basePath.slice(-1) === '/') { - this.basePath = this.basePath.slice(0, -1); - } - - if (typeof this.deprecated === 'string') { - switch(this.deprecated.toLowerCase()) { - case 'true': case 'yes': case '1': { - this.deprecated = true; - break; - } - - case 'false': case 'no': case '0': case null: { - this.deprecated = false; - break; - } - - default: this.deprecated = Boolean(this.deprecated); - } - } - - var i, model; - - if (definitions) { - // add to global models - for (key in definitions) { - model = new Model(key, definitions[key], this.models, parent.modelPropertyMacro); - - if (model) { - this.models[key] = model; - } - } - } - else { - definitions = {}; - } - - for (i = 0; i < this.parameters.length; i++) { - var d, param = this.parameters[i]; - - // Allow macro to set the default value - param.default = this.parameterMacro(this, param); - - if (param.type === 'array') { - param.isList = true; - param.allowMultiple = true; - } - - var innerType = this.getType(param); - - if (innerType && innerType.toString().toLowerCase() === 'boolean') { - param.allowableValues = {}; - param.isList = true; - param['enum'] = [true, false]; // use actual primitives - } - - for(key in param) { - helpers.extractExtensions(key, param); - } - if(typeof param['x-example'] !== 'undefined') { - d = param['x-example']; - param.default = d; - } - if(param['x-examples']) { - d = param['x-examples'].default; - if(typeof d !== 'undefined') { - param.default = d; - } - } - - var enumValues = param['enum'] || (param.items && param.items['enum']); - - if (typeof enumValues !== 'undefined') { - var id; - - param.allowableValues = {}; - param.allowableValues.values = []; - param.allowableValues.descriptiveValues = []; - - for (id = 0; id < enumValues.length; id++) { - var value = enumValues[id]; - var isDefault = (value === param.default || value+'' === param.default); - - param.allowableValues.values.push(value); - // Always have string for descriptive values.... - param.allowableValues.descriptiveValues.push({value : value+'', isDefault: isDefault}); - } - } - - if (param.type === 'array') { - innerType = [innerType]; - - if (typeof param.allowableValues === 'undefined') { - // can't show as a list if no values to select from - delete param.isList; - delete param.allowMultiple; - } - } - - param.modelSignature = {type: innerType, definitions: this.models}; - param.signature = this.getModelSignature(innerType, this.models).toString(); - param.sampleJSON = this.getModelSampleJSON(innerType, this.models); - param.responseClassSignature = param.signature; - } - - var keyname, defaultResponseCode, response, responses = this.responses; - - if (responses['200']) { - response = responses['200']; - defaultResponseCode = '200'; - } else if (responses['201']) { - response = responses['201']; - defaultResponseCode = '201'; - } else if (responses['202']) { - response = responses['202']; - defaultResponseCode = '202'; - } else if (responses['203']) { - response = responses['203']; - defaultResponseCode = '203'; - } else if (responses['204']) { - response = responses['204']; - defaultResponseCode = '204'; - } else if (responses['205']) { - response = responses['205']; - defaultResponseCode = '205'; - } else if (responses['206']) { - response = responses['206']; - defaultResponseCode = '206'; - } else if (responses['default']) { - response = responses['default']; - defaultResponseCode = 'default'; - } - - for(keyname in responses) { - helpers.extractExtensions(keyname, responses); - if(typeof keyname === 'string' && keyname.indexOf('x-') === -1) { - var responseObject = responses[keyname]; - if(typeof responseObject === 'object' && typeof responseObject.headers === 'object') { - var headers = responseObject.headers; - for(var headerName in headers) { - var header = headers[headerName]; - if(typeof header === 'object') { - for(var headerKey in header) { - helpers.extractExtensions(headerKey, header); - } - } - } - } - } - } - - if (response) { - for(keyname in response) { - helpers.extractExtensions(keyname, response); - } - } - - if (response && response.schema) { - var resolvedModel = this.resolveModel(response.schema, definitions); - var successResponse; - - delete responses[defaultResponseCode]; - - if (resolvedModel) { - this.successResponse = {}; - successResponse = this.successResponse[defaultResponseCode] = resolvedModel; - } else if (!response.schema.type || response.schema.type === 'object' || response.schema.type === 'array') { - // Inline model - this.successResponse = {}; - successResponse = this.successResponse[defaultResponseCode] = new Model(undefined, response.schema || {}, this.models, parent.modelPropertyMacro); - } else { - // Primitive - this.successResponse = {}; - successResponse = this.successResponse[defaultResponseCode] = response.schema; - } - - if (successResponse) { - successResponse.vendorExtensions = response.vendorExtensions; - // Attach response properties - if (response.description) { - successResponse.description = response.description; - } - - if (response.examples) { - successResponse.examples = response.examples; - } - - if (response.headers) { - successResponse.headers = response.headers; - } - } - - this.type = response; - } - - if (errors.length > 0) { - if (this.resource && this.resource.api && this.resource.api.fail) { - this.resource.api.fail(errors); - } - } - - return this; -}; - -Operation.prototype.isDefaultArrayItemValue = function(value, param) { - if (param.default && Array.isArray(param.default)) { - return param.default.indexOf(value) !== -1; - } - return value === param.default; -}; - -Operation.prototype.getType = function (param) { - var type = param.type; - var format = param.format; - var isArray = false; - var str; - - if (type === 'integer' && format === 'int32') { - str = 'integer'; - } else if (type === 'integer' && format === 'int64') { - str = 'long'; - } else if (type === 'integer') { - str = 'integer'; - } else if (type === 'string') { - if (format === 'date-time') { - str = 'date-time'; - } else if (format === 'date') { - str = 'date'; - } else { - str = 'string'; - } - } else if (type === 'number' && format === 'float') { - str = 'float'; - } else if (type === 'number' && format === 'double') { - str = 'double'; - } else if (type === 'number') { - str = 'double'; - } else if (type === 'boolean') { - str = 'boolean'; - } else if (type === 'array') { - isArray = true; - - if (param.items) { - str = this.getType(param.items); - } - } else if (type === 'file') { - str = 'file'; - } - - if (param.$ref) { - str = helpers.simpleRef(param.$ref); - } - - var schema = param.schema; - - if (schema) { - var ref = schema.$ref; - - if (ref) { - ref = helpers.simpleRef(ref); - - if (isArray) { - return [ ref ]; - } else { - return ref; - } - } else { - // If inline schema, we add it our interal hash -> which gives us it's ID (int) - if(schema.type === 'object') { - return this.addInlineModel(schema); - } - return this.getType(schema); - } - } - if (isArray) { - return [ str ]; - } else { - return str; - } -}; - -/** - * adds an inline schema (model) to a hash, where we can ref it later - * @param {object} schema a schema - * @return {number} the ID of the schema being added, or null - **/ -Operation.prototype.addInlineModel = function (schema) { - var len = this.inlineModels.length; - var model = this.resolveModel(schema, {}); - if(model) { - this.inlineModels.push(model); - return 'Inline Model '+len; // return string ref of the inline model (used with #getInlineModel) - } - return null; // report errors? -}; - -/** - * gets the internal ref to an inline model - * @param {string} inline_str a string reference to an inline model - * @return {Model} the model being referenced. Or null - **/ -Operation.prototype.getInlineModel = function(inlineStr) { - if(/^Inline Model \d+$/.test(inlineStr)) { - var id = parseInt(inlineStr.substr('Inline Model'.length).trim(),10); // - var model = this.inlineModels[id]; - return model; - } - // I'm returning null here, should I rather throw an error? - return null; -}; - -Operation.prototype.resolveModel = function (schema, definitions) { - if (typeof schema.$ref !== 'undefined') { - var ref = schema.$ref; - - if (ref.indexOf('#/definitions/') === 0) { - ref = ref.substring('#/definitions/'.length); - } - - if (definitions[ref]) { - return new Model(ref, definitions[ref], this.models, this.parent.modelPropertyMacro); - } - // schema must at least be an object to get resolved to an inline Model - } else if (schema && typeof schema === 'object' && - (schema.type === 'object' || _.isUndefined(schema.type))) { - return new Model(undefined, schema, this.models, this.parent.modelPropertyMacro); - } - - return null; -}; - -Operation.prototype.help = function (dontPrint) { - var out = this.nickname + ': ' + this.summary + '\n'; - - for (var i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - var typeInfo = param.signature; - - out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description; - } - - if (typeof dontPrint === 'undefined') { - helpers.log(out); - } - - return out; -}; - -Operation.prototype.getModelSignature = function (type, definitions) { - var isPrimitive, listType; - - if (type instanceof Array) { - listType = true; - type = type[0]; - } - - // Convert undefined to string of 'undefined' - if (typeof type === 'undefined') { - type = 'undefined'; - isPrimitive = true; - - } else if (definitions[type]){ - // a model def exists? - type = definitions[type]; /* Model */ - isPrimitive = false; - - } else if (this.getInlineModel(type)) { - type = this.getInlineModel(type); /* Model */ - isPrimitive = false; - - } else { - // We default to primitive - isPrimitive = true; - } - - if (isPrimitive) { - if (listType) { - return 'Array[' + type + ']'; - } else { - return type.toString(); - } - } else { - if (listType) { - return 'Array[' + type.getMockSignature() + ']'; - } else { - return type.getMockSignature(); - } - } -}; - -Operation.prototype.supportHeaderParams = function () { - return true; -}; - -Operation.prototype.supportedSubmitMethods = function () { - return this.parent.supportedSubmitMethods; -}; - -Operation.prototype.getHeaderParams = function (args) { - var headers = this.setContentTypes(args, {}); - var headerParamsByLowerCase = {}; - - for (var i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - - if (param.in === 'header') { - headerParamsByLowerCase[param.name.toLowerCase()] = param; - } - } - - for (var arg in args) { - var headerParam = headerParamsByLowerCase[arg.toLowerCase()]; - if (typeof headerParam !== 'undefined') { - var value = args[arg]; - - if (Array.isArray(value)) { - value = value.toString(); - } - - headers[headerParam.name] = value; - } - } - - return headers; -}; - -Operation.prototype.urlify = function (args, maskPasswords) { - var formParams = {}; - var requestUrl = this.path.replace(/#.*/, ''); // remove URL fragment - var querystring = ''; // grab params from the args, build the querystring along the way - - for (var i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - - if (typeof args[param.name] !== 'undefined') { - var isPassword; - if(param.type === 'string' && param.format === 'password' && maskPasswords) { - isPassword = true; - } - - if (param.in === 'path') { - var reg = new RegExp('\{' + param.name + '\}', 'gi'); - var value = args[param.name]; - - if (Array.isArray(value)) { - value = this.encodePathCollection(param.collectionFormat, param.name, value, isPassword); - } else { - value = this.encodePathParam(value, isPassword); - } - - requestUrl = requestUrl.replace(reg, value); - } else if (param.in === 'query' && typeof args[param.name] !== 'undefined') { - if (querystring === '' && requestUrl.indexOf('?') < 0) { - querystring += '?'; - } else { - querystring += '&'; - } - - if (typeof param.collectionFormat !== 'undefined') { - var qp = args[param.name]; - - if (Array.isArray(qp)) { - querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp, isPassword); - } else { - querystring += this.encodeQueryKey(param.name) + '=' + this.encodeQueryParam(args[param.name], isPassword); - } - } else { - querystring += this.encodeQueryKey(param.name) + '=' + this.encodeQueryParam(args[param.name], isPassword); - } - } else if (param.in === 'formData') { - formParams[param.name] = args[param.name]; - } - } - } - var url = this.scheme + '://' + this.host; - - if (this.basePath !== '/') { - url += this.basePath; - } - return url + requestUrl + querystring; -}; - -Operation.prototype.getMissingParams = function (args) { - var missingParams = []; // check required params, track the ones that are missing - var i; - - for (i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - - if (param.required === true) { - if (typeof args[param.name] === 'undefined') { - missingParams = param.name; - } - } - } - - return missingParams; -}; - -Operation.prototype.getBody = function (headers, args, opts) { - var formParams = {}, hasFormParams, param, body, key, value, hasBody = false; - - // look at each param and put form params in an object - for (var i = 0; i < this.parameters.length; i++) { - param = this.parameters[i]; - if (typeof args[param.name] !== 'undefined') { - var isPassword; - if(param.type === 'string' && param.format === 'password') { - isPassword = 'password'; - } - if (param.in === 'body') { - body = args[param.name]; - } else if (param.in === 'formData') { - formParams[param.name] = { - param: param, - value: args[param.name], - password: isPassword - }; - hasFormParams = true; - } - } - else { - if(param.in === 'body') { - hasBody = true; - } - } - } - - // if body is null and hasBody is true, AND a JSON body is requested, send empty {} - if(hasBody && typeof body === 'undefined') { - var contentType = headers['Content-Type']; - if(contentType && contentType.indexOf('application/json') === 0) { - body = '{}'; - } - } - - var isMultiPart = false; - if(headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) { - isMultiPart = true; - } - - // handle form params - if (hasFormParams && !isMultiPart) { - var encoded = ''; - - for (key in formParams) { - param = formParams[key].param; - value = formParams[key].value; - var password; - - if(opts && opts.maskPasswords) { - password = formParams[key].password; - } - - if (typeof value !== 'undefined') { - if (Array.isArray(value)) { - if (encoded !== '') { - encoded += '&'; - } - encoded += this.encodeQueryCollection(param.collectionFormat, key, value, password); - } - else { - if (encoded !== '') { - encoded += '&'; - } - - encoded += encodeURIComponent(key) + '=' + mask(encodeURIComponent(value), password); - } - } - } - - body = encoded; - } else if (isMultiPart) { - var bodyParam; - if (typeof FormData === 'function') { - bodyParam = new FormData(); - - bodyParam.type = 'formData'; - - for (key in formParams) { - param = formParams[key].param; - value = args[key]; - - if (typeof value !== 'undefined') { - if({}.toString.apply(value) === '[object File]') { - bodyParam.append(key, value); - } - else if (value.type === 'file' && value.value) { - bodyParam.append(key, value.value); - } else { - if (Array.isArray(value)) { - if(param.collectionFormat === 'multi') { - bodyParam.delete(key); - for(var v in value) { - bodyParam.append(key, value[v]); - } - } - else { - bodyParam.append(key, this.encodeQueryCollection(param.collectionFormat, key, value).split('=').slice(1).join('=')); - } - } - else { - bodyParam.append(key, value); - } - } - } - } - body = bodyParam; - } - else { - bodyParam = {}; - for (key in formParams) { - value = args[key]; - if (Array.isArray(value)) { - var delimeter; - var format = param.collectionFormat || 'multi'; - if(format === 'ssv') { - delimeter = ' '; - } - else if(format === 'pipes') { - delimeter = '|'; - } - else if(format === 'tsv') { - delimeter = '\t'; - } - else if(format === 'multi') { - bodyParam[key] = value; - break; - } - else { - delimeter = ','; - } - var data; - value.forEach(function(v) { - if(data) { - data += delimeter; - } - else { - data = ''; - } - data += v; - }); - bodyParam[key] = data; - } - else { - bodyParam[key] = value; - } - } - body = bodyParam; - } - headers['Content-Type'] = 'multipart/form-data'; - } - - return body; -}; - -/** - * gets sample response for a single operation - **/ -Operation.prototype.getModelSampleJSON = function (type, models) { - var listType, sampleJson, innerType; - models = models || {}; - - listType = (type instanceof Array); - innerType = listType ? type[0] : type; - - if(models[innerType]) { - sampleJson = models[innerType].createJSONSample(); - } else if (this.getInlineModel(innerType)){ - sampleJson = this.getInlineModel(innerType).createJSONSample(); // may return null, if type isn't correct - } - - - if (sampleJson) { - sampleJson = listType ? [sampleJson] : sampleJson; - - if (typeof sampleJson === 'string') { - return sampleJson; - } else if (_.isObject(sampleJson)) { - var t = sampleJson; - - if (sampleJson instanceof Array && sampleJson.length > 0) { - t = sampleJson[0]; - } - - if (t.nodeName && typeof t === 'Node') { - var xmlString = new XMLSerializer().serializeToString(t); - - return this.formatXml(xmlString); - } else { - return JSON.stringify(sampleJson, null, 2); - } - } else { - return sampleJson; - } - } -}; - -/** - * legacy binding - **/ -Operation.prototype.do = function (args, opts, callback, error, parent) { - return this.execute(args, opts, callback, error, parent); -}; - -/** - * executes an operation - **/ -Operation.prototype.execute = function (arg1, arg2, arg3, arg4, parent) { - var args = arg1 || {}; - var opts = {}, success, error, deferred, timeout; - - if (_.isObject(arg2)) { - opts = arg2; - success = arg3; - error = arg4; - } - - timeout = typeof opts.timeout !== 'undefined' ? opts.timeout : this.timeout; - - if(this.client) { - opts.client = this.client; - } - - if(this.requestAgent) { - opts.requestAgent = this.requestAgent; - } - - // add the request interceptor from parent, if none sent from client - if(!opts.requestInterceptor && this.requestInterceptor ) { - opts.requestInterceptor = this.requestInterceptor ; - } - - if(!opts.responseInterceptor && this.responseInterceptor) { - opts.responseInterceptor = this.responseInterceptor; - } - - if (typeof arg2 === 'function') { - success = arg2; - error = arg3; - } - - if (this.parent.usePromise) { - deferred = Q.defer(); - } else { - success = (success || this.parent.defaultSuccessCallback || helpers.log); - error = (error || this.parent.defaultErrorCallback || helpers.log); - } - - if (typeof opts.useJQuery === 'undefined') { - opts.useJQuery = this.useJQuery; - } - - if (typeof opts.jqueryAjaxCache === 'undefined') { - opts.jqueryAjaxCache = this.jqueryAjaxCache; - } - - if (typeof opts.enableCookies === 'undefined') { - opts.enableCookies = this.enableCookies; - } - - var missingParams = this.getMissingParams(args); - - if (missingParams.length > 0) { - var message = 'missing required params: ' + missingParams; - - helpers.fail(message); - - if (this.parent.usePromise) { - deferred.reject(message); - return deferred.promise; - } else { - error(message, parent); - return {}; - } - } - - var allHeaders = this.getHeaderParams(args); - var contentTypeHeaders = this.setContentTypes(args, opts); - var headers = {}, attrname; - - for (attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; } - for (attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; } - - var body = this.getBody(contentTypeHeaders, args, opts); - var url = this.urlify(args, opts.maskPasswords); - - if(url.indexOf('.{format}') > 0) { - if(headers) { - var format = headers.Accept || headers.accept; - if(format && format.indexOf('json') > 0) { - url = url.replace('.{format}', '.json'); - } - else if(format && format.indexOf('xml') > 0) { - url = url.replace('.{format}', '.xml'); - } - } - } - - var obj = { - url: url, - method: this.method.toUpperCase(), - body: body, - enableCookies: opts.enableCookies, - useJQuery: opts.useJQuery, - jqueryAjaxCache: opts.jqueryAjaxCache, - deferred: deferred, - headers: headers, - clientAuthorizations: opts.clientAuthorizations, - operation: this, - connectionAgent: this.connectionAgent, - on: { - response: function (response) { - if (deferred) { - deferred.resolve(response); - return deferred.promise; - } else { - return success(response, parent); - } - }, - error: function (response) { - if (deferred) { - deferred.reject(response); - return deferred.promise; - } else { - return error(response, parent); - } - } - } - }; - - if (timeout) { - obj.timeout = timeout; - } - - this.clientAuthorizations.apply(obj, this.operation.security); - if (opts.mock === true) { - return obj; - } else { - return new SwaggerHttp().execute(obj, opts); - } -}; - -function itemByPriority(col, itemPriority) { - - // No priorities? return first... - if(_.isEmpty(itemPriority)) { - return col[0]; - } - - for (var i = 0, len = itemPriority.length; i < len; i++) { - if(col.indexOf(itemPriority[i]) > -1) { - return itemPriority[i]; - } - } - - // Otherwise return first - return col[0]; -} - -Operation.prototype.setContentTypes = function (args, opts) { - // default type - var allDefinedParams = this.parameters; - var body; - var consumes = args.parameterContentType || itemByPriority(this.consumes, ['application/json', 'application/yaml']); - var accepts = opts.responseContentType || itemByPriority(this.produces, ['application/json', 'application/yaml']); - var definedFileParams = []; - var definedFormParams = []; - var headers = {}; - var i; - - // get params from the operation and set them in definedFileParams, definedFormParams, headers - for (i = 0; i < allDefinedParams.length; i++) { - var param = allDefinedParams[i]; - - if (param.in === 'formData') { - if (param.type === 'file') { - definedFileParams.push(param); - } else { - definedFormParams.push(param); - } - } else if (param.in === 'header' && opts) { - var key = param.name; - var headerValue = opts[param.name]; - - if (typeof opts[param.name] !== 'undefined') { - headers[key] = headerValue; - } - } else if (param.in === 'body' && typeof args[param.name] !== 'undefined') { - body = args[param.name]; - } - } - - // if there's a body, need to set the consumes header via requestContentType - var hasBody = body || definedFileParams.length || definedFormParams.length; - if (this.method === 'post' || this.method === 'put' || this.method === 'patch' || - ((this.method === 'delete' || this.method === 'get') && hasBody)) { - if (opts.requestContentType) { - consumes = opts.requestContentType; - } - // if any form params, content type must be set - if (definedFormParams.length > 0) { - consumes = undefined; - if (opts.requestContentType) { // override if set - consumes = opts.requestContentType; - } else if (definedFileParams.length > 0) { // if a file, must be multipart/form-data - consumes = 'multipart/form-data'; - } else { - if (this.consumes && this.consumes.length > 0) { - // use the consumes setting - for(var c in this.consumes) { - var chk = this.consumes[c]; - if(chk.indexOf('application/x-www-form-urlencoded') === 0 || chk.indexOf('multipart/form-data') === 0) { - consumes = chk; - } - } - } - } - if(typeof consumes === 'undefined') { - // default to x-www-from-urlencoded - consumes = 'application/x-www-form-urlencoded'; - } - } - } - else { - consumes = null; - } - - if (consumes && this.consumes) { - if (this.consumes.indexOf(consumes) === -1) { - helpers.log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes)); - } - } - - if (!this.matchesAccept(accepts)) { - helpers.log('server can\'t produce ' + accepts); - } - - if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded')) { - headers['Content-Type'] = consumes; - } - else if(this.consumes && this.consumes.length > 0 && this.consumes[0] === 'application/x-www-form-urlencoded') { - headers['Content-Type'] = this.consumes[0]; - } - - if (accepts) { - headers.Accept = accepts; - } - - return headers; -}; - -/** - * Returns true if the request accepts header matches anything in this.produces. - * If this.produces contains * / *, ignore the accept header. - * @param {string=} accepts The client request accept header. - * @return {boolean} - */ -Operation.prototype.matchesAccept = function(accepts) { - // no accepts or produces, no problem! - if (!accepts || !this.produces) { - return true; - } - return this.produces.indexOf(accepts) !== -1 || this.produces.indexOf('*/*') !== -1; -}; - -Operation.prototype.asCurl = function (args1, args2) { - var opts = {mock: true, maskPasswords: true}; - if (typeof args2 === 'object') { - for (var argKey in args2) { - opts[argKey] = args2[argKey]; - } - } - var obj = this.execute(args1, opts); - - this.clientAuthorizations.apply(obj, this.operation.security); - - var results = []; - - results.push('-X ' + this.method.toUpperCase()); - - if (typeof obj.headers !== 'undefined') { - var key; - - for (key in obj.headers) { - var value = obj.headers[key]; - if(typeof value === 'string'){ - value = value.replace(/\'/g, '\\u0027'); - } - results.push('--header \'' + key + ': ' + value + '\''); - } - } - var isFormData = false; - var isMultipart = false; - - var type = obj.headers['Content-Type']; - if(type && type.indexOf('application/x-www-form-urlencoded') === 0) { - isFormData = true; - } - else if (type && type.indexOf('multipart/form-data') === 0) { - isFormData = true; - isMultipart = true; - } - - if (obj.body) { - var body; - if (_.isObject(obj.body)) { - if(isMultipart) { - isMultipart = true; - // add the form data - for(var i = 0; i < this.parameters.length; i++) { - var parameter = this.parameters[i]; - if(parameter.in === 'formData') { - if (!body) { - body = ''; - } - - var paramValue; - if(typeof FormData === 'function' && obj.body instanceof FormData) { - paramValue = obj.body.getAll(parameter.name); - } - else { - paramValue = obj.body[parameter.name]; - } - if (paramValue) { - if (parameter.type === 'file') { - if(paramValue.name) { - body += '-F ' + parameter.name + '=@"' + paramValue.name + '" '; - } - } - else { - if (Array.isArray(paramValue)) { - if(parameter.collectionFormat === 'multi') { - for(var v in paramValue) { - body += '-F ' + this.encodeQueryKey(parameter.name) + '=' + mask(paramValue[v], parameter.format) + ' '; - } - } - else { - body += '-F ' + this.encodeQueryCollection(parameter.collectionFormat, parameter.name, mask(paramValue, parameter.format)) + ' '; - } - } else { - body += '-F ' + this.encodeQueryKey(parameter.name) + '=' + mask(paramValue, parameter.format) + ' '; - } - } - } - } - } - } - if(!body) { - body = JSON.stringify(obj.body); - } - } else { - body = obj.body; - } - // escape @ => %40, ' => %27 - body = body.replace(/\'/g, '%27').replace(/\n/g, ' \\ \n '); - - if(!isFormData) { - // escape & => %26 - body = body.replace(/&/g, '%26'); - } - if(isMultipart) { - results.push(body); - } - else { - results.push('-d \'' + body.replace(/@/g, '%40') + '\''); - } - } - - return 'curl ' + (results.join(' ')) + ' \'' + obj.url + '\''; -}; - -Operation.prototype.encodePathCollection = function (type, name, value, maskPasswords) { - var encoded = ''; - var i; - var separator = ''; - - if (type === 'ssv') { - separator = '%20'; - } else if (type === 'tsv') { - separator = '%09'; - } else if (type === 'pipes') { - separator = '|'; - } else { - separator = ','; - } - - for (i = 0; i < value.length; i++) { - if (i === 0) { - encoded = this.encodeQueryParam(value[i], maskPasswords); - } else { - encoded += separator + this.encodeQueryParam(value[i], maskPasswords); - } - } - - return encoded; -}; - -Operation.prototype.encodeQueryCollection = function (type, name, value, maskPasswords) { - var encoded = ''; - var i; - - type = type || 'default'; - if (type === 'default' || type === 'multi') { - for (i = 0; i < value.length; i++) { - if (i > 0) {encoded += '&';} - - encoded += this.encodeQueryKey(name) + '=' + mask(this.encodeQueryParam(value[i]), maskPasswords); - } - } else { - var separator = ''; - - if (type === 'csv') { - separator = ','; - } else if (type === 'ssv') { - separator = '%20'; - } else if (type === 'tsv') { - separator = '%09'; - } else if (type === 'pipes') { - separator = '|'; - } else if (type === 'brackets') { - for (i = 0; i < value.length; i++) { - if (i !== 0) { - encoded += '&'; - } - encoded += this.encodeQueryKey(name) + '[]=' + mask(this.encodeQueryParam(value[i]), maskPasswords); - } - } - - if (separator !== '') { - for (i = 0; i < value.length; i++) { - if (i === 0) { - encoded = this.encodeQueryKey(name) + '=' + this.encodeQueryParam(value[i]); - } else { - encoded += separator + this.encodeQueryParam(value[i]); - } - } - } - } - - return encoded; -}; - -Operation.prototype.encodeQueryKey = function (arg) { - return encodeURIComponent(arg) - .replace('%5B','[').replace('%5D', ']').replace('%24', '$'); -}; - -Operation.prototype.encodeQueryParam = function (arg, maskPasswords) { - if(maskPasswords) { - return "******"; - } - return encodeURIComponent(arg); -}; - -/** - * TODO revisit, might not want to leave '/' - **/ -Operation.prototype.encodePathParam = function (pathParam, maskPasswords) { - return encodeURIComponent(pathParam, maskPasswords); -}; - -var mask = function(value, format) { - if(typeof format === 'string' && format === 'password') { - return '******'; - } - return value; -} -},{"../helpers":4,"../http":5,"./model":9,"lodash-compat/lang/cloneDeep":138,"lodash-compat/lang/isEmpty":141,"lodash-compat/lang/isObject":144,"lodash-compat/lang/isUndefined":148,"q":157}],11:[function(require,module,exports){ -'use strict'; - -var OperationGroup = module.exports = function (tag, description, externalDocs, operation) { - this.description = description; - this.externalDocs = externalDocs; - this.name = tag; - this.operation = operation; - this.operationsArray = []; - this.path = tag; - this.tag = tag; -}; - -OperationGroup.prototype.sort = function () { - -}; - - -},{}],12:[function(require,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; -var queue = []; -var draining = false; - -function drainQueue() { - if (draining) { - return; - } - draining = true; - var currentQueue; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - var i = -1; - while (++i < len) { - currentQueue[i](); - } - len = queue.length; - } - draining = false; -} -process.nextTick = function (fun) { - queue.push(fun); - if (!draining) { - setTimeout(drainQueue, 0); - } -}; - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],13:[function(require,module,exports){ -(function (Buffer){ -(function () { - "use strict"; - - function btoa(str) { - var buffer - ; - - if (str instanceof Buffer) { - buffer = str; - } else { - buffer = new Buffer(str.toString(), 'binary'); - } - - return buffer.toString('base64'); - } - - module.exports = btoa; -}()); - -}).call(this,require("buffer").Buffer) - -},{"buffer":14}],14:[function(require,module,exports){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var isArray = require('is-array') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 -Buffer.poolSize = 8192 // not used by this implementation - -var rootParent = {} - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property - * on objects. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = (function () { - function Bar () {} - try { - var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - arr.constructor = Bar - return arr.foo() === 42 && // typed array instances can be augmented - arr.constructor === Bar && // constructor can be set - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } -})() - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -/** - * Class: Buffer - * ============= - * - * The Buffer constructor returns instances of `Uint8Array` that are augmented - * with function properties for all the node `Buffer` API functions. We use - * `Uint8Array` so that square bracket notation works as expected -- it returns - * a single octet. - * - * By augmenting the instances, we can avoid modifying the `Uint8Array` - * prototype. - */ -function Buffer (arg) { - if (!(this instanceof Buffer)) { - // Avoid going through an ArgumentsAdaptorTrampoline in the common case. - if (arguments.length > 1) return new Buffer(arg, arguments[1]) - return new Buffer(arg) - } - - this.length = 0 - this.parent = undefined - - // Common case. - if (typeof arg === 'number') { - return fromNumber(this, arg) - } - - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') - } - - // Unusual. - return fromObject(this, arg) -} - -function fromNumber (that, length) { - that = allocate(that, length < 0 ? 0 : checked(length) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < length; i++) { - that[i] = 0 - } - } - return that -} - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' - - // Assumption: byteLength() return value is always < kMaxLength. - var length = byteLength(string, encoding) | 0 - that = allocate(that, length) - - that.write(string, encoding) - return that -} - -function fromObject (that, object) { - if (Buffer.isBuffer(object)) return fromBuffer(that, object) - - if (isArray(object)) return fromArray(that, object) - - if (object == null) { - throw new TypeError('must start with number, buffer, array or string') - } - - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) - } - } - - if (object.length) return fromArrayLike(that, object) - - return fromJsonObject(that, object) -} - -function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that -} - -function fromArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -// Duplicate of fromArray() to keep fromArray() monomorphic. -function fromTypedArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - // Truncating the elements is probably not what people expect from typed - // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior - // of the old Buffer constructor. - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function fromArrayBuffer (that, array) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - array.byteLength - that = Buffer._augment(new Uint8Array(array)) - } else { - // Fallback: Return an object instance of the Buffer class - that = fromTypedArray(that, new Uint8Array(array)) - } - return that -} - -function fromArrayLike (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. -// Returns a zero-length buffer for inputs that don't conform to the spec. -function fromJsonObject (that, object) { - var array - var length = 0 - - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 - } - that = allocate(that, length) - - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that -} - -function allocate (that, length) { - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = Buffer._augment(new Uint8Array(length)) - } else { - // Fallback: Return an object instance of the Buffer class - that.length = length - that._isBuffer = true - } - - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent - - return that -} - -function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (subject, encoding) { - if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) - - var buf = new Buffer(subject, encoding) - delete buf.parent - return buf -} - -Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - var i = 0 - var len = Math.min(x, y) - while (i < len) { - if (a[i] !== b[i]) break - - ++i - } - - if (i !== len) { - x = a[i] - y = b[i] - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'raw': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') - - if (list.length === 0) { - return new Buffer(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; i++) { - length += list[i].length - } - } - - var buf = new Buffer(length) - var pos = 0 - for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length - } - return buf -} - -function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'binary': - // Deprecated - case 'raw': - case 'raws': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -// pre-set for values that may exist in the future -Buffer.prototype.length = undefined -Buffer.prototype.parent = undefined - -function slowToString (encoding, start, end) { - var loweredCase = false - - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 - - if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'binary': - return binarySlice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' -} - -Buffer.prototype.compare = function compare (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return 0 - return Buffer.compare(this, b) -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 - - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 - - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - - if (typeof val === 'string') { - if (val.length === 0) return -1 // special case: looking for empty string always fails - return String.prototype.indexOf.call(this, val, byteOffset) - } - if (Buffer.isBuffer(val)) { - return arrayIndexOf(this, val, byteOffset) - } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) - } - return arrayIndexOf(this, [ val ], byteOffset) - } - - function arrayIndexOf (arr, val, byteOffset) { - var foundIndex = -1 - for (var i = 0; byteOffset + i < arr.length; i++) { - if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex - } else { - foundIndex = -1 - } - } - return -1 - } - - throw new TypeError('val must be string, number or Buffer') -} - -// `get` is deprecated -Buffer.prototype.get = function get (offset) { - console.log('.get() is deprecated. Access using array indexes instead.') - return this.readUInt8(offset) -} - -// `set` is deprecated -Buffer.prototype.set = function set (v, offset) { - console.log('.set() is deprecated. Access using array indexes instead.') - return this.writeUInt8(v, offset) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) throw new Error('Invalid hex string') - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - var swap = encoding - encoding = offset - offset = length | 0 - length = swap - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'binary': - return binaryWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function binarySlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; i++) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = Buffer._augment(this.subarray(start, end)) - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - } - - if (newBuf.length) newBuf.parent = this.parent || this - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = value - return offset + 1 -} - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = value - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = value - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = value - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = value < 0 ? 1 : 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = value < 0 ? 1 : 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = value - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = value - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = value - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') - if (offset < 0) throw new RangeError('index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start] - } - } else { - target._set(this.subarray(start, start + len), targetStart) - } - - return len -} - -// fill(value, start=0, end=buffer.length) -Buffer.prototype.fill = function fill (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length - - if (end < start) throw new RangeError('end < start') - - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return - - if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') - if (end < 0 || end > this.length) throw new RangeError('end out of bounds') - - var i - if (typeof value === 'number') { - for (i = start; i < end; i++) { - this[i] = value - } - } else { - var bytes = utf8ToBytes(value.toString()) - var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] - } - } - - return this -} - -/** - * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. - * Added in Node 0.12. Only available in browsers that support ArrayBuffer. - */ -Buffer.prototype.toArrayBuffer = function toArrayBuffer () { - if (typeof Uint8Array !== 'undefined') { - if (Buffer.TYPED_ARRAY_SUPPORT) { - return (new Buffer(this)).buffer - } else { - var buf = new Uint8Array(this.length) - for (var i = 0, len = buf.length; i < len; i += 1) { - buf[i] = this[i] - } - return buf.buffer - } - } else { - throw new TypeError('Buffer.toArrayBuffer not supported in this browser') - } -} - -// HELPER FUNCTIONS -// ================ - -var BP = Buffer.prototype - -/** - * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods - */ -Buffer._augment = function _augment (arr) { - arr.constructor = Buffer - arr._isBuffer = true - - // save reference to original Uint8Array set method before overwriting - arr._set = arr.set - - // deprecated - arr.get = BP.get - arr.set = BP.set - - arr.write = BP.write - arr.toString = BP.toString - arr.toLocaleString = BP.toString - arr.toJSON = BP.toJSON - arr.equals = BP.equals - arr.compare = BP.compare - arr.indexOf = BP.indexOf - arr.copy = BP.copy - arr.slice = BP.slice - arr.readUIntLE = BP.readUIntLE - arr.readUIntBE = BP.readUIntBE - arr.readUInt8 = BP.readUInt8 - arr.readUInt16LE = BP.readUInt16LE - arr.readUInt16BE = BP.readUInt16BE - arr.readUInt32LE = BP.readUInt32LE - arr.readUInt32BE = BP.readUInt32BE - arr.readIntLE = BP.readIntLE - arr.readIntBE = BP.readIntBE - arr.readInt8 = BP.readInt8 - arr.readInt16LE = BP.readInt16LE - arr.readInt16BE = BP.readInt16BE - arr.readInt32LE = BP.readInt32LE - arr.readInt32BE = BP.readInt32BE - arr.readFloatLE = BP.readFloatLE - arr.readFloatBE = BP.readFloatBE - arr.readDoubleLE = BP.readDoubleLE - arr.readDoubleBE = BP.readDoubleBE - arr.writeUInt8 = BP.writeUInt8 - arr.writeUIntLE = BP.writeUIntLE - arr.writeUIntBE = BP.writeUIntBE - arr.writeUInt16LE = BP.writeUInt16LE - arr.writeUInt16BE = BP.writeUInt16BE - arr.writeUInt32LE = BP.writeUInt32LE - arr.writeUInt32BE = BP.writeUInt32BE - arr.writeIntLE = BP.writeIntLE - arr.writeIntBE = BP.writeIntBE - arr.writeInt8 = BP.writeInt8 - arr.writeInt16LE = BP.writeInt16LE - arr.writeInt16BE = BP.writeInt16BE - arr.writeInt32LE = BP.writeInt32LE - arr.writeInt32BE = BP.writeInt32BE - arr.writeFloatLE = BP.writeFloatLE - arr.writeFloatBE = BP.writeFloatBE - arr.writeDoubleLE = BP.writeDoubleLE - arr.writeDoubleBE = BP.writeDoubleBE - arr.fill = BP.fill - arr.inspect = BP.inspect - arr.toArrayBuffer = BP.toArrayBuffer - - return arr -} - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; i++) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -},{"base64-js":15,"ieee754":16,"is-array":17}],15:[function(require,module,exports){ -var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - -;(function (exports) { - 'use strict'; - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) - - function decode (elt) { - var code = elt.charCodeAt(0) - if (code === PLUS || - code === PLUS_URL_SAFE) - return 62 // '+' - if (code === SLASH || - code === SLASH_URL_SAFE) - return 63 // '/' - if (code < NUMBER) - return -1 //no match - if (code < NUMBER + 10) - return code - NUMBER + 26 + 26 - if (code < UPPER + 26) - return code - UPPER - if (code < LOWER + 26) - return code - LOWER + 26 - } - - function b64ToByteArray (b64) { - var i, j, l, tmp, placeHolders, arr - - if (b64.length % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - var len = b64.length - placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(b64.length * 3 / 4 - placeHolders) - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length - - var L = 0 - - function push (v) { - arr[L++] = v - } - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) - push((tmp & 0xFF0000) >> 16) - push((tmp & 0xFF00) >> 8) - push(tmp & 0xFF) - } - - if (placeHolders === 2) { - tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) - push(tmp & 0xFF) - } else if (placeHolders === 1) { - tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) - push((tmp >> 8) & 0xFF) - push(tmp & 0xFF) - } - - return arr - } - - function uint8ToBase64 (uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length - - function encode (num) { - return lookup.charAt(num) - } - - function tripletToBase64 (num) { - return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) - } - - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) - output += tripletToBase64(temp) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1] - output += encode(temp >> 2) - output += encode((temp << 4) & 0x3F) - output += '==' - break - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) - output += encode(temp >> 10) - output += encode((temp >> 4) & 0x3F) - output += encode((temp << 2) & 0x3F) - output += '=' - break - } - - return output - } - - exports.toByteArray = b64ToByteArray - exports.fromByteArray = uint8ToBase64 -}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) - -},{}],16:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],17:[function(require,module,exports){ - -/** - * isArray - */ - -var isArray = Array.isArray; - -/** - * toString - */ - -var str = Object.prototype.toString; - -/** - * Whether or not the given `val` - * is an array. - * - * example: - * - * isArray([]); - * // > true - * isArray(arguments); - * // > false - * isArray(''); - * // > false - * - * @param {mixed} val - * @return {bool} - */ - -module.exports = isArray || function (val) { - return !! val && '[object Array]' == str.call(val); -}; - -},{}],18:[function(require,module,exports){ -/* jshint node: true */ -(function () { - "use strict"; - - function CookieAccessInfo(domain, path, secure, script) { - if (this instanceof CookieAccessInfo) { - this.domain = domain || undefined; - this.path = path || "/"; - this.secure = !!secure; - this.script = !!script; - return this; - } - return new CookieAccessInfo(domain, path, secure, script); - } - exports.CookieAccessInfo = CookieAccessInfo; - - function Cookie(cookiestr, request_domain, request_path) { - if (cookiestr instanceof Cookie) { - return cookiestr; - } - if (this instanceof Cookie) { - this.name = null; - this.value = null; - this.expiration_date = Infinity; - this.path = String(request_path || "/"); - this.explicit_path = false; - this.domain = request_domain || null; - this.explicit_domain = false; - this.secure = false; //how to define default? - this.noscript = false; //httponly - if (cookiestr) { - this.parse(cookiestr, request_domain, request_path); - } - return this; - } - return new Cookie(cookiestr, request_domain, request_path); - } - exports.Cookie = Cookie; - - Cookie.prototype.toString = function toString() { - var str = [this.name + "=" + this.value]; - if (this.expiration_date !== Infinity) { - str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); - } - if (this.domain) { - str.push("domain=" + this.domain); - } - if (this.path) { - str.push("path=" + this.path); - } - if (this.secure) { - str.push("secure"); - } - if (this.noscript) { - str.push("httponly"); - } - return str.join("; "); - }; - - Cookie.prototype.toValueString = function toValueString() { - return this.name + "=" + this.value; - }; - - var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; - Cookie.prototype.parse = function parse(str, request_domain, request_path) { - if (this instanceof Cookie) { - var parts = str.split(";").filter(function (value) { - return !!value; - }), - pair = parts[0].match(/([^=]+)=([\s\S]*)/), - key = pair[1], - value = pair[2], - i; - this.name = key; - this.value = value; - - for (i = 1; i < parts.length; i += 1) { - pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); - key = pair[1].trim().toLowerCase(); - value = pair[2]; - switch (key) { - case "httponly": - this.noscript = true; - break; - case "expires": - this.expiration_date = value ? - Number(Date.parse(value)) : - Infinity; - break; - case "path": - this.path = value ? - value.trim() : - ""; - this.explicit_path = true; - break; - case "domain": - this.domain = value ? - value.trim() : - ""; - this.explicit_domain = !!this.domain; - break; - case "secure": - this.secure = true; - break; - } - } - - if (!this.explicit_path) { - this.path = request_path || "/"; - } - if (!this.explicit_domain) { - this.domain = request_domain; - } - - return this; - } - return new Cookie().parse(str, request_domain, request_path); - }; - - Cookie.prototype.matches = function matches(access_info) { - if (this.noscript && access_info.script || - this.secure && !access_info.secure || - !this.collidesWith(access_info)) { - return false; - } - return true; - }; - - Cookie.prototype.collidesWith = function collidesWith(access_info) { - if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { - return false; - } - if (this.path && access_info.path.indexOf(this.path) !== 0) { - return false; - } - if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { - return false; - } - var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); - var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); - if (cookie_domain === access_domain) { - return true; - } - if (cookie_domain) { - if (!this.explicit_domain) { - return false; // we already checked if the domains were exactly the same - } - var wildcard = access_domain.indexOf(cookie_domain); - if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { - return false; - } - return true; - } - return true; - }; - - function CookieJar() { - var cookies, cookies_list, collidable_cookie; - if (this instanceof CookieJar) { - cookies = Object.create(null); //name: [Cookie] - - this.setCookie = function setCookie(cookie, request_domain, request_path) { - var remove, i; - cookie = new Cookie(cookie, request_domain, request_path); - //Delete the cookie if the set is past the current time - remove = cookie.expiration_date <= Date.now(); - if (cookies[cookie.name] !== undefined) { - cookies_list = cookies[cookie.name]; - for (i = 0; i < cookies_list.length; i += 1) { - collidable_cookie = cookies_list[i]; - if (collidable_cookie.collidesWith(cookie)) { - if (remove) { - cookies_list.splice(i, 1); - if (cookies_list.length === 0) { - delete cookies[cookie.name]; - } - return false; - } - cookies_list[i] = cookie; - return cookie; - } - } - if (remove) { - return false; - } - cookies_list.push(cookie); - return cookie; - } - if (remove) { - return false; - } - cookies[cookie.name] = [cookie]; - return cookies[cookie.name]; - }; - //returns a cookie - this.getCookie = function getCookie(cookie_name, access_info) { - var cookie, i; - cookies_list = cookies[cookie_name]; - if (!cookies_list) { - return; - } - for (i = 0; i < cookies_list.length; i += 1) { - cookie = cookies_list[i]; - if (cookie.expiration_date <= Date.now()) { - if (cookies_list.length === 0) { - delete cookies[cookie.name]; - } - continue; - } - - if (cookie.matches(access_info)) { - return cookie; - } - } - }; - //returns a list of cookies - this.getCookies = function getCookies(access_info) { - var matches = [], cookie_name, cookie; - for (cookie_name in cookies) { - cookie = this.getCookie(cookie_name, access_info); - if (cookie) { - matches.push(cookie); - } - } - matches.toString = function toString() { - return matches.join(":"); - }; - matches.toValueString = function toValueString() { - return matches.map(function (c) { - return c.toValueString(); - }).join(';'); - }; - return matches; - }; - - return this; - } - return new CookieJar(); - } - exports.CookieJar = CookieJar; - - //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. - CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { - cookies = Array.isArray(cookies) ? - cookies : - cookies.split(cookie_str_splitter); - var successful = [], - i, - cookie; - cookies = cookies.map(function(item){ - return new Cookie(item, request_domain, request_path); - }); - for (i = 0; i < cookies.length; i += 1) { - cookie = cookies[i]; - if (this.setCookie(cookie, request_domain, request_path)) { - successful.push(cookie); - } - } - return successful; - }; -}()); - -},{}],19:[function(require,module,exports){ -'use strict'; - - -var yaml = require('./lib/js-yaml.js'); - - -module.exports = yaml; - -},{"./lib/js-yaml.js":20}],20:[function(require,module,exports){ -'use strict'; - - -var loader = require('./js-yaml/loader'); -var dumper = require('./js-yaml/dumper'); - - -function deprecated(name) { - return function () { - throw new Error('Function ' + name + ' is deprecated and cannot be used.'); - }; -} - - -module.exports.Type = require('./js-yaml/type'); -module.exports.Schema = require('./js-yaml/schema'); -module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe'); -module.exports.JSON_SCHEMA = require('./js-yaml/schema/json'); -module.exports.CORE_SCHEMA = require('./js-yaml/schema/core'); -module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe'); -module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full'); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.safeLoad = loader.safeLoad; -module.exports.safeLoadAll = loader.safeLoadAll; -module.exports.dump = dumper.dump; -module.exports.safeDump = dumper.safeDump; -module.exports.YAMLException = require('./js-yaml/exception'); - -// Deprecated schema names from JS-YAML 2.0.x -module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe'); -module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe'); -module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full'); - -// Deprecated functions from JS-YAML 1.x.x -module.exports.scan = deprecated('scan'); -module.exports.parse = deprecated('parse'); -module.exports.compose = deprecated('compose'); -module.exports.addConstructor = deprecated('addConstructor'); - -},{"./js-yaml/dumper":22,"./js-yaml/exception":23,"./js-yaml/loader":24,"./js-yaml/schema":26,"./js-yaml/schema/core":27,"./js-yaml/schema/default_full":28,"./js-yaml/schema/default_safe":29,"./js-yaml/schema/failsafe":30,"./js-yaml/schema/json":31,"./js-yaml/type":32}],21:[function(require,module,exports){ -'use strict'; - - -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} - - -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} - - -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; -} - - -function extend(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } - } - - return target; -} - - -function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } - - return result; -} - - -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} - - -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; - -},{}],22:[function(require,module,exports){ -'use strict'; - -/*eslint-disable no-use-before-define*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); -var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - - if (map === null) return {}; - - result = {}; - keys = Object.keys(map); - - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - - type = schema.compiledTypeMap[tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } - - result[tag] = style; - } - - return result; -} - -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} - -function State(options) { - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; - - this.tag = null; - this.result = ''; - - this.duplicates = []; - this.usedDuplicates = null; -} - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } - - if (line.length && line !== '\n') result += ind; - - result += line; - } - - return result; -} - -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} - -function testImplicitResolving(state, str) { - var index, length, type; - - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - - if (type.resolve(str)) { - return true; - } - } - - return false; -} - -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); -} - -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c) { - // Uses a subset of nb-char - c-flow-indicator - ":" - "#" - // where nb-char ::= c-printable - b-char - c-byte-order-mark. - return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - && c !== CHAR_COLON - && c !== CHAR_SHARP; -} - -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} - -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; - -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { - var i; - var char; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); - - if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char); - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char); - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (string[0] === ' ' && indentPerLevel > 9) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; -} - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { - state.dump = (function () { - if (string.length === 0) { - return "''"; - } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; - } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } - }()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = (string[0] === ' ') ? String(indentPerLevel) : ''; - - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); - - return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; - - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; - - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; - - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } - - return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char; - var escapeSeq; - - for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - - return result; -} - -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ', '; - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; -} - -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } - _result += '- ' + state.dump; - } - } - - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. -} - -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (index !== 0) pairBuffer += ', '; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + ': '; - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = '{' + _result + '}'; -} - -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } - - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); - - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } - - pairBuffer += state.dump; - - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} - -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - - state.tag = explicit ? type.tag : '?'; - - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; - - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } - - state.dump = _result; - } - - return true; - } - } - - return false; -} - -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } - - var type = _toString.call(state.dump); - - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } - - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; - - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } - - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } - - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); - } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; - } - } - - return true; -} - -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); - - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} - -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; - - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); - - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } - } - } -} - -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - - if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; - - return ''; -} - -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - -module.exports.dump = dump; -module.exports.safeDump = safeDump; - -},{"./common":21,"./exception":23,"./schema/default_full":28,"./schema/default_safe":29}],23:[function(require,module,exports){ -// YAML error class. http://stackoverflow.com/questions/8458984 -// -'use strict'; - -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); -} - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; - - result += this.reason || '(unknown reason)'; - - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); - } - - return result; -}; - - -module.exports = YAMLException; - -},{}],24:[function(require,module,exports){ -'use strict'; - -/*eslint-disable max-len,no-use-before-define*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var Mark = require('./mark'); -var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); -var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} - -function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; -} - -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} - -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; -} - -function simpleEscapeSequence(c) { - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} - -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode(((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00); -} - -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); -} - - -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.onWarning = options['onWarning'] || null; - this.legacy = options['legacy'] || false; - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - -} - - -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} - -function throwError(state, message) { - throw generateError(state, message); -} - -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} - - -var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - state.tagMap[handle] = prefix; - } -}; - - -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; - _position < _length; - _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; - } - } -} - -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode) { - var index, quantity; - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; - } - - return _result; -} - -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; -} - -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; -} - -function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; -} - -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} - - -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = captureEnd = state.position; - state.position++; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} - -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else { - break; // Reading is done. Go to the epilogue. - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; -} - -function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!state.anchorMap.hasOwnProperty(alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; - typeIndex < typeQuantity; - typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only assigned to plain scalars. So, it isn't - // needed to check for 'kind' conformity. - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap, state.tag)) { - type = state.typeMap[state.tag]; - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} - - -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } - } - - var state = new State(input, options); - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; -} - - -function loadAll(input, iterator, options) { - var documents = loadDocuments(input, options), index, length; - - for (index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} - - -function load(input, options) { - var documents = loadDocuments(input, options); - - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} - - -function safeLoadAll(input, output, options) { - loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} - - -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; - -},{"./common":21,"./exception":23,"./mark":25,"./schema/default_full":28,"./schema/default_safe":29}],25:[function(require,module,exports){ -'use strict'; - - -var common = require('./common'); - - -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} - - -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; - - if (!this.buffer) return null; - - indent = indent || 4; - maxLength = maxLength || 75; - - head = ''; - start = this.position; - - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } - } - - tail = ''; - end = this.position; - - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; - } - } - - snippet = this.buffer.slice(start, end); - - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; - - -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; - - if (this.name) { - where += 'in "' + this.name + '" '; - } - - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - - if (!compact) { - snippet = this.getSnippet(); - - if (snippet) { - where += ':\n' + snippet; - } - } - - return where; -}; - - -module.exports = Mark; - -},{"./common":21}],26:[function(require,module,exports){ -'use strict'; - -/*eslint-disable max-len*/ - -var common = require('./common'); -var YAMLException = require('./exception'); -var Type = require('./type'); - - -function compileList(schema, name, result) { - var exclude = []; - - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); - }); - - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag) { - exclude.push(previousIndex); - } - }); - - result.push(currentType); - }); - - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); -} - - -function compileMap(/* lists... */) { - var result = {}, index, length; - - function collectType(type) { - result[type.tag] = type; - } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - - return result; -} - - -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; - - this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - }); - - this.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} - - -Schema.DEFAULT = null; - - -Schema.create = function createSchema() { - var schemas, types; - - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; - - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; - - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); - } - - schemas = common.toArray(schemas); - types = common.toArray(types); - - if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); - } - - if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - return new Schema({ - include: schemas, - explicit: types - }); -}; - - -module.exports = Schema; - -},{"./common":21,"./exception":23,"./type":32}],27:[function(require,module,exports){ -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./json') - ] -}); - -},{"../schema":26,"./json":31}],28:[function(require,module,exports){ -// JS-YAML's default schema for `load` function. -// It is not described in the YAML specification. -// -// This schema is based on JS-YAML's default safe schema and includes -// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. -// -// Also this schema is used as default base schema at `Schema.create` function. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = Schema.DEFAULT = new Schema({ - include: [ - require('./default_safe') - ], - explicit: [ - require('../type/js/undefined'), - require('../type/js/regexp'), - require('../type/js/function') - ] -}); - -},{"../schema":26,"../type/js/function":37,"../type/js/regexp":38,"../type/js/undefined":39,"./default_safe":29}],29:[function(require,module,exports){ -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./core') - ], - implicit: [ - require('../type/timestamp'), - require('../type/merge') - ], - explicit: [ - require('../type/binary'), - require('../type/omap'), - require('../type/pairs'), - require('../type/set') - ] -}); - -},{"../schema":26,"../type/binary":33,"../type/merge":41,"../type/omap":43,"../type/pairs":44,"../type/set":46,"../type/timestamp":48,"./core":27}],30:[function(require,module,exports){ -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - explicit: [ - require('../type/str'), - require('../type/seq'), - require('../type/map') - ] -}); - -},{"../schema":26,"../type/map":40,"../type/seq":45,"../type/str":47}],31:[function(require,module,exports){ -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - - -'use strict'; - - -var Schema = require('../schema'); - - -module.exports = new Schema({ - include: [ - require('./failsafe') - ], - implicit: [ - require('../type/null'), - require('../type/bool'), - require('../type/int'), - require('../type/float') - ] -}); - -},{"../schema":26,"../type/bool":34,"../type/float":35,"../type/int":36,"../type/null":42,"./failsafe":30}],32:[function(require,module,exports){ -'use strict'; - -var YAMLException = require('./exception'); - -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; - -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; - -function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; -} - -function Type(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} - -module.exports = Type; - -},{"./exception":23}],33:[function(require,module,exports){ -'use strict'; - -/*eslint-disable no-bitwise*/ - -var NodeBuffer; - -try { - // A trick for browserified version, to not include `Buffer` shim - var _require = require; - NodeBuffer = _require('buffer').Buffer; -} catch (__) {} - -var Type = require('../type'); - - -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - -function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} - -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - // Wrap into Buffer for NodeJS and leave Array for browser - if (NodeBuffer) return new NodeBuffer(result); - - return result; -} - -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; -} - -function isBinary(object) { - return NodeBuffer && NodeBuffer.isBuffer(object); -} - -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); - -},{"../type":32}],34:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} - -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} - -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} - -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); - -},{"../type":32}],35:[function(require,module,exports){ -'use strict'; - -var common = require('../common'); -var Type = require('../type'); - -var YAML_FLOAT_PATTERN = new RegExp( - '^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' + - '|\\.[0-9_]+(?:[eE][-+][0-9]+)?' + - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - '|[-+]?\\.(?:inf|Inf|INF)' + - '|\\.(?:nan|NaN|NAN))$'); - -function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data)) return false; - - return true; -} - -function constructYamlFloat(data) { - var value, sign, base, digits; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); - - value = 0.0; - base = 1; - - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); - - return sign * value; - - } - return sign * parseFloat(value, 10); -} - - -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} - -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); - -},{"../common":21,"../type":32}],36:[function(require,module,exports){ -'use strict'; - -var common = require('../common'); -var Type = require('../type'); - -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} - -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} - -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} - -function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits; - } - - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits; - } - - // base 10 (except 0) or base 60 - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch === ':') break; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; - } - - if (!hasDigits) return false; - - // if !base60 - done; - if (ch !== ':') return true; - - // base60 almost not used, no needs to optimize - return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); -} - -function constructYamlInteger(data) { - var value = data, sign = 1, ch, base, digits = []; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value, 16); - return sign * parseInt(value, 8); - } - - if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); - - value = 0; - base = 1; - - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); - - return sign * value; - - } - - return sign * parseInt(value, 10); -} - -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (object) { return '0b' + object.toString(2); }, - octal: function (object) { return '0' + object.toString(8); }, - decimal: function (object) { return object.toString(10); }, - hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } -}); - -},{"../common":21,"../type":32}],37:[function(require,module,exports){ -'use strict'; - -var esprima; - -// Browserified version does not have esprima -// -// 1. For node.js just require module as deps -// 2. For browser try to require mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { - // workaround to exclude package from browserify list. - var _require = require; - esprima = _require('esprima'); -} catch (_) { - /*global window */ - if (typeof window !== 'undefined') esprima = window.esprima; -} - -var Type = require('../../type'); - -function resolveJavascriptFunction(data) { - if (data === null) return false; - - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - ast.body[0].expression.type !== 'FunctionExpression') { - return false; - } - - return true; - } catch (err) { - return false; - } -} - -function constructJavascriptFunction(data) { - /*jslint evil:true*/ - - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; - - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - ast.body[0].expression.type !== 'FunctionExpression') { - throw new Error('Failed to resolve function'); - } - - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); - - body = ast.body[0].expression.body.range; - - // Esprima's ranges include the first '{' and the last '}' characters on - // function expressions. So cut them out. - /*eslint-disable no-new-func*/ - return new Function(params, source.slice(body[0] + 1, body[1] - 1)); -} - -function representJavascriptFunction(object /*, style*/) { - return object.toString(); -} - -function isFunction(object) { - return Object.prototype.toString.call(object) === '[object Function]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/function', { - kind: 'scalar', - resolve: resolveJavascriptFunction, - construct: constructJavascriptFunction, - predicate: isFunction, - represent: representJavascriptFunction -}); - -},{"../../type":32}],38:[function(require,module,exports){ -'use strict'; - -var Type = require('../../type'); - -function resolveJavascriptRegExp(data) { - if (data === null) return false; - if (data.length === 0) return false; - - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // if regexp starts with '/' it can have modifiers and must be properly closed - // `/foo/gim` - modifiers tail can be maximum 3 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; - } - - return true; -} - -function constructJavascriptRegExp(data) { - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; - - // `/foo/gim` - tail can be maximum 4 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); - } - - return new RegExp(regexp, modifiers); -} - -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; - - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; - - return result; -} - -function isRegExp(object) { - return Object.prototype.toString.call(object) === '[object RegExp]'; -} - -module.exports = new Type('tag:yaml.org,2002:js/regexp', { - kind: 'scalar', - resolve: resolveJavascriptRegExp, - construct: constructJavascriptRegExp, - predicate: isRegExp, - represent: representJavascriptRegExp -}); - -},{"../../type":32}],39:[function(require,module,exports){ -'use strict'; - -var Type = require('../../type'); - -function resolveJavascriptUndefined() { - return true; -} - -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} - -function representJavascriptUndefined() { - return ''; -} - -function isUndefined(object) { - return typeof object === 'undefined'; -} - -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); - -},{"../../type":32}],40:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); - -},{"../type":32}],41:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} - -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); - -},{"../type":32}],42:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { - return null; -} - -function isNull(object) { - return object === null; -} - -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } - }, - defaultStyle: 'lowercase' -}); - -},{"../type":32}],43:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; - -function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; -} - -function constructYamlOmap(data) { - return data !== null ? data : []; -} - -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - -},{"../type":32}],44:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; -} - -function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; -} - -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); - -},{"../type":32}],45:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); - -},{"../type":32}],46:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; -} - -function constructYamlSet(data) { - return data !== null ? data : {}; -} - -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - -},{"../type":32}],47:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); - -},{"../type":32}],48:[function(require,module,exports){ -'use strict'; - -var Type = require('../type'); - -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} - -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} - -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} - -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); - -},{"../type":32}],49:[function(require,module,exports){ -var baseIndexOf = require('../internal/baseIndexOf'), - binaryIndex = require('../internal/binaryIndex'); - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the offset - * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` - * performs a faster binary search. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {boolean|number} [fromIndex=0] The index to search from or `true` - * to perform a binary search on a sorted array. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // using `fromIndex` - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - * - * // performing a binary search - * _.indexOf([1, 1, 2, 2], 2, true); - * // => 2 - */ -function indexOf(array, value, fromIndex) { - var length = array ? array.length : 0; - if (!length) { - return -1; - } - if (typeof fromIndex == 'number') { - fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; - } else if (fromIndex) { - var index = binaryIndex(array, value); - if (index < length && - (value === value ? (value === array[index]) : (array[index] !== array[index]))) { - return index; - } - return -1; - } - return baseIndexOf(array, value, fromIndex || 0); -} - -module.exports = indexOf; - -},{"../internal/baseIndexOf":78,"../internal/binaryIndex":92}],50:[function(require,module,exports){ -/** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ -function last(array) { - var length = array ? array.length : 0; - return length ? array[length - 1] : undefined; -} - -module.exports = last; - -},{}],51:[function(require,module,exports){ -var LazyWrapper = require('../internal/LazyWrapper'), - LodashWrapper = require('../internal/LodashWrapper'), - baseLodash = require('../internal/baseLodash'), - isArray = require('../lang/isArray'), - isObjectLike = require('../internal/isObjectLike'), - wrapperClone = require('../internal/wrapperClone'); - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Creates a `lodash` object which wraps `value` to enable implicit chaining. - * Methods that operate on and return arrays, collections, and functions can - * be chained together. Methods that retrieve a single value or may return a - * primitive value will automatically end the chain returning the unwrapped - * value. Explicit chaining may be enabled using `_.chain`. The execution of - * chained methods is lazy, that is, execution is deferred until `_#value` - * is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. Shortcut - * fusion is an optimization strategy which merge iteratee calls; this can help - * to avoid the creation of intermediate data structures and greatly reduce the - * number of iteratee executions. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, - * `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, - * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, - * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, - * and `where` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, - * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, - * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`, - * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`, - * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, - * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, - * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, - * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, - * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`, - * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, - * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, - * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`, - * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, - * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`, - * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, - * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`, - * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`, - * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, - * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, - * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, - * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, - * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`, - * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`, - * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`, - * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`, - * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`, - * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, - * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, - * `unescape`, `uniqueId`, `value`, and `words` - * - * The wrapper method `sample` will return a wrapped value when `n` is provided, - * otherwise an unwrapped value is returned. - * - * @name _ - * @constructor - * @category Chain - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var wrapped = _([1, 2, 3]); - * - * // returns an unwrapped value - * wrapped.reduce(function(total, n) { - * return total + n; - * }); - * // => 6 - * - * // returns a wrapped value - * var squares = wrapped.map(function(n) { - * return n * n; - * }); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ -function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); -} - -// Ensure wrappers are instances of `baseLodash`. -lodash.prototype = baseLodash.prototype; - -module.exports = lodash; - -},{"../internal/LazyWrapper":60,"../internal/LodashWrapper":61,"../internal/baseLodash":82,"../internal/isObjectLike":126,"../internal/wrapperClone":137,"../lang/isArray":140}],52:[function(require,module,exports){ -module.exports = require('./forEach'); - -},{"./forEach":54}],53:[function(require,module,exports){ -var baseEach = require('../internal/baseEach'), - createFind = require('../internal/createFind'); - -/** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is bound to `thisArg` and - * invoked with three arguments: (value, index|key, collection). - * - * If a property name is provided for `predicate` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `predicate` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * @static - * @memberOf _ - * @alias detect - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {Function|Object|string} [predicate=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `predicate`. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.result(_.find(users, function(chr) { - * return chr.age < 40; - * }), 'user'); - * // => 'barney' - * - * // using the `_.matches` callback shorthand - * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); - * // => 'pebbles' - * - * // using the `_.matchesProperty` callback shorthand - * _.result(_.find(users, 'active', false), 'user'); - * // => 'fred' - * - * // using the `_.property` callback shorthand - * _.result(_.find(users, 'active'), 'user'); - * // => 'barney' - */ -var find = createFind(baseEach); - -module.exports = find; - -},{"../internal/baseEach":71,"../internal/createFind":102}],54:[function(require,module,exports){ -var arrayEach = require('../internal/arrayEach'), - baseEach = require('../internal/baseEach'), - createForEach = require('../internal/createForEach'); - -/** - * Iterates over elements of `collection` invoking `iteratee` for each element. - * The `iteratee` is bound to `thisArg` and invoked with three arguments: - * (value, index|key, collection). Iteratee functions may exit iteration early - * by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" property - * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` - * may be used for object iteration. - * - * @static - * @memberOf _ - * @alias each - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2]).forEach(function(n) { - * console.log(n); - * }).value(); - * // => logs each value from left to right and returns the array - * - * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { - * console.log(n, key); - * }); - * // => logs each value-key pair and returns the object (iteration order is not guaranteed) - */ -var forEach = createForEach(arrayEach, baseEach); - -module.exports = forEach; - -},{"../internal/arrayEach":63,"../internal/baseEach":71,"../internal/createForEach":103}],55:[function(require,module,exports){ -var baseIndexOf = require('../internal/baseIndexOf'), - getLength = require('../internal/getLength'), - isArray = require('../lang/isArray'), - isIterateeCall = require('../internal/isIterateeCall'), - isLength = require('../internal/isLength'), - isString = require('../lang/isString'), - values = require('../object/values'); - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Checks if `target` is in `collection` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the offset - * from the end of `collection`. - * - * @static - * @memberOf _ - * @alias contains, include - * @category Collection - * @param {Array|Object|string} collection The collection to search. - * @param {*} target The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. - * @returns {boolean} Returns `true` if a matching element is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); - * // => true - * - * _.includes('pebbles', 'eb'); - * // => true - */ -function includes(collection, target, fromIndex, guard) { - var length = collection ? getLength(collection) : 0; - if (!isLength(length)) { - collection = values(collection); - length = collection.length; - } - if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { - fromIndex = 0; - } else { - fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); - } - return (typeof collection == 'string' || !isArray(collection) && isString(collection)) - ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1) - : (!!length && baseIndexOf(collection, target, fromIndex) > -1); -} - -module.exports = includes; - -},{"../internal/baseIndexOf":78,"../internal/getLength":112,"../internal/isIterateeCall":122,"../internal/isLength":125,"../lang/isArray":140,"../lang/isString":146,"../object/values":152}],56:[function(require,module,exports){ -var arrayMap = require('../internal/arrayMap'), - baseCallback = require('../internal/baseCallback'), - baseMap = require('../internal/baseMap'), - isArray = require('../lang/isArray'); - -/** - * Creates an array of values by running each element in `collection` through - * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three - * arguments: (value, index|key, collection). - * - * If a property name is provided for `iteratee` the created `_.property` - * style callback returns the property value of the given element. - * - * If a value is also provided for `thisArg` the created `_.matchesProperty` - * style callback returns `true` for elements that have a matching property - * value, else `false`. - * - * If an object is provided for `iteratee` the created `_.matches` style - * callback returns `true` for elements that have the properties of the given - * object, else `false`. - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, - * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, - * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, - * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, - * `sum`, `uniq`, and `words` - * - * @static - * @memberOf _ - * @alias collect - * @category Collection - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [iteratee=_.identity] The function invoked - * per iteration. - * @param {*} [thisArg] The `this` binding of `iteratee`. - * @returns {Array} Returns the new mapped array. - * @example - * - * function timesThree(n) { - * return n * 3; - * } - * - * _.map([1, 2], timesThree); - * // => [3, 6] - * - * _.map({ 'a': 1, 'b': 2 }, timesThree); - * // => [3, 6] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // using the `_.property` callback shorthand - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ -function map(collection, iteratee, thisArg) { - var func = isArray(collection) ? arrayMap : baseMap; - iteratee = baseCallback(iteratee, thisArg, 3); - return func(collection, iteratee); -} - -module.exports = map; - -},{"../internal/arrayMap":64,"../internal/baseCallback":67,"../internal/baseMap":83,"../lang/isArray":140}],57:[function(require,module,exports){ -var getNative = require('../internal/getNative'); - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeNow = getNative(Date, 'now'); - -/** - * Gets the number of milliseconds that have elapsed since the Unix epoch - * (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @category Date - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => logs the number of milliseconds it took for the deferred function to be invoked - */ -var now = nativeNow || function() { - return new Date().getTime(); -}; - -module.exports = now; - -},{"../internal/getNative":114}],58:[function(require,module,exports){ -var createWrapper = require('../internal/createWrapper'), - replaceHolders = require('../internal/replaceHolders'), - restParam = require('./restParam'); - -/** Used to compose bitmasks for wrapper metadata. */ -var BIND_FLAG = 1, - PARTIAL_FLAG = 32; - -/** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and prepends any additional `_.bind` arguments to those provided to the - * bound function. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind` this method does not set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var greet = function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * }; - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // using placeholders - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ -var bind = restParam(function(func, thisArg, partials) { - var bitmask = BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, bind.placeholder); - bitmask |= PARTIAL_FLAG; - } - return createWrapper(func, bitmask, thisArg, partials, holders); -}); - -// Assign default placeholders. -bind.placeholder = {}; - -module.exports = bind; - -},{"../internal/createWrapper":106,"../internal/replaceHolders":132,"./restParam":59}],59:[function(require,module,exports){ -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as an array. - * - * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). - * - * @static - * @memberOf _ - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.restParam(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ -function restParam(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - rest = Array(length); - - while (++index < length) { - rest[index] = args[start + index]; - } - switch (start) { - case 0: return func.call(this, rest); - case 1: return func.call(this, args[0], rest); - case 2: return func.call(this, args[0], args[1], rest); - } - var otherArgs = Array(start + 1); - index = -1; - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = rest; - return func.apply(this, otherArgs); - }; -} - -module.exports = restParam; - -},{}],60:[function(require,module,exports){ -var baseCreate = require('./baseCreate'), - baseLodash = require('./baseLodash'); - -/** Used as references for `-Infinity` and `Infinity`. */ -var POSITIVE_INFINITY = Number.POSITIVE_INFINITY; - -/** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @param {*} value The value to wrap. - */ -function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = POSITIVE_INFINITY; - this.__views__ = []; -} - -LazyWrapper.prototype = baseCreate(baseLodash.prototype); -LazyWrapper.prototype.constructor = LazyWrapper; - -module.exports = LazyWrapper; - -},{"./baseCreate":70,"./baseLodash":82}],61:[function(require,module,exports){ -var baseCreate = require('./baseCreate'), - baseLodash = require('./baseLodash'); - -/** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable chaining for all wrapper methods. - * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. - */ -function LodashWrapper(value, chainAll, actions) { - this.__wrapped__ = value; - this.__actions__ = actions || []; - this.__chain__ = !!chainAll; -} - -LodashWrapper.prototype = baseCreate(baseLodash.prototype); -LodashWrapper.prototype.constructor = LodashWrapper; - -module.exports = LodashWrapper; - -},{"./baseCreate":70,"./baseLodash":82}],62:[function(require,module,exports){ -/** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ -function arrayCopy(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; -} - -module.exports = arrayCopy; - -},{}],63:[function(require,module,exports){ -/** - * A specialized version of `_.forEach` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ -function arrayEach(array, iteratee) { - var index = -1, - length = array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; -} - -module.exports = arrayEach; - -},{}],64:[function(require,module,exports){ -/** - * A specialized version of `_.map` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -module.exports = arrayMap; - -},{}],65:[function(require,module,exports){ -/** - * A specialized version of `_.some` for arrays without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ -function arraySome(array, predicate) { - var index = -1, - length = array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; -} - -module.exports = arraySome; - -},{}],66:[function(require,module,exports){ -var baseCopy = require('./baseCopy'), - keys = require('../object/keys'); - -/** - * The base implementation of `_.assign` without support for argument juggling, - * multiple sources, and `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ -function baseAssign(object, source) { - return source == null - ? object - : baseCopy(source, keys(source), object); -} - -module.exports = baseAssign; - -},{"../object/keys":149,"./baseCopy":69}],67:[function(require,module,exports){ -var baseMatches = require('./baseMatches'), - baseMatchesProperty = require('./baseMatchesProperty'), - bindCallback = require('./bindCallback'), - identity = require('../utility/identity'), - property = require('../utility/property'); - -/** - * The base implementation of `_.callback` which supports specifying the - * number of arguments to provide to `func`. - * - * @private - * @param {*} [func=_.identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {number} [argCount] The number of arguments to provide to `func`. - * @returns {Function} Returns the callback. - */ -function baseCallback(func, thisArg, argCount) { - var type = typeof func; - if (type == 'function') { - return thisArg === undefined - ? func - : bindCallback(func, thisArg, argCount); - } - if (func == null) { - return identity; - } - if (type == 'object') { - return baseMatches(func); - } - return thisArg === undefined - ? property(func) - : baseMatchesProperty(func, thisArg); -} - -module.exports = baseCallback; - -},{"../utility/identity":154,"../utility/property":156,"./baseMatches":84,"./baseMatchesProperty":85,"./bindCallback":94}],68:[function(require,module,exports){ -var arrayCopy = require('./arrayCopy'), - arrayEach = require('./arrayEach'), - baseAssign = require('./baseAssign'), - baseForOwn = require('./baseForOwn'), - initCloneArray = require('./initCloneArray'), - initCloneByTag = require('./initCloneByTag'), - initCloneObject = require('./initCloneObject'), - isArray = require('../lang/isArray'), - isHostObject = require('./isHostObject'), - isObject = require('../lang/isObject'); - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values supported by `_.clone`. */ -var cloneableTags = {}; -cloneableTags[argsTag] = cloneableTags[arrayTag] = -cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = -cloneableTags[dateTag] = cloneableTags[float32Tag] = -cloneableTags[float64Tag] = cloneableTags[int8Tag] = -cloneableTags[int16Tag] = cloneableTags[int32Tag] = -cloneableTags[numberTag] = cloneableTags[objectTag] = -cloneableTags[regexpTag] = cloneableTags[stringTag] = -cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = -cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; -cloneableTags[errorTag] = cloneableTags[funcTag] = -cloneableTags[mapTag] = cloneableTags[setTag] = -cloneableTags[weakMapTag] = false; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** - * The base implementation of `_.clone` without support for argument juggling - * and `this` binding `customizer` functions. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The object `value` belongs to. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates clones with source counterparts. - * @returns {*} Returns the cloned value. - */ -function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { - var result; - if (customizer) { - result = object ? customizer(value, key, object) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return arrayCopy(value, result); - } - } else { - var tag = objToString.call(value), - isFunc = tag == funcTag; - - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - if (isHostObject(value)) { - return object ? value : {}; - } - result = initCloneObject(isFunc ? {} : value); - if (!isDeep) { - return baseAssign(result, value); - } - } else { - return cloneableTags[tag] - ? initCloneByTag(value, tag, isDeep) - : (object ? value : {}); - } - } - // Check for circular references and return its corresponding clone. - stackA || (stackA = []); - stackB || (stackB = []); - - var length = stackA.length; - while (length--) { - if (stackA[length] == value) { - return stackB[length]; - } - } - // Add the source value to the stack of traversed objects and associate it with its clone. - stackA.push(value); - stackB.push(result); - - // Recursively populate clone (susceptible to call stack limits). - (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { - result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); - }); - return result; -} - -module.exports = baseClone; - -},{"../lang/isArray":140,"../lang/isObject":144,"./arrayCopy":62,"./arrayEach":63,"./baseAssign":66,"./baseForOwn":76,"./initCloneArray":116,"./initCloneByTag":117,"./initCloneObject":118,"./isHostObject":120}],69:[function(require,module,exports){ -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property names to copy. - * @param {Object} [object={}] The object to copy properties to. - * @returns {Object} Returns `object`. - */ -function baseCopy(source, props, object) { - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - object[key] = source[key]; - } - return object; -} - -module.exports = baseCopy; - -},{}],70:[function(require,module,exports){ -var isObject = require('../lang/isObject'); - -/** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ -var baseCreate = (function() { - function object() {} - return function(prototype) { - if (isObject(prototype)) { - object.prototype = prototype; - var result = new object; - object.prototype = undefined; - } - return result || {}; - }; -}()); - -module.exports = baseCreate; - -},{"../lang/isObject":144}],71:[function(require,module,exports){ -var baseForOwn = require('./baseForOwn'), - createBaseEach = require('./createBaseEach'); - -/** - * The base implementation of `_.forEach` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object|string} Returns `collection`. - */ -var baseEach = createBaseEach(baseForOwn); - -module.exports = baseEach; - -},{"./baseForOwn":76,"./createBaseEach":98}],72:[function(require,module,exports){ -/** - * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, - * without support for callback shorthands and `this` binding, which iterates - * over `collection` using the provided `eachFunc`. - * - * @private - * @param {Array|Object|string} collection The collection to search. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @param {boolean} [retKey] Specify returning the key of the found element - * instead of the element itself. - * @returns {*} Returns the found element or its key, else `undefined`. - */ -function baseFind(collection, predicate, eachFunc, retKey) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = retKey ? key : value; - return false; - } - }); - return result; -} - -module.exports = baseFind; - -},{}],73:[function(require,module,exports){ -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for callback shorthands and `this` binding. - * - * @private - * @param {Array} array The array to search. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -module.exports = baseFindIndex; - -},{}],74:[function(require,module,exports){ -var createBaseFor = require('./createBaseFor'); - -/** - * The base implementation of `baseForIn` and `baseForOwn` which iterates - * over `object` properties returned by `keysFunc` invoking `iteratee` for - * each property. Iteratee functions may exit iteration early by explicitly - * returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); - -module.exports = baseFor; - -},{"./createBaseFor":99}],75:[function(require,module,exports){ -var baseFor = require('./baseFor'), - keysIn = require('../object/keysIn'); - -/** - * The base implementation of `_.forIn` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForIn(object, iteratee) { - return baseFor(object, iteratee, keysIn); -} - -module.exports = baseForIn; - -},{"../object/keysIn":150,"./baseFor":74}],76:[function(require,module,exports){ -var baseFor = require('./baseFor'), - keys = require('../object/keys'); - -/** - * The base implementation of `_.forOwn` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return baseFor(object, iteratee, keys); -} - -module.exports = baseForOwn; - -},{"../object/keys":149,"./baseFor":74}],77:[function(require,module,exports){ -var toObject = require('./toObject'); - -/** - * The base implementation of `get` without support for string paths - * and default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path of the property to get. - * @param {string} [pathKey] The key representation of path. - * @returns {*} Returns the resolved value. - */ -function baseGet(object, path, pathKey) { - if (object == null) { - return; - } - object = toObject(object); - if (pathKey !== undefined && pathKey in object) { - path = [pathKey]; - } - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = toObject(object)[path[index++]]; - } - return (index && index == length) ? object : undefined; -} - -module.exports = baseGet; - -},{"./toObject":135}],78:[function(require,module,exports){ -var indexOfNaN = require('./indexOfNaN'); - -/** - * The base implementation of `_.indexOf` without support for binary searches. - * - * @private - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return indexOfNaN(array, fromIndex); - } - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -module.exports = baseIndexOf; - -},{"./indexOfNaN":115}],79:[function(require,module,exports){ -var baseIsEqualDeep = require('./baseIsEqualDeep'), - isObject = require('../lang/isObject'), - isObjectLike = require('./isObjectLike'); - -/** - * The base implementation of `_.isEqual` without support for `this` binding - * `customizer` functions. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparing values. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ -function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); -} - -module.exports = baseIsEqual; - -},{"../lang/isObject":144,"./baseIsEqualDeep":80,"./isObjectLike":126}],80:[function(require,module,exports){ -var equalArrays = require('./equalArrays'), - equalByTag = require('./equalByTag'), - equalObjects = require('./equalObjects'), - isArray = require('../lang/isArray'), - isHostObject = require('./isHostObject'), - isTypedArray = require('../lang/isTypedArray'); - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - objectTag = '[object Object]'; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing objects. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA=[]] Tracks traversed `value` objects. - * @param {Array} [stackB=[]] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = arrayTag, - othTag = arrayTag; - - if (!objIsArr) { - objTag = objToString.call(object); - if (objTag == argsTag) { - objTag = objectTag; - } else if (objTag != objectTag) { - objIsArr = isTypedArray(object); - } - } - if (!othIsArr) { - othTag = objToString.call(other); - if (othTag == argsTag) { - othTag = objectTag; - } else if (othTag != objectTag) { - othIsArr = isTypedArray(other); - } - } - var objIsObj = objTag == objectTag && !isHostObject(object), - othIsObj = othTag == objectTag && !isHostObject(other), - isSameTag = objTag == othTag; - - if (isSameTag && !(objIsArr || objIsObj)) { - return equalByTag(object, other, objTag); - } - if (!isLoose) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); - } - } - if (!isSameTag) { - return false; - } - // Assume cyclic values are equal. - // For more information on detecting circular references see https://es5.github.io/#JO. - stackA || (stackA = []); - stackB || (stackB = []); - - var length = stackA.length; - while (length--) { - if (stackA[length] == object) { - return stackB[length] == other; - } - } - // Add `object` and `other` to the stack of traversed objects. - stackA.push(object); - stackB.push(other); - - var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); - - stackA.pop(); - stackB.pop(); - - return result; -} - -module.exports = baseIsEqualDeep; - -},{"../lang/isArray":140,"../lang/isTypedArray":147,"./equalArrays":107,"./equalByTag":108,"./equalObjects":109,"./isHostObject":120}],81:[function(require,module,exports){ -var baseIsEqual = require('./baseIsEqual'), - toObject = require('./toObject'); - -/** - * The base implementation of `_.isMatch` without support for callback - * shorthands and `this` binding. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} matchData The propery names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparing objects. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ -function baseIsMatch(object, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = toObject(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var result = customizer ? customizer(objValue, srcValue, key) : undefined; - if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { - return false; - } - } - } - return true; -} - -module.exports = baseIsMatch; - -},{"./baseIsEqual":79,"./toObject":135}],82:[function(require,module,exports){ -/** - * The function whose prototype all chaining wrappers inherit from. - * - * @private - */ -function baseLodash() { - // No operation performed. -} - -module.exports = baseLodash; - -},{}],83:[function(require,module,exports){ -var baseEach = require('./baseEach'), - isArrayLike = require('./isArrayLike'); - -/** - * The base implementation of `_.map` without support for callback shorthands - * and `this` binding. - * - * @private - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; -} - -module.exports = baseMap; - -},{"./baseEach":71,"./isArrayLike":119}],84:[function(require,module,exports){ -var baseIsMatch = require('./baseIsMatch'), - getMatchData = require('./getMatchData'), - toObject = require('./toObject'); - -/** - * The base implementation of `_.matches` which does not clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new function. - */ -function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - var key = matchData[0][0], - value = matchData[0][1]; - - return function(object) { - if (object == null) { - return false; - } - object = toObject(object); - return object[key] === value && (value !== undefined || (key in object)); - }; - } - return function(object) { - return baseIsMatch(object, matchData); - }; -} - -module.exports = baseMatches; - -},{"./baseIsMatch":81,"./getMatchData":113,"./toObject":135}],85:[function(require,module,exports){ -var baseGet = require('./baseGet'), - baseIsEqual = require('./baseIsEqual'), - baseSlice = require('./baseSlice'), - isArray = require('../lang/isArray'), - isKey = require('./isKey'), - isStrictComparable = require('./isStrictComparable'), - last = require('../array/last'), - toObject = require('./toObject'), - toPath = require('./toPath'); - -/** - * The base implementation of `_.matchesProperty` which does not clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to compare. - * @returns {Function} Returns the new function. - */ -function baseMatchesProperty(path, srcValue) { - var isArr = isArray(path), - isCommon = isKey(path) && isStrictComparable(srcValue), - pathKey = (path + ''); - - path = toPath(path); - return function(object) { - if (object == null) { - return false; - } - var key = pathKey; - object = toObject(object); - if ((isArr || !isCommon) && !(key in object)) { - object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); - if (object == null) { - return false; - } - key = last(path); - object = toObject(object); - } - return object[key] === srcValue - ? (srcValue !== undefined || (key in object)) - : baseIsEqual(srcValue, object[key], undefined, true); - }; -} - -module.exports = baseMatchesProperty; - -},{"../array/last":50,"../lang/isArray":140,"./baseGet":77,"./baseIsEqual":79,"./baseSlice":89,"./isKey":123,"./isStrictComparable":127,"./toObject":135,"./toPath":136}],86:[function(require,module,exports){ -var toObject = require('./toObject'); - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : toObject(object)[key]; - }; -} - -module.exports = baseProperty; - -},{"./toObject":135}],87:[function(require,module,exports){ -var baseGet = require('./baseGet'), - toPath = require('./toPath'); - -/** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new function. - */ -function basePropertyDeep(path) { - var pathKey = (path + ''); - path = toPath(path); - return function(object) { - return baseGet(object, path, pathKey); - }; -} - -module.exports = basePropertyDeep; - -},{"./baseGet":77,"./toPath":136}],88:[function(require,module,exports){ -var identity = require('../utility/identity'), - metaMap = require('./metaMap'); - -/** - * The base implementation of `setData` without support for hot loop detection. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ -var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; -}; - -module.exports = baseSetData; - -},{"../utility/identity":154,"./metaMap":129}],89:[function(require,module,exports){ -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - start = start == null ? 0 : (+start || 0); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : (+end || 0); - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -module.exports = baseSlice; - -},{}],90:[function(require,module,exports){ -/** - * Converts `value` to a string if it's not one. An empty string is returned - * for `null` or `undefined` values. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - return value == null ? '' : (value + ''); -} - -module.exports = baseToString; - -},{}],91:[function(require,module,exports){ -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues(object, props) { - var index = -1, - length = props.length, - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; -} - -module.exports = baseValues; - -},{}],92:[function(require,module,exports){ -var binaryIndexBy = require('./binaryIndexBy'), - identity = require('../utility/identity'); - -/** Used as references for the maximum length and index of an array. */ -var MAX_ARRAY_LENGTH = 4294967295, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - -/** - * Performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ -function binaryIndex(array, value, retHighest) { - var low = 0, - high = array ? array.length : low; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return binaryIndexBy(array, value, identity, retHighest); -} - -module.exports = binaryIndex; - -},{"../utility/identity":154,"./binaryIndexBy":93}],93:[function(require,module,exports){ -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeFloor = Math.floor, - nativeMin = Math.min; - -/** Used as references for the maximum length and index of an array. */ -var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1; - -/** - * This function is like `binaryIndex` except that it invokes `iteratee` for - * `value` and each element of `array` to compute their sort ranking. The - * iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The function invoked per iteration. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ -function binaryIndexBy(array, value, iteratee, retHighest) { - value = iteratee(value); - - var low = 0, - high = array ? array.length : 0, - valIsNaN = value !== value, - valIsNull = value === null, - valIsUndef = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - isDef = computed !== undefined, - isReflexive = computed === computed; - - if (valIsNaN) { - var setLow = isReflexive || retHighest; - } else if (valIsNull) { - setLow = isReflexive && isDef && (retHighest || computed != null); - } else if (valIsUndef) { - setLow = isReflexive && (retHighest || isDef); - } else if (computed == null) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); -} - -module.exports = binaryIndexBy; - -},{}],94:[function(require,module,exports){ -var identity = require('../utility/identity'); - -/** - * A specialized version of `baseCallback` which only supports `this` binding - * and specifying the number of arguments to provide to `func`. - * - * @private - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {number} [argCount] The number of arguments to provide to `func`. - * @returns {Function} Returns the callback. - */ -function bindCallback(func, thisArg, argCount) { - if (typeof func != 'function') { - return identity; - } - if (thisArg === undefined) { - return func; - } - switch (argCount) { - case 1: return function(value) { - return func.call(thisArg, value); - }; - case 3: return function(value, index, collection) { - return func.call(thisArg, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - case 5: return function(value, other, key, object, source) { - return func.call(thisArg, value, other, key, object, source); - }; - } - return function() { - return func.apply(thisArg, arguments); - }; -} - -module.exports = bindCallback; - -},{"../utility/identity":154}],95:[function(require,module,exports){ -(function (global){ -/** Native method references. */ -var ArrayBuffer = global.ArrayBuffer, - Uint8Array = global.Uint8Array; - -/** - * Creates a clone of the given array buffer. - * - * @private - * @param {ArrayBuffer} buffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ -function bufferClone(buffer) { - var result = new ArrayBuffer(buffer.byteLength), - view = new Uint8Array(result); - - view.set(new Uint8Array(buffer)); - return result; -} - -module.exports = bufferClone; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],96:[function(require,module,exports){ -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array|Object} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @returns {Array} Returns the new array of composed arguments. - */ -function composeArgs(args, partials, holders) { - var holdersLength = holders.length, - argsIndex = -1, - argsLength = nativeMax(args.length - holdersLength, 0), - leftIndex = -1, - leftLength = partials.length, - result = Array(leftLength + argsLength); - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - while (argsLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; -} - -module.exports = composeArgs; - -},{}],97:[function(require,module,exports){ -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array|Object} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @returns {Array} Returns the new array of composed arguments. - */ -function composeArgsRight(args, partials, holders) { - var holdersIndex = -1, - holdersLength = holders.length, - argsIndex = -1, - argsLength = nativeMax(args.length - holdersLength, 0), - rightIndex = -1, - rightLength = partials.length, - result = Array(argsLength + rightLength); - - while (++argsIndex < argsLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - return result; -} - -module.exports = composeArgsRight; - -},{}],98:[function(require,module,exports){ -var getLength = require('./getLength'), - isLength = require('./isLength'), - toObject = require('./toObject'); - -/** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - var length = collection ? getLength(collection) : 0; - if (!isLength(length)) { - return eachFunc(collection, iteratee); - } - var index = fromRight ? length : -1, - iterable = toObject(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; -} - -module.exports = createBaseEach; - -},{"./getLength":112,"./isLength":125,"./toObject":135}],99:[function(require,module,exports){ -var toObject = require('./toObject'); - -/** - * Creates a base function for `_.forIn` or `_.forInRight`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var iterable = toObject(object), - props = keysFunc(object), - length = props.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length)) { - var key = props[index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} - -module.exports = createBaseFor; - -},{"./toObject":135}],100:[function(require,module,exports){ -(function (global){ -var createCtorWrapper = require('./createCtorWrapper'); - -/** - * Creates a function that wraps `func` and invokes it with the `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to bind. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new bound function. - */ -function createBindWrapper(func, thisArg) { - var Ctor = createCtorWrapper(func); - - function wrapper() { - var fn = (this && this !== global && this instanceof wrapper) ? Ctor : func; - return fn.apply(thisArg, arguments); - } - return wrapper; -} - -module.exports = createBindWrapper; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./createCtorWrapper":101}],101:[function(require,module,exports){ -var baseCreate = require('./baseCreate'), - isObject = require('../lang/isObject'); - -/** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ -function createCtorWrapper(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. - // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; -} - -module.exports = createCtorWrapper; - -},{"../lang/isObject":144,"./baseCreate":70}],102:[function(require,module,exports){ -var baseCallback = require('./baseCallback'), - baseFind = require('./baseFind'), - baseFindIndex = require('./baseFindIndex'), - isArray = require('../lang/isArray'); - -/** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new find function. - */ -function createFind(eachFunc, fromRight) { - return function(collection, predicate, thisArg) { - predicate = baseCallback(predicate, thisArg, 3); - if (isArray(collection)) { - var index = baseFindIndex(collection, predicate, fromRight); - return index > -1 ? collection[index] : undefined; - } - return baseFind(collection, predicate, eachFunc); - }; -} - -module.exports = createFind; - -},{"../lang/isArray":140,"./baseCallback":67,"./baseFind":72,"./baseFindIndex":73}],103:[function(require,module,exports){ -var bindCallback = require('./bindCallback'), - isArray = require('../lang/isArray'); - -/** - * Creates a function for `_.forEach` or `_.forEachRight`. - * - * @private - * @param {Function} arrayFunc The function to iterate over an array. - * @param {Function} eachFunc The function to iterate over a collection. - * @returns {Function} Returns the new each function. - */ -function createForEach(arrayFunc, eachFunc) { - return function(collection, iteratee, thisArg) { - return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) - ? arrayFunc(collection, iteratee) - : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); - }; -} - -module.exports = createForEach; - -},{"../lang/isArray":140,"./bindCallback":94}],104:[function(require,module,exports){ -(function (global){ -var arrayCopy = require('./arrayCopy'), - composeArgs = require('./composeArgs'), - composeArgsRight = require('./composeArgsRight'), - createCtorWrapper = require('./createCtorWrapper'), - isLaziable = require('./isLaziable'), - reorder = require('./reorder'), - replaceHolders = require('./replaceHolders'), - setData = require('./setData'); - -/** Used to compose bitmasks for wrapper metadata. */ -var BIND_FLAG = 1, - BIND_KEY_FLAG = 2, - CURRY_BOUND_FLAG = 4, - CURRY_FLAG = 8, - CURRY_RIGHT_FLAG = 16, - PARTIAL_FLAG = 32, - PARTIAL_RIGHT_FLAG = 64, - ARY_FLAG = 128; - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Creates a function that wraps `func` and invokes it with optional `this` - * binding of, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ -function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & ARY_FLAG, - isBind = bitmask & BIND_FLAG, - isBindKey = bitmask & BIND_KEY_FLAG, - isCurry = bitmask & CURRY_FLAG, - isCurryBound = bitmask & CURRY_BOUND_FLAG, - isCurryRight = bitmask & CURRY_RIGHT_FLAG, - Ctor = isBindKey ? undefined : createCtorWrapper(func); - - function wrapper() { - // Avoid `arguments` object use disqualifying optimizations by - // converting it to an array before providing it to other functions. - var length = arguments.length, - index = length, - args = Array(length); - - while (index--) { - args[index] = arguments[index]; - } - if (partials) { - args = composeArgs(args, partials, holders); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight); - } - if (isCurry || isCurryRight) { - var placeholder = wrapper.placeholder, - argsHolders = replaceHolders(args, placeholder); - - length -= argsHolders.length; - if (length < arity) { - var newArgPos = argPos ? arrayCopy(argPos) : undefined, - newArity = nativeMax(arity - length, 0), - newsHolders = isCurry ? argsHolders : undefined, - newHoldersRight = isCurry ? undefined : argsHolders, - newPartials = isCurry ? args : undefined, - newPartialsRight = isCurry ? undefined : args; - - bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); - - if (!isCurryBound) { - bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); - } - var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity], - result = createHybridWrapper.apply(undefined, newData); - - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return result; - } - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - if (argPos) { - args = reorder(args, argPos); - } - if (isAry && ary < args.length) { - args.length = ary; - } - if (this && this !== global && this instanceof wrapper) { - fn = Ctor || createCtorWrapper(func); - } - return fn.apply(thisBinding, args); - } - return wrapper; -} - -module.exports = createHybridWrapper; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./arrayCopy":62,"./composeArgs":96,"./composeArgsRight":97,"./createCtorWrapper":101,"./isLaziable":124,"./reorder":131,"./replaceHolders":132,"./setData":133}],105:[function(require,module,exports){ -(function (global){ -var createCtorWrapper = require('./createCtorWrapper'); - -/** Used to compose bitmasks for wrapper metadata. */ -var BIND_FLAG = 1; - -/** - * Creates a function that wraps `func` and invokes it with the optional `this` - * binding of `thisArg` and the `partials` prepended to those provided to - * the wrapper. - * - * @private - * @param {Function} func The function to partially apply arguments to. - * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to the new function. - * @returns {Function} Returns the new bound function. - */ -function createPartialWrapper(func, bitmask, thisArg, partials) { - var isBind = bitmask & BIND_FLAG, - Ctor = createCtorWrapper(func); - - function wrapper() { - // Avoid `arguments` object use disqualifying optimizations by - // converting it to an array before providing it `func`. - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength); - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - var fn = (this && this !== global && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, args); - } - return wrapper; -} - -module.exports = createPartialWrapper; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./createCtorWrapper":101}],106:[function(require,module,exports){ -var baseSetData = require('./baseSetData'), - createBindWrapper = require('./createBindWrapper'), - createHybridWrapper = require('./createHybridWrapper'), - createPartialWrapper = require('./createPartialWrapper'), - getData = require('./getData'), - mergeData = require('./mergeData'), - setData = require('./setData'); - -/** Used to compose bitmasks for wrapper metadata. */ -var BIND_FLAG = 1, - BIND_KEY_FLAG = 2, - PARTIAL_FLAG = 32, - PARTIAL_RIGHT_FLAG = 64; - -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of flags. - * The bitmask may be composed of the following flags: - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ -function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - length -= (holders ? holders.length : 0); - if (bitmask & PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func), - newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; - - if (data) { - mergeData(newData, data); - bitmask = newData[1]; - arity = newData[9]; - } - newData[9] = arity == null - ? (isBindKey ? 0 : func.length) - : (nativeMax(arity - length, 0) || 0); - - if (bitmask == BIND_FLAG) { - var result = createBindWrapper(newData[0], newData[2]); - } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { - result = createPartialWrapper.apply(undefined, newData); - } else { - result = createHybridWrapper.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setter(result, newData); -} - -module.exports = createWrapper; - -},{"./baseSetData":88,"./createBindWrapper":100,"./createHybridWrapper":104,"./createPartialWrapper":105,"./getData":110,"./mergeData":128,"./setData":133}],107:[function(require,module,exports){ -var arraySome = require('./arraySome'); - -/** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing arrays. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ -function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { - var index = -1, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isLoose && othLength > arrLength)) { - return false; - } - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index], - result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; - - if (result !== undefined) { - if (result) { - continue; - } - return false; - } - // Recursively compare arrays (susceptible to call stack limits). - if (isLoose) { - if (!arraySome(other, function(othValue) { - return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); - })) { - return false; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { - return false; - } - } - return true; -} - -module.exports = equalArrays; - -},{"./arraySome":65}],108:[function(require,module,exports){ -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - numberTag = '[object Number]', - regexpTag = '[object RegExp]', - stringTag = '[object String]'; - -/** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalByTag(object, other, tag) { - switch (tag) { - case boolTag: - case dateTag: - // Coerce dates and booleans to numbers, dates to milliseconds and booleans - // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. - return +object == +other; - - case errorTag: - return object.name == other.name && object.message == other.message; - - case numberTag: - // Treat `NaN` vs. `NaN` as equal. - return (object != +object) - ? other != +other - : object == +other; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings primitives and string - // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. - return object == (other + ''); - } - return false; -} - -module.exports = equalByTag; - -},{}],109:[function(require,module,exports){ -var keys = require('../object/keys'); - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Function} [customizer] The function to customize comparing values. - * @param {boolean} [isLoose] Specify performing partial comparisons. - * @param {Array} [stackA] Tracks traversed `value` objects. - * @param {Array} [stackB] Tracks traversed `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { - var objProps = keys(object), - objLength = objProps.length, - othProps = keys(other), - othLength = othProps.length; - - if (objLength != othLength && !isLoose) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var skipCtor = isLoose; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key], - result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; - - // Recursively compare objects (susceptible to call stack limits). - if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { - return false; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (!skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - return false; - } - } - return true; -} - -module.exports = equalObjects; - -},{"../object/keys":149}],110:[function(require,module,exports){ -var metaMap = require('./metaMap'), - noop = require('../utility/noop'); - -/** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ -var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); -}; - -module.exports = getData; - -},{"../utility/noop":155,"./metaMap":129}],111:[function(require,module,exports){ -var realNames = require('./realNames'); - -/** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ -function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = array ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; -} - -module.exports = getFuncName; - -},{"./realNames":130}],112:[function(require,module,exports){ -var baseProperty = require('./baseProperty'); - -/** - * Gets the "length" property value of `object`. - * - * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) - * that affects Safari on at least iOS 8.1-8.3 ARM64. - * - * @private - * @param {Object} object The object to query. - * @returns {*} Returns the "length" value. - */ -var getLength = baseProperty('length'); - -module.exports = getLength; - -},{"./baseProperty":86}],113:[function(require,module,exports){ -var isStrictComparable = require('./isStrictComparable'), - pairs = require('../object/pairs'); - -/** - * Gets the propery names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ -function getMatchData(object) { - var result = pairs(object), - length = result.length; - - while (length--) { - result[length][2] = isStrictComparable(result[length][1]); - } - return result; -} - -module.exports = getMatchData; - -},{"../object/pairs":151,"./isStrictComparable":127}],114:[function(require,module,exports){ -var isNative = require('../lang/isNative'); - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = object == null ? undefined : object[key]; - return isNative(value) ? value : undefined; -} - -module.exports = getNative; - -},{"../lang/isNative":143}],115:[function(require,module,exports){ -/** - * Gets the index at which the first occurrence of `NaN` is found in `array`. - * - * @private - * @param {Array} array The array to search. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched `NaN`, else `-1`. - */ -function indexOfNaN(array, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 0 : -1); - - while ((fromRight ? index-- : ++index < length)) { - var other = array[index]; - if (other !== other) { - return index; - } - } - return -1; -} - -module.exports = indexOfNaN; - -},{}],116:[function(require,module,exports){ -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. - */ -function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); - - // Add array properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; -} - -module.exports = initCloneArray; - -},{}],117:[function(require,module,exports){ -(function (global){ -var bufferClone = require('./bufferClone'); - -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]', - dateTag = '[object Date]', - numberTag = '[object Number]', - regexpTag = '[object RegExp]', - stringTag = '[object String]'; - -var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to match `RegExp` flags from their coerced string values. */ -var reFlags = /\w*$/; - -/** Native method references. */ -var Uint8Array = global.Uint8Array; - -/** Used to lookup a type array constructors by `toStringTag`. */ -var ctorByTag = {}; -ctorByTag[float32Tag] = global.Float32Array; -ctorByTag[float64Tag] = global.Float64Array; -ctorByTag[int8Tag] = global.Int8Array; -ctorByTag[int16Tag] = global.Int16Array; -ctorByTag[int32Tag] = global.Int32Array; -ctorByTag[uint8Tag] = Uint8Array; -ctorByTag[uint8ClampedTag] = global.Uint8ClampedArray; -ctorByTag[uint16Tag] = global.Uint16Array; -ctorByTag[uint32Tag] = global.Uint32Array; - -/** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return bufferClone(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - // Safari 5 mobile incorrectly has `Object` as the constructor of typed arrays. - if (Ctor instanceof Ctor) { - Ctor = ctorByTag[tag]; - } - var buffer = object.buffer; - return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - var result = new Ctor(object.source, reFlags.exec(object)); - result.lastIndex = object.lastIndex; - } - return result; -} - -module.exports = initCloneByTag; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./bufferClone":95}],118:[function(require,module,exports){ -/** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ -function initCloneObject(object) { - var Ctor = object.constructor; - if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { - Ctor = Object; - } - return new Ctor; -} - -module.exports = initCloneObject; - -},{}],119:[function(require,module,exports){ -var getLength = require('./getLength'), - isLength = require('./isLength'); - -/** - * Checks if `value` is array-like. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - */ -function isArrayLike(value) { - return value != null && isLength(getLength(value)); -} - -module.exports = isArrayLike; - -},{"./getLength":112,"./isLength":125}],120:[function(require,module,exports){ -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -var isHostObject = (function() { - try { - Object({ 'toString': 0 } + ''); - } catch(e) { - return function() { return false; }; - } - return function(value) { - // IE < 9 presents many host objects as `Object` objects that can coerce - // to strings despite having improperly defined `toString` methods. - return typeof value.toString != 'function' && typeof (value + '') == 'string'; - }; -}()); - -module.exports = isHostObject; - -},{}],121:[function(require,module,exports){ -/** Used to detect unsigned integer values. */ -var reIsUint = /^\d+$/; - -/** - * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) - * of an array-like value. - */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; - length = length == null ? MAX_SAFE_INTEGER : length; - return value > -1 && value % 1 == 0 && value < length; -} - -module.exports = isIndex; - -},{}],122:[function(require,module,exports){ -var isArrayLike = require('./isArrayLike'), - isIndex = require('./isIndex'), - isObject = require('../lang/isObject'); - -/** - * Checks if the provided arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object)) { - var other = object[index]; - return value === value ? (value === other) : (other !== other); - } - return false; -} - -module.exports = isIterateeCall; - -},{"../lang/isObject":144,"./isArrayLike":119,"./isIndex":121}],123:[function(require,module,exports){ -var isArray = require('../lang/isArray'), - toObject = require('./toObject'); - -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey(value, object) { - var type = typeof value; - if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { - return true; - } - if (isArray(value)) { - return false; - } - var result = !reIsDeepProp.test(value); - return result || (object != null && value in toObject(object)); -} - -module.exports = isKey; - -},{"../lang/isArray":140,"./toObject":135}],124:[function(require,module,exports){ -var LazyWrapper = require('./LazyWrapper'), - getData = require('./getData'), - getFuncName = require('./getFuncName'), - lodash = require('../chain/lodash'); - -/** - * Checks if `func` has a lazy counterpart. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`. - */ -function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; - - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; -} - -module.exports = isLaziable; - -},{"../chain/lodash":51,"./LazyWrapper":60,"./getData":110,"./getFuncName":111}],125:[function(require,module,exports){ -/** - * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) - * of an array-like value. - */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - */ -function isLength(value) { - return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -module.exports = isLength; - -},{}],126:[function(require,module,exports){ -/** - * Checks if `value` is object-like. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -module.exports = isObjectLike; - -},{}],127:[function(require,module,exports){ -var isObject = require('../lang/isObject'); - -/** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ -function isStrictComparable(value) { - return value === value && !isObject(value); -} - -module.exports = isStrictComparable; - -},{"../lang/isObject":144}],128:[function(require,module,exports){ -var arrayCopy = require('./arrayCopy'), - composeArgs = require('./composeArgs'), - composeArgsRight = require('./composeArgsRight'), - replaceHolders = require('./replaceHolders'); - -/** Used to compose bitmasks for wrapper metadata. */ -var BIND_FLAG = 1, - CURRY_BOUND_FLAG = 4, - CURRY_FLAG = 8, - ARY_FLAG = 128, - REARG_FLAG = 256; - -/** Used as the internal argument placeholder. */ -var PLACEHOLDER = '__lodash_placeholder__'; - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMin = Math.min; - -/** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers required to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` - * augment function arguments, making the order in which they are executed important, - * preventing the merging of metadata. However, we make an exception for a safe - * common case where curried functions have `_.ary` and or `_.rearg` applied. - * - * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. - */ -function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < ARY_FLAG; - - var isCombo = - (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) || - (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) || - (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = arrayCopy(value); - } - // Use source `ary` if it's smaller. - if (srcBitmask & ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; - } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; -} - -module.exports = mergeData; - -},{"./arrayCopy":62,"./composeArgs":96,"./composeArgsRight":97,"./replaceHolders":132}],129:[function(require,module,exports){ -(function (global){ -var getNative = require('./getNative'); - -/** Native method references. */ -var WeakMap = getNative(global, 'WeakMap'); - -/** Used to store function metadata. */ -var metaMap = WeakMap && new WeakMap; - -module.exports = metaMap; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./getNative":114}],130:[function(require,module,exports){ -/** Used to lookup unminified function names. */ -var realNames = {}; - -module.exports = realNames; - -},{}],131:[function(require,module,exports){ -var arrayCopy = require('./arrayCopy'), - isIndex = require('./isIndex'); - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeMin = Math.min; - -/** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. - * - * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ -function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = arrayCopy(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; -} - -module.exports = reorder; - -},{"./arrayCopy":62,"./isIndex":121}],132:[function(require,module,exports){ -/** Used as the internal argument placeholder. */ -var PLACEHOLDER = '__lodash_placeholder__'; - -/** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ -function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = -1, - result = []; - - while (++index < length) { - if (array[index] === placeholder) { - array[index] = PLACEHOLDER; - result[++resIndex] = index; - } - } - return result; -} - -module.exports = replaceHolders; - -},{}],133:[function(require,module,exports){ -var baseSetData = require('./baseSetData'), - now = require('../date/now'); - -/** Used to detect when a function becomes hot. */ -var HOT_COUNT = 150, - HOT_SPAN = 16; - -/** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity function - * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) - * for more details. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ -var setData = (function() { - var count = 0, - lastCalled = 0; - - return function(key, value) { - var stamp = now(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return key; - } - } else { - count = 0; - } - return baseSetData(key, value); - }; -}()); - -module.exports = setData; - -},{"../date/now":57,"./baseSetData":88}],134:[function(require,module,exports){ -var isArguments = require('../lang/isArguments'), - isArray = require('../lang/isArray'), - isIndex = require('./isIndex'), - isLength = require('./isLength'), - isString = require('../lang/isString'), - keysIn = require('../object/keysIn'); - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * A fallback implementation of `Object.keys` which creates an array of the - * own enumerable property names of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function shimKeys(object) { - var props = keysIn(object), - propsLength = props.length, - length = propsLength && object.length; - - var allowIndexes = !!length && isLength(length) && - (isArray(object) || isArguments(object) || isString(object)); - - var index = -1, - result = []; - - while (++index < propsLength) { - var key = props[index]; - if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { - result.push(key); - } - } - return result; -} - -module.exports = shimKeys; - -},{"../lang/isArguments":139,"../lang/isArray":140,"../lang/isString":146,"../object/keysIn":150,"./isIndex":121,"./isLength":125}],135:[function(require,module,exports){ -var isObject = require('../lang/isObject'), - isString = require('../lang/isString'), - support = require('../support'); - -/** - * Converts `value` to an object if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Object} Returns the object. - */ -function toObject(value) { - if (support.unindexedChars && isString(value)) { - var index = -1, - length = value.length, - result = Object(value); - - while (++index < length) { - result[index] = value.charAt(index); - } - return result; - } - return isObject(value) ? value : Object(value); -} - -module.exports = toObject; - -},{"../lang/isObject":144,"../lang/isString":146,"../support":153}],136:[function(require,module,exports){ -var baseToString = require('./baseToString'), - isArray = require('../lang/isArray'); - -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; - -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; - -/** - * Converts `value` to property path array if it's not one. - * - * @private - * @param {*} value The value to process. - * @returns {Array} Returns the property path array. - */ -function toPath(value) { - if (isArray(value)) { - return value; - } - var result = []; - baseToString(value).replace(rePropName, function(match, number, quote, string) { - result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -} - -module.exports = toPath; - -},{"../lang/isArray":140,"./baseToString":90}],137:[function(require,module,exports){ -var LazyWrapper = require('./LazyWrapper'), - LodashWrapper = require('./LodashWrapper'), - arrayCopy = require('./arrayCopy'); - -/** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ -function wrapperClone(wrapper) { - return wrapper instanceof LazyWrapper - ? wrapper.clone() - : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); -} - -module.exports = wrapperClone; - -},{"./LazyWrapper":60,"./LodashWrapper":61,"./arrayCopy":62}],138:[function(require,module,exports){ -var baseClone = require('../internal/baseClone'), - bindCallback = require('../internal/bindCallback'); - -/** - * Creates a deep clone of `value`. If `customizer` is provided it's invoked - * to produce the cloned values. If `customizer` returns `undefined` cloning - * is handled by the method instead. The `customizer` is bound to `thisArg` - * and invoked with up to three argument; (value [, index|key, object]). - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). - * The enumerable properties of `arguments` objects and objects created by - * constructors other than `Object` are cloned to plain `Object` objects. An - * empty object is returned for uncloneable values such as functions, DOM nodes, - * Maps, Sets, and WeakMaps. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to deep clone. - * @param {Function} [customizer] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `customizer`. - * @returns {*} Returns the deep cloned value. - * @example - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * var deep = _.cloneDeep(users); - * deep[0] === users[0]; - * // => false - * - * // using a customizer callback - * var el = _.cloneDeep(document.body, function(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * }); - * - * el === document.body - * // => false - * el.nodeName - * // => BODY - * el.childNodes.length; - * // => 20 - */ -function cloneDeep(value, customizer, thisArg) { - return typeof customizer == 'function' - ? baseClone(value, true, bindCallback(customizer, thisArg, 3)) - : baseClone(value, true); -} - -module.exports = cloneDeep; - -},{"../internal/baseClone":68,"../internal/bindCallback":94}],139:[function(require,module,exports){ -var isArrayLike = require('../internal/isArrayLike'), - isObjectLike = require('../internal/isObjectLike'); - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** Native method references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; - -/** - * Checks if `value` is classified as an `arguments` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - return isObjectLike(value) && isArrayLike(value) && - hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); -} - -module.exports = isArguments; - -},{"../internal/isArrayLike":119,"../internal/isObjectLike":126}],140:[function(require,module,exports){ -var getNative = require('../internal/getNative'), - isLength = require('../internal/isLength'), - isObjectLike = require('../internal/isObjectLike'); - -/** `Object#toString` result references. */ -var arrayTag = '[object Array]'; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeIsArray = getNative(Array, 'isArray'); - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(function() { return arguments; }()); - * // => false - */ -var isArray = nativeIsArray || function(value) { - return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; -}; - -module.exports = isArray; - -},{"../internal/getNative":114,"../internal/isLength":125,"../internal/isObjectLike":126}],141:[function(require,module,exports){ -var isArguments = require('./isArguments'), - isArray = require('./isArray'), - isArrayLike = require('../internal/isArrayLike'), - isFunction = require('./isFunction'), - isObjectLike = require('../internal/isObjectLike'), - isString = require('./isString'), - keys = require('../object/keys'); - -/** - * Checks if `value` is empty. A value is considered empty unless it's an - * `arguments` object, array, string, or jQuery-like collection with a length - * greater than `0` or an object with own enumerable properties. - * - * @static - * @memberOf _ - * @category Lang - * @param {Array|Object|string} value The value to inspect. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ -function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) || - (isObjectLike(value) && isFunction(value.splice)))) { - return !value.length; - } - return !keys(value).length; -} - -module.exports = isEmpty; - -},{"../internal/isArrayLike":119,"../internal/isObjectLike":126,"../object/keys":149,"./isArguments":139,"./isArray":140,"./isFunction":142,"./isString":146}],142:[function(require,module,exports){ -var isObject = require('./isObject'); - -/** `Object#toString` result references. */ -var funcTag = '[object Function]'; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in older versions of Chrome and Safari which return 'function' for regexes - // and Safari 8 which returns 'object' for typed array constructors. - return isObject(value) && objToString.call(value) == funcTag; -} - -module.exports = isFunction; - -},{"./isObject":144}],143:[function(require,module,exports){ -var isFunction = require('./isFunction'), - isHostObject = require('../internal/isHostObject'), - isObjectLike = require('../internal/isObjectLike'); - -/** Used to detect host constructors (Safari > 5). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var fnToString = Function.prototype.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); - -/** - * Checks if `value` is a native function. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false - */ -function isNative(value) { - if (value == null) { - return false; - } - if (isFunction(value)) { - return reIsNative.test(fnToString.call(value)); - } - return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); -} - -module.exports = isNative; - -},{"../internal/isHostObject":120,"../internal/isObjectLike":126,"./isFunction":142}],144:[function(require,module,exports){ -/** - * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. - * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(1); - * // => false - */ -function isObject(value) { - // Avoid a V8 JIT bug in Chrome 19-20. - // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} - -module.exports = isObject; - -},{}],145:[function(require,module,exports){ -var baseForIn = require('../internal/baseForIn'), - isArguments = require('./isArguments'), - isHostObject = require('../internal/isHostObject'), - isObjectLike = require('../internal/isObjectLike'), - support = require('../support'); - -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * **Note:** This method assumes objects created by the `Object` constructor - * have no inherited enumerable properties. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - var Ctor; - - // Exit early for non `Object` objects. - if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) || - (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { - return false; - } - // IE < 9 iterates inherited properties before own properties. If the first - // iterated property is an object's own property then there are no inherited - // enumerable properties. - var result; - if (support.ownLast) { - baseForIn(value, function(subValue, key, object) { - result = hasOwnProperty.call(object, key); - return false; - }); - return result !== false; - } - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - baseForIn(value, function(subValue, key) { - result = key; - }); - return result === undefined || hasOwnProperty.call(value, result); -} - -module.exports = isPlainObject; - -},{"../internal/baseForIn":75,"../internal/isHostObject":120,"../internal/isObjectLike":126,"../support":153,"./isArguments":139}],146:[function(require,module,exports){ -var isObjectLike = require('../internal/isObjectLike'); - -/** `Object#toString` result references. */ -var stringTag = '[object String]'; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); -} - -module.exports = isString; - -},{"../internal/isObjectLike":126}],147:[function(require,module,exports){ -var isLength = require('../internal/isLength'), - isObjectLike = require('../internal/isObjectLike'); - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dateTag] = typedArrayTags[errorTag] = -typedArrayTags[funcTag] = typedArrayTags[mapTag] = -typedArrayTags[numberTag] = typedArrayTags[objectTag] = -typedArrayTags[regexpTag] = typedArrayTags[setTag] = -typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - -/** Used for native method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -function isTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; -} - -module.exports = isTypedArray; - -},{"../internal/isLength":125,"../internal/isObjectLike":126}],148:[function(require,module,exports){ -/** - * Checks if `value` is `undefined`. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - * - * _.isUndefined(null); - * // => false - */ -function isUndefined(value) { - return value === undefined; -} - -module.exports = isUndefined; - -},{}],149:[function(require,module,exports){ -var getNative = require('../internal/getNative'), - isArrayLike = require('../internal/isArrayLike'), - isObject = require('../lang/isObject'), - shimKeys = require('../internal/shimKeys'), - support = require('../support'); - -/* Native method references for those with the same name as other `lodash` methods. */ -var nativeKeys = getNative(Object, 'keys'); - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) - * for more details. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -var keys = !nativeKeys ? shimKeys : function(object) { - var Ctor = object == null ? undefined : object.constructor; - if ((typeof Ctor == 'function' && Ctor.prototype === object) || - (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { - return shimKeys(object); - } - return isObject(object) ? nativeKeys(object) : []; -}; - -module.exports = keys; - -},{"../internal/getNative":114,"../internal/isArrayLike":119,"../internal/shimKeys":134,"../lang/isObject":144,"../support":153}],150:[function(require,module,exports){ -var arrayEach = require('../internal/arrayEach'), - isArguments = require('../lang/isArguments'), - isArray = require('../lang/isArray'), - isFunction = require('../lang/isFunction'), - isIndex = require('../internal/isIndex'), - isLength = require('../internal/isLength'), - isObject = require('../lang/isObject'), - isString = require('../lang/isString'), - support = require('../support'); - -/** `Object#toString` result references. */ -var arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag = '[object Function]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - stringTag = '[object String]'; - -/** Used to fix the JScript `[[DontEnum]]` bug. */ -var shadowProps = [ - 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', - 'toLocaleString', 'toString', 'valueOf' -]; - -/** Used for native method references. */ -var errorProto = Error.prototype, - objectProto = Object.prototype, - stringProto = String.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objToString = objectProto.toString; - -/** Used to avoid iterating over non-enumerable properties in IE < 9. */ -var nonEnumProps = {}; -nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; -nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; -nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; -nonEnumProps[objectTag] = { 'constructor': true }; - -arrayEach(shadowProps, function(key) { - for (var tag in nonEnumProps) { - if (hasOwnProperty.call(nonEnumProps, tag)) { - var props = nonEnumProps[tag]; - props[key] = hasOwnProperty.call(props, key); - } - } -}); - -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - if (object == null) { - return []; - } - if (!isObject(object)) { - object = Object(object); - } - var length = object.length; - - length = (length && isLength(length) && - (isArray(object) || isArguments(object) || isString(object)) && length) || 0; - - var Ctor = object.constructor, - index = -1, - proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, - isProto = proto === object, - result = Array(length), - skipIndexes = length > 0, - skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), - skipProto = support.enumPrototypes && isFunction(object); - - while (++index < length) { - result[index] = (index + ''); - } - // lodash skips the `constructor` property when it infers it's iterating - // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` - // attribute of an existing property and the `constructor` property of a - // prototype defaults to non-enumerable. - for (var key in object) { - if (!(skipProto && key == 'prototype') && - !(skipErrorProps && (key == 'message' || key == 'name')) && - !(skipIndexes && isIndex(key, length)) && - !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - if (support.nonEnumShadows && object !== objectProto) { - var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), - nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; - - if (tag == objectTag) { - proto = objectProto; - } - length = shadowProps.length; - while (length--) { - key = shadowProps[length]; - var nonEnum = nonEnums[key]; - if (!(isProto && nonEnum) && - (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { - result.push(key); - } - } - } - return result; -} - -module.exports = keysIn; - -},{"../internal/arrayEach":63,"../internal/isIndex":121,"../internal/isLength":125,"../lang/isArguments":139,"../lang/isArray":140,"../lang/isFunction":142,"../lang/isObject":144,"../lang/isString":146,"../support":153}],151:[function(require,module,exports){ -var keys = require('./keys'), - toObject = require('../internal/toObject'); - -/** - * Creates a two dimensional array of the key-value pairs for `object`, - * e.g. `[[key1, value1], [key2, value2]]`. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the new array of key-value pairs. - * @example - * - * _.pairs({ 'barney': 36, 'fred': 40 }); - * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) - */ -function pairs(object) { - object = toObject(object); - - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - var key = props[index]; - result[index] = [key, object[key]]; - } - return result; -} - -module.exports = pairs; - -},{"../internal/toObject":135,"./keys":149}],152:[function(require,module,exports){ -var baseValues = require('../internal/baseValues'), - keys = require('./keys'); - -/** - * Creates an array of the own enumerable property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values(object) { - return baseValues(object, keys(object)); -} - -module.exports = values; - -},{"../internal/baseValues":91,"./keys":149}],153:[function(require,module,exports){ -/** Used for native method references. */ -var arrayProto = Array.prototype, - errorProto = Error.prototype, - objectProto = Object.prototype; - -/** Native method references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice; - -/** - * An object environment feature flags. - * - * @static - * @memberOf _ - * @type Object - */ -var support = {}; - -(function(x) { - var Ctor = function() { this.x = x; }, - object = { '0': x, 'length': x }, - props = []; - - Ctor.prototype = { 'valueOf': x, 'y': x }; - for (var key in new Ctor) { props.push(key); } - - /** - * Detect if `name` or `message` properties of `Error.prototype` are - * enumerable by default (IE < 9, Safari < 5.1). - * - * @memberOf _.support - * @type boolean - */ - support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || - propertyIsEnumerable.call(errorProto, 'name'); - - /** - * Detect if `prototype` properties are enumerable by default. - * - * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 - * (if the prototype or a property on the prototype has been set) - * incorrectly set the `[[Enumerable]]` value of a function's `prototype` - * property to `true`. - * - * @memberOf _.support - * @type boolean - */ - support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); - - /** - * Detect if properties shadowing those on `Object.prototype` are non-enumerable. - * - * In IE < 9 an object's own properties, shadowing non-enumerable ones, - * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). - * - * @memberOf _.support - * @type boolean - */ - support.nonEnumShadows = !/valueOf/.test(props); - - /** - * Detect if own properties are iterated after inherited properties (IE < 9). - * - * @memberOf _.support - * @type boolean - */ - support.ownLast = props[0] != 'x'; - - /** - * Detect if `Array#shift` and `Array#splice` augment array-like objects - * correctly. - * - * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array - * `shift()` and `splice()` functions that fail to remove the last element, - * `value[0]`, of array-like objects even though the "length" property is - * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, - * while `splice()` is buggy regardless of mode in IE < 9. - * - * @memberOf _.support - * @type boolean - */ - support.spliceObjects = (splice.call(object, 0, 1), !object[0]); - - /** - * Detect lack of support for accessing string characters by index. - * - * IE < 8 can't access characters by index. IE 8 can only access characters - * by index on string literals, not string objects. - * - * @memberOf _.support - * @type boolean - */ - support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; -}(1, 0)); - -module.exports = support; - -},{}],154:[function(require,module,exports){ -/** - * This method returns the first argument provided to it. - * - * @static - * @memberOf _ - * @category Utility - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'user': 'fred' }; - * - * _.identity(object) === object; - * // => true - */ -function identity(value) { - return value; -} - -module.exports = identity; - -},{}],155:[function(require,module,exports){ -/** - * A no-operation function that returns `undefined` regardless of the - * arguments it receives. - * - * @static - * @memberOf _ - * @category Utility - * @example - * - * var object = { 'user': 'fred' }; - * - * _.noop(object) === undefined; - * // => true - */ -function noop() { - // No operation performed. -} - -module.exports = noop; - -},{}],156:[function(require,module,exports){ -var baseProperty = require('../internal/baseProperty'), - basePropertyDeep = require('../internal/basePropertyDeep'), - isKey = require('../internal/isKey'); - -/** - * Creates a function that returns the property value at `path` on a - * given object. - * - * @static - * @memberOf _ - * @category Utility - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new function. - * @example - * - * var objects = [ - * { 'a': { 'b': { 'c': 2 } } }, - * { 'a': { 'b': { 'c': 1 } } } - * ]; - * - * _.map(objects, _.property('a.b.c')); - * // => [2, 1] - * - * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); - * // => [1, 2] - */ -function property(path) { - return isKey(path) ? baseProperty(path) : basePropertyDeep(path); -} - -module.exports = property; - -},{"../internal/baseProperty":86,"../internal/basePropertyDeep":87,"../internal/isKey":123}],157:[function(require,module,exports){ -(function (process){ -// vim:ts=4:sts=4:sw=4: -/*! - * - * Copyright 2009-2012 Kris Kowal under the terms of the MIT - * license found at http://github.com/kriskowal/q/raw/master/LICENSE - * - * With parts by Tyler Close - * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found - * at http://www.opensource.org/licenses/mit-license.html - * Forked at ref_send.js version: 2009-05-11 - * - * With parts by Mark Miller - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -(function (definition) { - "use strict"; - - // This file will function properly as a - priceBoxes.priceBox({ - 'priceConfig': { - priceFormat: jsonConfig.priceFormat, - prices: jsonConfig.prices + diff --git a/app/code/Magento/Swatches/view/frontend/templates/product/view/renderer.phtml b/app/code/Magento/Swatches/view/frontend/templates/product/view/renderer.phtml index fc1de530a66bd..ea166b9080f5c 100644 --- a/app/code/Magento/Swatches/view/frontend/templates/product/view/renderer.phtml +++ b/app/code/Magento/Swatches/view/frontend/templates/product/view/renderer.phtml @@ -14,11 +14,13 @@ "[data-role=swatch-options]": { "Magento_Swatches/js/swatch-renderer": { "jsonConfig": getJsonConfig() ?>, - "jsonSwatchConfig": getJsonSwatchConfig(); ?>, + "jsonSwatchConfig": getJsonSwatchConfig(); ?>, "mediaCallback": "getMediaCallback() ?>", "gallerySwitchStrategy": "getVar('gallery_switch_strategy', 'Magento_ConfigurableProduct') ?: 'replace'; ?>" + }, + "Magento_Swatches/js/configurable-customer-data": { + "swatchOptions": } } } diff --git a/app/code/Magento/Swatches/view/frontend/web/js/configurable-customer-data.js b/app/code/Magento/Swatches/view/frontend/web/js/configurable-customer-data.js index 6467c6276da58..8cea83c1bd551 100644 --- a/app/code/Magento/Swatches/view/frontend/web/js/configurable-customer-data.js +++ b/app/code/Magento/Swatches/view/frontend/web/js/configurable-customer-data.js @@ -1,28 +1,51 @@ -require([ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +define([ 'jquery', - 'Magento_ConfigurableProduct/js/options-updater' + 'Magento_ConfigurableProduct/js/options-updater', + 'jquery/ui' ], function ($, Updater) { 'use strict'; - var selectors = { - formSelector: '#product_addtocart_form', - swatchSelector: '.swatch-opt' + $.widget('mage.selectSwatch', { + options: { + swatchOptions: null, + selectors: { + formSelector: '#product_addtocart_form', + swatchSelector: '.swatch-opt' + }, + swatchWidgetName: 'mageSwatchRenderer', + widgetInitEvent: 'swatch.initialized', + clickEventName: 'emulateClick' }, - swatchWidgetName = 'mageSwatchRenderer', - widgetInitEvent = 'swatch.initialized', - /** - * Sets all configurable swatch attribute's selected values - */ - updateSwatchOptions = function () { - var swatchWidget = $(selectors.swatchSelector).data(swatchWidgetName); + /** + * Widget initialisation. + * Configurable product options updater listens to selected swatch options + */ + _init: function () { + var updater; - if (!swatchWidget || !swatchWidget._EmulateSelectedByAttributeId) { - return; + updater = new Updater(this.options.widgetInitEvent, this.selectDefaultSwatchOptions.bind(this)); + updater.listen(); + }, + + /** + * Sets default configurable swatch attribute's selected + */ + selectDefaultSwatchOptions: function () { + var swatchWidget = $(this.options.selectors.swatchSelector).data(this.options.swatchWidgetName); + + if (!swatchWidget || !swatchWidget._EmulateSelectedByAttributeId) { + return; + } + swatchWidget._EmulateSelectedByAttributeId( + this.options.swatchOptions.defaultValues, this.options.clickEventName + ); } - swatchWidget._EmulateSelectedByAttributeId(this.productOptions); - }, - updater = new Updater(widgetInitEvent, updateSwatchOptions); + }); - updater.listen(); + return $.mage.selectSwatch; }); diff --git a/app/code/Magento/Swatches/view/frontend/web/js/swatch-renderer.js b/app/code/Magento/Swatches/view/frontend/web/js/swatch-renderer.js index d1f7c477ba8d7..2c4058e243efe 100644 --- a/app/code/Magento/Swatches/view/frontend/web/js/swatch-renderer.js +++ b/app/code/Magento/Swatches/view/frontend/web/js/swatch-renderer.js @@ -268,8 +268,11 @@ define([ // tier prise selectors start tierPriceTemplateSelector: '#tier-prices-template', tierPriceBlockSelector: '[data-role="tier-price-block"]', - tierPriceTemplate: '' + tierPriceTemplate: '', // tier prise selectors end + + // A price label selector + normalPriceLabelSelector: '.normal-price .price-label' }, /** @@ -312,7 +315,7 @@ define([ */ _sortAttributes: function () { this.options.jsonConfig.attributes = _.sortBy(this.options.jsonConfig.attributes, function (attribute) { - return attribute.position; + return parseInt(attribute.position, 10); }); }, @@ -616,6 +619,10 @@ define([ return $widget._OnClick($(this), $widget); }); + $widget.element.on('emulateClick', '.' + options.optionClass, function () { + return $widget._OnClick($(this), $widget, 'emulateClick'); + }); + $widget.element.on('change', '.' + options.selectClass, function () { return $widget._OnChange($(this), $widget); }); @@ -646,9 +653,10 @@ define([ /** * Load media gallery using ajax or json config. * + * @param {String|undefined} eventName * @private */ - _loadMedia: function () { + _loadMedia: function (eventName) { var $main = this.inProductList ? this.element.parents('.product-item-info') : this.element.parents('.column.main'), @@ -663,7 +671,7 @@ define([ images = this.options.mediaGalleryInitial; } - this.updateBaseImage(images, $main, !this.inProductList); + this.updateBaseImage(images, $main, !this.inProductList, eventName); } }, @@ -672,9 +680,10 @@ define([ * * @param {Object} $this * @param {Object} $widget + * @param {String|undefined} eventName * @private */ - _OnClick: function ($this, $widget) { + _OnClick: function ($this, $widget, eventName) { var $parent = $this.parents('.' + $widget.options.classes.attributeClass), $wrapper = $this.parents('.' + $widget.options.classes.attributeOptionsWrapper), $label = $parent.find('.' + $widget.options.classes.attributeSelectedOptionLabelClass), @@ -713,7 +722,7 @@ define([ $widget._UpdatePrice(); } - $widget._loadMedia(); + $widget._loadMedia(eventName); $input.trigger('change'); }, @@ -924,6 +933,22 @@ define([ } else { $(this.options.tierPriceBlockSelector).hide(); } + + $(this.options.normalPriceLabelSelector).hide(); + + _.each($('.' + this.options.classes.attributeOptionsWrapper), function (attribute) { + if ($(attribute).find('.' + this.options.classes.optionClass + '.selected').length === 0) { + if ($(attribute).find('.' + this.options.classes.selectClass).length > 0) { + _.each($(attribute).find('.' + this.options.classes.selectClass), function (dropdown) { + if ($(dropdown).val() === '0') { + $(this.options.normalPriceLabelSelector).show(); + } + }.bind(this)); + } else { + $(this.options.normalPriceLabelSelector).show(); + } + } + }.bind(this)); }, /** @@ -1117,16 +1142,36 @@ define([ return images; }, + /** + * Start update base image process based on event name + * @param {Array} images + * @param {jQuery} context + * @param {Boolean} isInProductView + * @param {String|undefined} eventName + */ + updateBaseImage: function (images, context, isInProductView, eventName) { + var gallery = context.find(this.options.mediaGallerySelector).data('gallery'); + + if (eventName === undefined) { + this.processUpdateBaseImage(images, context, isInProductView, gallery); + } else { + context.find(this.options.mediaGallerySelector).on('gallery:loaded', function (loadedGallery) { + loadedGallery = context.find(this.options.mediaGallerySelector).data('gallery'); + this.processUpdateBaseImage(images, context, isInProductView, loadedGallery); + }.bind(this)); + } + }, + /** * Update [gallery-placeholder] or [product-image-photo] * @param {Array} images * @param {jQuery} context * @param {Boolean} isInProductView + * @param {Object} gallery */ - updateBaseImage: function (images, context, isInProductView) { + processUpdateBaseImage: function (images, context, isInProductView, gallery) { var justAnImage = images[0], initialImages = this.options.mediaGalleryInitial, - gallery = context.find(this.options.mediaGallerySelector).data('gallery'), imagesToUpdate, isInitial; @@ -1203,14 +1248,19 @@ define([ /** * Emulate mouse click or selection change on all swatches that should be selected * @param {Object} [selectedAttributes] + * @param {String} triggerClick * @private */ - _EmulateSelectedByAttributeId: function (selectedAttributes) { + _EmulateSelectedByAttributeId: function (selectedAttributes, triggerClick) { $.each(selectedAttributes, $.proxy(function (attributeId, optionId) { var elem = this.element.find('.' + this.options.classes.attributeClass + '[attribute-id="' + attributeId + '"] [option-id="' + optionId + '"]'), parentInput = elem.parent(); + if (triggerClick === null || triggerClick === '') { + triggerClick = 'click'; + } + if (elem.hasClass('selected')) { return; } @@ -1219,7 +1269,7 @@ define([ parentInput.val(optionId); parentInput.trigger('change'); } else { - elem.trigger('click'); + elem.trigger(triggerClick); } }, this)); }, diff --git a/app/code/Magento/SwatchesLayeredNavigation/composer.json b/app/code/Magento/SwatchesLayeredNavigation/composer.json index fabf559c401b9..c7bec15094136 100644 --- a/app/code/Magento/SwatchesLayeredNavigation/composer.json +++ b/app/code/Magento/SwatchesLayeredNavigation/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-swatches-layered-navigation", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/framework": "101.0.*", "magento/magento-composer-installer": "*" }, diff --git a/app/code/Magento/Tax/Block/Adminhtml/Rate/Toolbar/Add.php b/app/code/Magento/Tax/Block/Adminhtml/Rate/Toolbar/Add.php index 80cc9673a0d38..9cf96bc21e962 100644 --- a/app/code/Magento/Tax/Block/Adminhtml/Rate/Toolbar/Add.php +++ b/app/code/Magento/Tax/Block/Adminhtml/Rate/Toolbar/Add.php @@ -11,8 +11,6 @@ */ namespace Magento\Tax\Block\Adminhtml\Rate\Toolbar; -use Magento\Framework\View\Element\Template; - /** * @api * @since 100.0.2 diff --git a/app/code/Magento/Tax/Block/Grid/Renderer/Codes.php b/app/code/Magento/Tax/Block/Grid/Renderer/Codes.php index c4ed80c522c6e..0c394ff090bf1 100644 --- a/app/code/Magento/Tax/Block/Grid/Renderer/Codes.php +++ b/app/code/Magento/Tax/Block/Grid/Renderer/Codes.php @@ -18,8 +18,12 @@ class Codes extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractR */ public function render(\Magento\Framework\DataObject $row) { - $ratesCodes = $row->getTaxRatesCodes(); - - return is_array($ratesCodes) ? implode(', ', $ratesCodes) : ''; + /** @var string[]|null $ratesCodes */ + $ratesCodes = $row['tax_rates_codes']; + if ($ratesCodes) { + return $this->escapeHtml(implode(', ', $ratesCodes)); + } else { + return ''; + } } } diff --git a/app/code/Magento/Tax/Controller/Adminhtml/Tax/IgnoreTaxNotification.php b/app/code/Magento/Tax/Controller/Adminhtml/Tax/IgnoreTaxNotification.php index 847f1312e8caf..b623b6c6868e7 100644 --- a/app/code/Magento/Tax/Controller/Adminhtml/Tax/IgnoreTaxNotification.php +++ b/app/code/Magento/Tax/Controller/Adminhtml/Tax/IgnoreTaxNotification.php @@ -51,8 +51,8 @@ public function execute() } // clear the block html cache - $this->_cacheTypeList->cleanType('block_html'); - $this->_eventManager->dispatch('adminhtml_cache_refresh_type', ['type' => 'block_html']); + $this->_cacheTypeList->cleanType('config'); + $this->_eventManager->dispatch('adminhtml_cache_refresh_type', ['type' => 'config']); /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); diff --git a/app/code/Magento/Tax/Helper/Data.php b/app/code/Magento/Tax/Helper/Data.php index f77ecc956f26d..9d31368106924 100644 --- a/app/code/Magento/Tax/Helper/Data.php +++ b/app/code/Magento/Tax/Helper/Data.php @@ -9,7 +9,6 @@ use Magento\Store\Model\Store; use Magento\Customer\Model\Address; use Magento\Tax\Model\Config; -use Magento\Customer\Model\Session as CustomerSession; use Magento\Tax\Api\OrderTaxManagementInterface; use Magento\Sales\Model\Order\Invoice; use Magento\Sales\Model\Order\Creditmemo; diff --git a/app/code/Magento/Tax/Model/Calculation/Rate.php b/app/code/Magento/Tax/Model/Calculation/Rate.php index f639d6680a7fc..9e44cd113ddea 100644 --- a/app/code/Magento/Tax/Model/Calculation/Rate.php +++ b/app/code/Magento/Tax/Model/Calculation/Rate.php @@ -227,7 +227,7 @@ public function afterDelete() */ public function saveTitles($titles = null) { - if (is_null($titles)) { + if ($titles === null) { $titles = $this->getTitle(); } @@ -256,7 +256,7 @@ public function saveTitles($titles = null) */ public function getTitleModel() { - if (is_null($this->_titleModel)) { + if ($this->_titleModel === null) { $this->_titleModel = $this->_titleFactory->create(); } return $this->_titleModel; @@ -270,7 +270,7 @@ public function getTitles() if ($this->getData(self::KEY_TITLES)) { return $this->getData(self::KEY_TITLES); } - if (is_null($this->_titles)) { + if ($this->_titles === null) { $this->_titles = $this->getTitleModel()->getCollection()->loadByRateId($this->getId())->getItems(); } return $this->_titles; diff --git a/app/code/Magento/Tax/Model/Calculation/Rule/Validator.php b/app/code/Magento/Tax/Model/Calculation/Rule/Validator.php index 75923748e14cf..00c0e7101d4ca 100644 --- a/app/code/Magento/Tax/Model/Calculation/Rule/Validator.php +++ b/app/code/Magento/Tax/Model/Calculation/Rule/Validator.php @@ -6,7 +6,6 @@ namespace Magento\Tax\Model\Calculation\Rule; -use Magento\Framework\Exception\InputException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Tax\Model\ClassModel as TaxClassModel; use Magento\Tax\Model\ClassModelRegistry; diff --git a/app/code/Magento/Tax/Model/Plugin/OrderSave.php b/app/code/Magento/Tax/Model/Plugin/OrderSave.php index 7203285248688..a1a3ebf861d60 100644 --- a/app/code/Magento/Tax/Model/Plugin/OrderSave.php +++ b/app/code/Magento/Tax/Model/Plugin/OrderSave.php @@ -97,8 +97,12 @@ protected function saveOrderTax(\Magento\Sales\Api\Data\OrderInterface $order) } else { $percentSum = 0; foreach ($taxRates as $rate) { - $realAmount = $rates['amount'] * $rate['percent'] / $rates['percent']; - $realBaseAmount = $rates['base_amount'] * $rate['percent'] / $rates['percent']; + $percentSum += $rate['percent']; + } + + foreach ($taxRates as $rate) { + $realAmount = $rates['amount'] * $rate['percent'] / $percentSum; + $realBaseAmount = $rates['base_amount'] * $rate['percent'] / $percentSum; $ratesIdQuoteItemId[$rates['id']][] = [ 'id' => $taxesArray['item_id'], 'percent' => $rate['percent'], @@ -110,7 +114,6 @@ protected function saveOrderTax(\Magento\Sales\Api\Data\OrderInterface $order) 'real_amount' => $realAmount, 'real_base_amount' => $realBaseAmount, ]; - $percentSum += $rate['percent']; } } } @@ -163,7 +166,9 @@ protected function saveOrderTax(\Magento\Sales\Api\Data\OrderInterface $order) if (isset($quoteItemId['id'])) { //This is a product item $item = $order->getItemByQuoteItemId($quoteItemId['id']); - $itemId = $item->getId(); + if ($item !== null && $item->getId()) { + $itemId = $item->getId(); + } } elseif (isset($quoteItemId['associated_item_id'])) { //This item is associated with a product item $item = $order->getItemByQuoteItemId($quoteItemId['associated_item_id']); diff --git a/app/code/Magento/Tax/Model/ResourceModel/Calculation/Rule.php b/app/code/Magento/Tax/Model/ResourceModel/Calculation/Rule.php index e509f477bcd8d..91fd0f4dcffb3 100644 --- a/app/code/Magento/Tax/Model/ResourceModel/Calculation/Rule.php +++ b/app/code/Magento/Tax/Model/ResourceModel/Calculation/Rule.php @@ -6,7 +6,7 @@ namespace Magento\Tax\Model\ResourceModel\Calculation; /** - * Tax rate resource model + * Tax rule resource model * * @author Magento Core Team */ diff --git a/app/code/Magento/Tax/Model/Sales/Order/TaxManagement.php b/app/code/Magento/Tax/Model/Sales/Order/TaxManagement.php index c563ee1b3084e..2e6e74a573f99 100644 --- a/app/code/Magento/Tax/Model/Sales/Order/TaxManagement.php +++ b/app/code/Magento/Tax/Model/Sales/Order/TaxManagement.php @@ -10,7 +10,6 @@ use Magento\Framework\Exception\NoSuchEntityException; use Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterfaceFactory as TaxDetailsDataObjectFactory; use Magento\Tax\Api\Data\OrderTaxDetailsAppliedTaxInterface as AppliedTax; -use Magento\Tax\Model\Sales\Order\Tax; use Magento\Sales\Model\Order\Tax\Item; class TaxManagement implements \Magento\Tax\Api\OrderTaxManagementInterface diff --git a/app/code/Magento/Tax/Model/Sales/Total/Quote/CommonTaxCollector.php b/app/code/Magento/Tax/Model/Sales/Total/Quote/CommonTaxCollector.php index 1fcaf0e413cd5..7752911ceb22f 100644 --- a/app/code/Magento/Tax/Model/Sales/Total/Quote/CommonTaxCollector.php +++ b/app/code/Magento/Tax/Model/Sales/Total/Quote/CommonTaxCollector.php @@ -771,7 +771,7 @@ protected function _saveAppliedTaxes( $previouslyAppliedTaxes[$row['id']] = $row; } - if (!is_null($row['percent'])) { + if ($row['percent'] !== null) { $row['percent'] = $row['percent'] ? $row['percent'] : 1; $rate = $rate ? $rate : 1; diff --git a/app/code/Magento/Tax/Model/TaxRuleCollection.php b/app/code/Magento/Tax/Model/TaxRuleCollection.php index 33aaf3b22b6d6..5c6f3b1f14455 100644 --- a/app/code/Magento/Tax/Model/TaxRuleCollection.php +++ b/app/code/Magento/Tax/Model/TaxRuleCollection.php @@ -27,14 +27,14 @@ class TaxRuleCollection extends AbstractServiceCollection /** * Initialize dependencies. * - * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory + * @param EntityFactory $entityFactory * @param FilterBuilder $filterBuilder * @param SearchCriteriaBuilder $searchCriteriaBuilder * @param SortOrderBuilder $sortOrderBuilder * @param TaxRuleRepositoryInterface $ruleService */ public function __construct( - \Magento\Framework\Data\Collection\EntityFactory $entityFactory, + EntityFactory $entityFactory, FilterBuilder $filterBuilder, SearchCriteriaBuilder $searchCriteriaBuilder, SortOrderBuilder $sortOrderBuilder, diff --git a/app/code/Magento/Tax/Setup/UpgradeData.php b/app/code/Magento/Tax/Setup/UpgradeData.php index c2b9baca84042..5ede9cb6180e4 100644 --- a/app/code/Magento/Tax/Setup/UpgradeData.php +++ b/app/code/Magento/Tax/Setup/UpgradeData.php @@ -81,7 +81,7 @@ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface false ); } - if (version_compare($context->getVersion(), '2.0.2', '<')) { + if (version_compare($context->getVersion(), '2.0.3', '<')) { //Update the tax_region_id $taxRateList = $this->taxRateRepository->getList($this->searchCriteriaFactory->create()); /** @var \Magento\Tax\Api\Data\TaxRateInterface $taxRateData */ @@ -91,6 +91,9 @@ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface /** @var \Magento\Directory\Model\Region $region */ $region = $this->directoryRegionFactory->create(); $region->loadByCode($regionCode, $taxRateData->getTaxCountryId()); + if ($taxRateData->getTaxPostcode() === null) { + $taxRateData->setTaxPostcode('*'); + } $taxRateData->setTaxRegionId($region->getRegionId()); $this->taxRateRepository->save($taxRateData); } diff --git a/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php b/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php index afbf65b67b3a8..224be8cfbda67 100644 --- a/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php +++ b/app/code/Magento/Tax/Test/Unit/Block/Grid/Renderer/CodesTest.php @@ -6,8 +6,10 @@ namespace Magento\Tax\Test\Unit\Block\Grid\Renderer; use Magento\Framework\DataObject; +use Magento\Framework\Escaper; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Tax\Block\Grid\Renderer\Codes; +use Magento\Backend\Block\Context; /** * Test for Tax Rates codes column of Tax Rules grid. @@ -24,7 +26,26 @@ class CodesTest extends \PHPUnit\Framework\TestCase protected function setUp() { $objectManager = new ObjectManager($this); - $this->codes = $objectManager->getObject(Codes::class); + $escaper = $this->getMockBuilder(Escaper::class) + ->disableOriginalConstructor() + ->getMock(); + $escaper->expects($this->any()) + ->method('escapeHtml') + ->willReturnCallback( + function ($str) { + return 'ESCAPED:' .$str; + } + ); + $context = $this->getMockBuilder(Context::class) + ->disableOriginalConstructor() + ->getMock(); + $context->expects($this->any()) + ->method('getEscaper') + ->willReturn($escaper); + $this->codes = $objectManager->getObject( + Codes::class, + ['context' => $context] + ); } /** @@ -32,7 +53,7 @@ protected function setUp() * * @param array $ratesCodes * @param string $expected - * @see Magento\Tax\Block\Grid\Renderer\Codes::render + * @see Codes::render * @dataProvider ratesCodesDataProvider */ public function testRenderCodes($ratesCodes, $expected) @@ -50,8 +71,8 @@ public function testRenderCodes($ratesCodes, $expected) public function ratesCodesDataProvider() { return [ - [['some_code'], 'some_code'], - [['some_code', 'some_code2'], 'some_code, some_code2'], + [['some_code'], 'ESCAPED:some_code'], + [['some_code', 'some_code2'], 'ESCAPED:some_code, some_code2'], [[], ''], [null, ''] ]; diff --git a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php index 0f879a6e162f5..2035885f05e8f 100644 --- a/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php +++ b/app/code/Magento/Tax/Test/Unit/Controller/Adminhtml/Tax/IgnoreTaxNotificationTest.php @@ -19,7 +19,7 @@ public function testExecute() ->getMock(); $cacheTypeList->expects($this->once()) ->method('cleanType') - ->with('block_html') + ->with('config') ->willReturn(null); $request = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php index db2053efd41f6..e6a29177301dd 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateRepositoryTest.php @@ -307,7 +307,8 @@ public function testSaveThrowsExceptionIfCannotSaveTitles($expectedException, $e ->with($rateTitles) ->willThrowException($expectedException); $this->rateRegistryMock->expects($this->never())->method('registerTaxRate')->with($rateMock); - $this->expectException($exceptionType, $exceptionMessage); + $this->expectException($exceptionType); + $this->expectExceptionMessage($exceptionMessage); $this->model->save($rateMock); } diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php index 5a5abfd828d88..c0a04a3fb45f6 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RateTest.php @@ -46,7 +46,8 @@ protected function setUp() */ public function testExceptionOfValidation($exceptionMessage, $data) { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class, $exceptionMessage); + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage($exceptionMessage); $rate = $this->objectHelper->getObject( \Magento\Tax\Model\Calculation\Rate::class, ['resource' => $this->resourceMock] diff --git a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php index abb8c49015962..89800e3be872e 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php +++ b/app/code/Magento/Tax/Test/Unit/Model/Calculation/RowBaseAndTotalBaseCalculatorTestCase.php @@ -9,7 +9,7 @@ namespace Magento\Tax\Test\Unit\Model\Calculation; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Tax\Model\Calculation\RowbaseCalculator; +use Magento\Tax\Model\Calculation\RowBaseCalculator; use Magento\Tax\Model\Calculation\TotalBaseCalculator; /** diff --git a/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php b/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php index 182e1b43d786c..f4151cd18ba66 100644 --- a/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php +++ b/app/code/Magento/Tax/Test/Unit/Model/TaxRuleRepositoryTest.php @@ -163,7 +163,8 @@ public function testSaveWithExceptions($exceptionObject, $exceptionName, $except ->willThrowException($exceptionObject); $this->taxRuleRegistry->expects($this->never())->method('registerTaxRule'); - $this->expectException($exceptionName, $exceptionMessage); + $this->expectException($exceptionName); + $this->expectExceptionMessage($exceptionMessage); $this->model->save($rule); } diff --git a/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php b/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php index aaaf72b986240..9860825e07453 100644 --- a/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php +++ b/app/code/Magento/Tax/Test/Unit/Observer/UpdateProductOptionsObserverTest.php @@ -3,10 +3,9 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Tax\Test\Unit\Observer; -use \Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; class UpdateProductOptionsObserverTest extends \PHPUnit\Framework\TestCase { @@ -25,7 +24,7 @@ public function testUpdateProductOptions( $displayPriceExcludingTax ) { - $frameworkObject= new \Magento\Framework\DataObject(); + $frameworkObject = new \Magento\Framework\DataObject(); $frameworkObject->setAdditionalOptions([]); $product=$this->createMock(\Magento\Catalog\Model\Product::class); @@ -64,18 +63,18 @@ public function testUpdateProductOptions( ->method('getEvent') ->will($this->returnValue($eventObject)); - $objectManager = new ObjectManager($this); - $taxObserverObject = $objectManager->getObject( - \Magento\Tax\Observer\UpdateProductOptionsObserver::class, - [ - 'taxData' => $taxData, - 'registry' => $registry, - ] - ); + $objectManager = new ObjectManager($this); + $taxObserverObject = $objectManager->getObject( + \Magento\Tax\Observer\UpdateProductOptionsObserver::class, + [ + 'taxData' => $taxData, + 'registry' => $registry, + ] + ); - $taxObserverObject->execute($observerObject); + $taxObserverObject->execute($observerObject); - $this->assertEquals($expected, $frameworkObject->getAdditionalOptions()); + $this->assertEquals($expected, $frameworkObject->getAdditionalOptions()); } /** diff --git a/app/code/Magento/Tax/composer.json b/app/code/Magento/Tax/composer.json index 140b0ee8450cd..1c3023003c5fb 100644 --- a/app/code/Magento/Tax/composer.json +++ b/app/code/Magento/Tax/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-tax", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-config": "101.0.*", "magento/module-store": "100.2.*", "magento/module-catalog": "102.0.*", @@ -22,7 +22,7 @@ "magento/module-tax-sample-data": "Sample Data version:100.2.*" }, "type": "magento2-module", - "version": "100.2.0", + "version": "100.2.3", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Tax/etc/config.xml b/app/code/Magento/Tax/etc/config.xml index f5a1dd3478999..0b837944a3614 100644 --- a/app/code/Magento/Tax/etc/config.xml +++ b/app/code/Magento/Tax/etc/config.xml @@ -20,7 +20,6 @@ shipping 0 0 - 0 0 diff --git a/app/code/Magento/Tax/etc/di.xml b/app/code/Magento/Tax/etc/di.xml index 66b23f24e1095..096f8359fadd3 100644 --- a/app/code/Magento/Tax/etc/di.xml +++ b/app/code/Magento/Tax/etc/di.xml @@ -116,6 +116,7 @@ main_table.zip_is_range main_table.zip_from main_table.zip_to + region_table.code diff --git a/app/code/Magento/Tax/etc/module.xml b/app/code/Magento/Tax/etc/module.xml index 4f1c5dbeb12ec..a100b0ac01181 100644 --- a/app/code/Magento/Tax/etc/module.xml +++ b/app/code/Magento/Tax/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/Tax/i18n/en_US.csv b/app/code/Magento/Tax/i18n/en_US.csv index 2314f27b92928..836221e2ec974 100644 --- a/app/code/Magento/Tax/i18n/en_US.csv +++ b/app/code/Magento/Tax/i18n/en_US.csv @@ -176,4 +176,6 @@ Rate,Rate "Order Total Incl. Tax","Order Total Incl. Tax" "Order Total","Order Total" "Your credit card will be charged for","Your credit card will be charged for" -"An error occurred while loading tax rates.","An error occurred while loading tax rates." \ No newline at end of file +"An error occurred while loading tax rates.","An error occurred while loading tax rates." +"You will be charged for","You will be charged for" +"Not yet calculated", "Not yet calculated" diff --git a/app/code/Magento/Tax/view/adminhtml/templates/rule/edit.phtml b/app/code/Magento/Tax/view/adminhtml/templates/rule/edit.phtml index d16c4faeede28..fced077015f4e 100644 --- a/app/code/Magento/Tax/view/adminhtml/templates/rule/edit.phtml +++ b/app/code/Magento/Tax/view/adminhtml/templates/rule/edit.phtml @@ -111,6 +111,7 @@ require([ TaxRateEditableMultiselect.prototype.init = function () { var options = { + mselectContainer: '#tax_rate + section.mselect-list', toggleAddButton:false, addText: '', parse: null, diff --git a/app/code/Magento/Tax/view/frontend/layout/checkout_index_index.xml b/app/code/Magento/Tax/view/frontend/layout/checkout_index_index.xml index 6d867fcb71f2e..6969580b78b8f 100644 --- a/app/code/Magento/Tax/view/frontend/layout/checkout_index_index.xml +++ b/app/code/Magento/Tax/view/frontend/layout/checkout_index_index.xml @@ -70,7 +70,7 @@ Order Total Excl. Tax Order Total Incl. Tax - Your credit card will be charged for + You will be charged for Order Total diff --git a/app/code/Magento/Tax/view/frontend/templates/checkout/discount.phtml b/app/code/Magento/Tax/view/frontend/templates/checkout/discount.phtml deleted file mode 100644 index 75f04eae82159..0000000000000 --- a/app/code/Magento/Tax/view/frontend/templates/checkout/discount.phtml +++ /dev/null @@ -1,5 +0,0 @@ - helper('Magento\Tax\Helper\Data')->displayFullSummary() && $_value != 0): ?> - getTotal()->getFullInfo() as $info): ?> - diff --git a/app/code/Magento/Tax/view/frontend/web/js/view/checkout/summary/tax.js b/app/code/Magento/Tax/view/frontend/web/js/view/checkout/summary/tax.js index c86c3b4d1ab06..2bf3fd597891a 100644 --- a/app/code/Magento/Tax/view/frontend/web/js/view/checkout/summary/tax.js +++ b/app/code/Magento/Tax/view/frontend/web/js/view/checkout/summary/tax.js @@ -11,8 +11,10 @@ define([ 'ko', 'Magento_Checkout/js/view/summary/abstract-total', 'Magento_Checkout/js/model/quote', - 'Magento_Checkout/js/model/totals' -], function (ko, Component, quote, totals) { + 'Magento_Checkout/js/model/totals', + 'jquery', + 'mage/translate' +], function (ko, Component, quote, totals, $) { 'use strict'; var isTaxDisplayedInGrandTotal = window.checkoutConfig.includeTaxInGrandTotal, @@ -22,7 +24,7 @@ define([ return Component.extend({ defaults: { isTaxDisplayedInGrandTotal: isTaxDisplayedInGrandTotal, - notCalculatedMessage: 'Not yet calculated', + notCalculatedMessage: $.mage.__('Not yet calculated'), template: 'Magento_Tax/checkout/summary/tax' }, totals: quote.getTotals(), diff --git a/app/code/Magento/TaxImportExport/composer.json b/app/code/Magento/TaxImportExport/composer.json index 719c10ffe435c..3cb9f7dfce09b 100644 --- a/app/code/Magento/TaxImportExport/composer.json +++ b/app/code/Magento/TaxImportExport/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-tax-import-export", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-tax": "100.2.*", "magento/module-backend": "100.2.*", "magento/module-directory": "100.2.*", diff --git a/app/code/Magento/Theme/Block/Html/Footer.php b/app/code/Magento/Theme/Block/Html/Footer.php index 4cd63462ec754..cdb350336f38f 100644 --- a/app/code/Magento/Theme/Block/Html/Footer.php +++ b/app/code/Magento/Theme/Block/Html/Footer.php @@ -57,7 +57,6 @@ protected function _construct() { $this->addData( [ - 'cache_lifetime' => false, 'cache_tags' => [\Magento\Store\Model\Store::CACHE_TAG, \Magento\Cms\Model\Block::CACHE_TAG], ] ); @@ -123,4 +122,14 @@ public function getIdentities() { return [\Magento\Store\Model\Store::CACHE_TAG, \Magento\Cms\Model\Block::CACHE_TAG]; } + + /** + * Get block cache life time + * + * @return int + */ + protected function getCacheLifetime() + { + return parent::getCacheLifetime() ?: 3600; + } } diff --git a/app/code/Magento/Theme/Block/Html/Topmenu.php b/app/code/Magento/Theme/Block/Html/Topmenu.php index b1b22e06d7172..ed3445e117331 100644 --- a/app/code/Magento/Theme/Block/Html/Topmenu.php +++ b/app/code/Magento/Theme/Block/Html/Topmenu.php @@ -235,7 +235,13 @@ protected function _getHtml( if ($childLevel == 0 && $outermostClass) { $outermostClassCode = ' class="' . $outermostClass . '" '; - $child->setClass($outermostClass); + $currentClass = $child->getClass(); + + if (empty($currentClass)) { + $child->setClass($outermostClass); + } else { + $child->setClass($currentClass . ' ' . $outermostClass); + } } if (count($colBrakes) && $colBrakes[$counter]['colbrake']) { @@ -331,7 +337,7 @@ protected function _getMenuItemClasses(\Magento\Framework\Data\Tree\Node $item) /** * Add identity * - * @param array $identity + * @param string|array $identity * @return void */ public function addIdentity($identity) diff --git a/app/code/Magento/Theme/Console/Command/ThemeUninstallCommand.php b/app/code/Magento/Theme/Console/Command/ThemeUninstallCommand.php index 4c8d6bca52edc..540fd962a4f2e 100644 --- a/app/code/Magento/Theme/Console/Command/ThemeUninstallCommand.php +++ b/app/code/Magento/Theme/Console/Command/ThemeUninstallCommand.php @@ -6,9 +6,10 @@ namespace Magento\Theme\Console\Command; -use Magento\Framework\App\Area; use Magento\Framework\App\Cache; use Magento\Framework\App\MaintenanceMode; +use Magento\Framework\App\Console\MaintenanceModeEnabler; +use Magento\Framework\App\ObjectManager; use Magento\Framework\App\State\CleanupFiles; use Magento\Framework\Composer\ComposerInformation; use Magento\Framework\Composer\DependencyChecker; @@ -39,13 +40,6 @@ class ThemeUninstallCommand extends Command const INPUT_KEY_THEMES = 'theme'; const INPUT_KEY_CLEAR_STATIC_CONTENT = 'clear-static-content'; - /** - * Maintenance Mode - * - * @var MaintenanceMode - */ - private $maintenanceMode; - /** * Composer general dependency checker * @@ -116,13 +110,18 @@ class ThemeUninstallCommand extends Command */ private $themeDependencyChecker; + /** + * @var MaintenanceModeEnabler + */ + private $maintenanceModeEnabler; + /** * Constructor * * @param Cache $cache * @param CleanupFiles $cleanupFiles * @param ComposerInformation $composer - * @param MaintenanceMode $maintenanceMode + * @param MaintenanceMode $maintenanceMode deprecated, use $maintenanceModeEnabler instead * @param DependencyChecker $dependencyChecker * @param Collection $themeCollection * @param BackupRollbackFactory $backupRollbackFactory @@ -130,6 +129,9 @@ class ThemeUninstallCommand extends Command * @param ThemePackageInfo $themePackageInfo * @param ThemeUninstaller $themeUninstaller * @param ThemeDependencyChecker $themeDependencyChecker + * @param MaintenanceModeEnabler $maintenanceModeEnabler + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __construct( Cache $cache, @@ -142,12 +144,12 @@ public function __construct( ThemeValidator $themeValidator, ThemePackageInfo $themePackageInfo, ThemeUninstaller $themeUninstaller, - ThemeDependencyChecker $themeDependencyChecker + ThemeDependencyChecker $themeDependencyChecker, + MaintenanceModeEnabler $maintenanceModeEnabler = null ) { $this->cache = $cache; $this->cleanupFiles = $cleanupFiles; $this->composer = $composer; - $this->maintenanceMode = $maintenanceMode; $this->dependencyChecker = $dependencyChecker; $this->themeCollection = $themeCollection; $this->backupRollbackFactory = $backupRollbackFactory; @@ -155,6 +157,8 @@ public function __construct( $this->themePackageInfo = $themePackageInfo; $this->themeUninstaller = $themeUninstaller; $this->themeDependencyChecker = $themeDependencyChecker; + $this->maintenanceModeEnabler = + $maintenanceModeEnabler ?: ObjectManager::getInstance()->get(MaintenanceModeEnabler::class); parent::__construct(); } @@ -214,27 +218,32 @@ protected function execute(InputInterface $input, OutputInterface $output) return \Magento\Framework\Console\Cli::RETURN_FAILURE; } - try { - $output->writeln('Enabling maintenance mode'); - $this->maintenanceMode->set(true); - if ($input->getOption(self::INPUT_KEY_BACKUP_CODE)) { - $time = time(); - $codeBackup = $this->backupRollbackFactory->create($output); - $codeBackup->codeBackup($time); - } - - $this->themeUninstaller->uninstallRegistry($output, $themePaths); - $this->themeUninstaller->uninstallCode($output, $themePaths); + $result = $this->maintenanceModeEnabler->executeInMaintenanceMode( + function () use ($input, $output, $themePaths) { + try { + if ($input->getOption(self::INPUT_KEY_BACKUP_CODE)) { + $time = time(); + $codeBackup = $this->backupRollbackFactory->create($output); + $codeBackup->codeBackup($time); + } + + $this->themeUninstaller->uninstallRegistry($output, $themePaths); + $this->themeUninstaller->uninstallCode($output, $themePaths); + + $this->cleanup($input, $output); + return \Magento\Framework\Console\Cli::RETURN_SUCCESS; + } catch (\Exception $e) { + $output->writeln('' . $e->getMessage() . ''); + $output->writeln('Please disable maintenance mode after you resolved above issues'); + // we must have an exit code higher than zero to indicate something was wrong + return \Magento\Framework\Console\Cli::RETURN_FAILURE; + } + }, + $output, + true + ); - $this->cleanup($input, $output); - $output->writeln('Disabling maintenance mode'); - $this->maintenanceMode->set(false); - } catch (\Exception $e) { - $output->writeln('' . $e->getMessage() . ''); - $output->writeln('Please disable maintenance mode after you resolved above issues'); - // we must have an exit code higher than zero to indicate something was wrong - return \Magento\Framework\Console\Cli::RETURN_FAILURE; - } + return $result; } /** diff --git a/app/code/Magento/Theme/Model/Config/Processor/DesignTheme.php b/app/code/Magento/Theme/Model/Config/Processor/DesignTheme.php index 258be67979ed2..d9d2c0e041e99 100644 --- a/app/code/Magento/Theme/Model/Config/Processor/DesignTheme.php +++ b/app/code/Magento/Theme/Model/Config/Processor/DesignTheme.php @@ -72,8 +72,8 @@ public function process(array $config) private function changeThemeFullPathToIdentifier($configItems) { $theme = null; - if ($this->arrayManager->exists(DesignInterface::XML_PATH_THEME_ID, $configItems)) { - $themeIdentifier = $this->arrayManager->get(DesignInterface::XML_PATH_THEME_ID, $configItems); + $themeIdentifier = $this->arrayManager->get(DesignInterface::XML_PATH_THEME_ID, $configItems); + if (!empty($themeIdentifier)) { if (!is_numeric($themeIdentifier)) { // workaround for case when db is not available try { diff --git a/app/code/Magento/Theme/Model/Design/Backend/File.php b/app/code/Magento/Theme/Model/Design/Backend/File.php index 1e32cb36b4aea..b37628e54aa30 100644 --- a/app/code/Magento/Theme/Model/Design/Backend/File.php +++ b/app/code/Magento/Theme/Model/Design/Backend/File.php @@ -89,9 +89,9 @@ public function beforeSave() $values = $this->getValue(); $value = reset($values) ?: []; if (!isset($value['file'])) { - throw new LocalizedException( - __('%1 does not contain field \'file\'', $this->getData('field_config/field')) - ); + throw new LocalizedException( + __('%1 does not contain field \'file\'', $this->getData('field_config/field')) + ); } if (isset($value['exists'])) { $this->setValue($value['file']); diff --git a/app/code/Magento/Theme/Model/Design/Config/Storage.php b/app/code/Magento/Theme/Model/Design/Config/Storage.php index a73f70efa0adf..c97114f963a09 100644 --- a/app/code/Magento/Theme/Model/Design/Config/Storage.php +++ b/app/code/Magento/Theme/Model/Design/Config/Storage.php @@ -87,10 +87,13 @@ public function load($scope, $scopeId) $scopeId, $fieldData->getFieldConfig() ); - if ($value !== null) { - $fieldData->setValue($value); + + if ($value === null) { + $value = ''; } + $fieldData->setValue($value); } + return $designConfig; } diff --git a/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php b/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php index abd4c91a7e1b7..2ae889e69bb12 100644 --- a/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php +++ b/app/code/Magento/Theme/Test/Unit/Console/Command/ThemeUninstallCommandTest.php @@ -6,6 +6,7 @@ namespace Magento\Theme\Test\Unit\Console\Command; +use Magento\Framework\App\Console\MaintenanceModeEnabler; use Magento\Theme\Console\Command\ThemeUninstallCommand; use Magento\Theme\Model\Theme\themePackageInfo; use Magento\Theme\Model\Theme\ThemeUninstaller; @@ -19,7 +20,7 @@ class ThemeUninstallCommandTest extends \PHPUnit\Framework\TestCase { /** - * @var \Magento\Framework\App\MaintenanceMode|\PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Console\MaintenanceMode|\PHPUnit_Framework_MockObject_MockObject */ private $maintenanceMode; @@ -107,7 +108,8 @@ protected function setUp() $this->themeValidator, $this->themePackageInfo, $this->themeUninstaller, - $this->themeDependencyChecker + $this->themeDependencyChecker, + new MaintenanceModeEnabler($this->maintenanceMode) ); $this->tester = new CommandTester($this->command); } diff --git a/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php b/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php index 1f3ab5642f471..bb2160f1e293d 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/Config/Processor/DesignThemeTest.php @@ -5,7 +5,6 @@ */ namespace Magento\Theme\Test\Unit\Model\Config\Processor; -use Magento\Config\App\Config\Source\DumpConfigSourceAggregated; use Magento\Framework\Stdlib\ArrayManager; use Magento\Framework\View\Design\Theme\ListInterface; use Magento\Theme\Model\Config\Processor\DesignTheme; @@ -78,6 +77,7 @@ private function prepareThemeMock() /** * @return array + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getDumpConfigDataProvider() { @@ -163,6 +163,22 @@ public function getDumpConfigDataProvider() ], ], ], + [ + [ + 'websites' => [ + 'base' => [ + 'design' => ['theme' => ['theme_id' => '']], + ], + ], + ], + [ + 'websites' => [ + 'base' => [ + 'design' => ['theme' => ['theme_id' => '']], + ], + ], + ], + ], ]; } } diff --git a/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php b/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php index 0eaa509685616..f1f4664c8541d 100644 --- a/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php +++ b/app/code/Magento/Theme/Test/Unit/Observer/CleanThemeRelatedContentObserverTest.php @@ -105,7 +105,8 @@ public function testCleanThemeRelatedContentException() $this->themeConfig->expects($this->any())->method('isThemeAssignedToStore')->with($themeMock)->willReturn(true); - $this->expectException(\Magento\Framework\Exception\LocalizedException::class, 'Theme isn\'t deletable.'); + $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectExceptionMessage('Theme isn\'t deletable.'); $this->themeObserver->execute($observerMock); } diff --git a/app/code/Magento/Theme/composer.json b/app/code/Magento/Theme/composer.json index 3d3161c476ef1..147091aa14364 100644 --- a/app/code/Magento/Theme/composer.json +++ b/app/code/Magento/Theme/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-theme", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-store": "100.2.*", "magento/module-customer": "101.0.*", "magento/module-backend": "100.2.*", @@ -22,7 +22,7 @@ "magento/module-directory": "100.2.*" }, "type": "magento2-module", - "version": "100.2.0", + "version": "100.2.3", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Theme/etc/config.xml b/app/code/Magento/Theme/etc/config.xml index 925b906af9523..a6984b449d944 100644 --- a/app/code/Magento/Theme/etc/config.xml +++ b/app/code/Magento/Theme/etc/config.xml @@ -45,7 +45,7 @@ Disallow: /*SID= Default welcome msg!
    - Copyright © 2013-2017 Magento, Inc. All rights reserved. + Copyright © 2013-present Magento, Inc. All rights reserved.
    diff --git a/app/code/Magento/Theme/i18n/en_US.csv b/app/code/Magento/Theme/i18n/en_US.csv index 16cc5596b3a93..b454b7222bd1c 100644 --- a/app/code/Magento/Theme/i18n/en_US.csv +++ b/app/code/Magento/Theme/i18n/en_US.csv @@ -142,7 +142,7 @@ Empty,Empty "1 column","1 column" Configuration,Configuration "Default welcome msg!","Default welcome msg!" -"Copyright © 2013-2017 Magento, Inc. All rights reserved.","Copyright © 2013-2017 Magento, Inc. All rights reserved." +"Copyright © 2013-present Magento, Inc. All rights reserved.","Copyright © 2013-present Magento, Inc. All rights reserved." "Design Config Grid","Design Config Grid" "Rebuild design config grid index","Rebuild design config grid index" "Admin empty","Admin empty" diff --git a/app/code/Magento/Theme/view/frontend/requirejs-config.js b/app/code/Magento/Theme/view/frontend/requirejs-config.js index 51657fb11f2c8..bf38d3cbaae00 100644 --- a/app/code/Magento/Theme/view/frontend/requirejs-config.js +++ b/app/code/Magento/Theme/view/frontend/requirejs-config.js @@ -27,7 +27,8 @@ var config = { 'menu': 'mage/menu', 'popupWindow': 'mage/popup-window', 'validation': 'mage/validation/validation', - 'welcome': 'Magento_Theme/js/view/welcome' + 'welcome': 'Magento_Theme/js/view/welcome', + 'breadcrumbs': 'Magento_Theme/js/view/breadcrumbs' } }, paths: { @@ -38,5 +39,12 @@ var config = { 'mage/common', 'mage/dataPost', 'mage/bootstrap' - ] + ], + config: { + mixins: { + 'Magento_Theme/js/view/breadcrumbs': { + 'Magento_Theme/js/view/add-home-breadcrumb': true + } + } + } }; diff --git a/app/code/Magento/Theme/view/frontend/templates/html/header.phtml b/app/code/Magento/Theme/view/frontend/templates/html/header.phtml index cc3ea276e2230..4395cab651de1 100644 --- a/app/code/Magento/Theme/view/frontend/templates/html/header.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/html/header.phtml @@ -15,11 +15,11 @@ $welcomeMessage = $block->getWelcome(); case 'welcome': ?>
  • - + - + getBlockHtml('header.additional') ?>
  • diff --git a/app/code/Magento/Theme/view/frontend/templates/page/js/require_js.phtml b/app/code/Magento/Theme/view/frontend/templates/page/js/require_js.phtml index 67265de90da77..2a4b07ee6396f 100644 --- a/app/code/Magento/Theme/view/frontend/templates/page/js/require_js.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/page/js/require_js.phtml @@ -5,6 +5,7 @@ */ ?> '; } } diff --git a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php index ed571f44dd6e9..d814fdcd153da 100644 --- a/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php +++ b/app/code/Magento/Ui/Test/Unit/Component/Filters/Type/InputTest.php @@ -111,8 +111,7 @@ public function testPrepare($name, $filterData, $expectedCondition) ->method('addComponentDefinition') ->with(Input::NAME, ['extends' => Input::NAME]); $this->contextMock->expects($this->any()) - ->method('getRequestParam') - ->with(UiContext::FILTER_VAR) + ->method('getFiltersParams') ->willReturn($filterData); $dataProvider = $this->getMockForAbstractClass( \Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface::class, @@ -120,20 +119,41 @@ public function testPrepare($name, $filterData, $expectedCondition) '', false ); + $this->contextMock->expects($this->any()) ->method('getDataProvider') ->willReturn($dataProvider); - if ($expectedCondition !== null) { - $dataProvider->expects($this->any()) - ->method('addFilter') - ->with($expectedCondition, $name); - } $this->uiComponentFactory->expects($this->any()) ->method('create') ->with($name, Input::COMPONENT, ['context' => $this->contextMock]) ->willReturn($uiComponent); + if ($expectedCondition !== null) { + $this->filterBuilderMock->expects($this->once()) + ->method('setConditionType') + ->with('like') + ->willReturnSelf(); + + $this->filterBuilderMock->expects($this->once()) + ->method('setField') + ->with($name) + ->willReturnSelf(); + + $this->filterBuilderMock->expects($this->once()) + ->method('setValue') + ->with($expectedCondition['like']) + ->willReturnSelf(); + + $filterMock = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->filterBuilderMock->expects($this->once()) + ->method('create') + ->willReturn($filterMock); + } + $date = new Input( $this->contextMock, $this->uiComponentFactory, @@ -160,7 +180,12 @@ public function getPrepareDataProvider() [ 'test_date', ['test_date' => 'some_value'], - ['like' => '%some_value%'], + ['like' => '%some\_value%'], + ], + [ + 'test_date', + ['test_date' => '%'], + ['like' => '%\%%'], ], ]; } diff --git a/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php b/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php new file mode 100644 index 0000000000000..3935842aa642b --- /dev/null +++ b/app/code/Magento/Ui/Test/Unit/Component/FiltersTest.php @@ -0,0 +1,79 @@ +uiComponentInterface = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->uiComponentFactory = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentFactory::class) + ->disableOriginalConstructor() + ->getMock(); + $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponent\ContextInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->filters = $objectManager->getObject( + Filters::class, + [ + 'columnFilters' => ['select' => $this->uiComponentInterface], + 'uiComponentFactory' => $this->uiComponentFactory, + 'context' => $this->context + ] + ); + } + + public function testUpdate() + { + $componentName = 'component_name'; + $componentConfig = [0, 1, 2]; + $columnInterface = $this->getMockBuilder(\Magento\Ui\Component\Listing\Columns\ColumnInterface::class) + ->disableOriginalConstructor() + ->setMethods(['getData', 'getName', 'getConfiguration']) + ->getMockForAbstractClass(); + $columnInterface->expects($this->atLeastOnce())->method('getData')->with('config/filter')->willReturn('text'); + $columnInterface->expects($this->atLeastOnce())->method('getName')->willReturn($componentName); + $columnInterface->expects($this->once())->method('getConfiguration')->willReturn($componentConfig); + $filterComponent = $this->getMockBuilder(\Magento\Framework\View\Element\UiComponentInterface::class) + ->disableOriginalConstructor() + ->setMethods(['setData', 'prepare']) + ->getMockForAbstractClass(); + $filterComponent->expects($this->once())->method('setData')->with('config', $componentConfig) + ->willReturnSelf(); + $filterComponent->expects($this->once())->method('prepare')->willReturnSelf(); + $this->uiComponentFactory->expects($this->once())->method('create') + ->with($componentName, 'filterInput', ['context' => $this->context]) + ->willReturn($filterComponent); + + $this->filters->update($columnInterface); + /** Verify that filter is already set and it wouldn't be set again */ + $this->filters->update($columnInterface); + } +} diff --git a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php index 7d5de26be6d2e..08d56d0c0bb93 100644 --- a/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php +++ b/app/code/Magento/Ui/Test/Unit/Controller/Adminhtml/Index/RenderTest.php @@ -9,6 +9,7 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; /** + * Test for Magento\Ui\Controller\Adminhtml\Index\Render * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class RenderTest extends \PHPUnit\Framework\TestCase @@ -89,6 +90,9 @@ class RenderTest extends \PHPUnit\Framework\TestCase */ private $loggerMock; + /** + * @inheritdoc + */ protected function setUp() { $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class) @@ -175,88 +179,61 @@ protected function setUp() public function testExecuteAjaxRequestException() { - $name = 'test-name'; + $namespace = 'test-name'; $renderedData = 'data'; - $this->requestMock->expects($this->any()) - ->method('getParam') - ->with('namespace') - ->willReturn($name); - $this->requestMock->expects($this->any()) - ->method('getParams') - ->willReturn([]); + $this->prepareComponent($namespace, $renderedData); $this->responseMock->expects($this->once()) ->method('appendBody') ->willThrowException(new \Exception('exception')); - $jsonResultMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Json::class) ->disableOriginalConstructor() ->setMethods(['setData']) ->getMock(); - $this->resultJsonFactoryMock->expects($this->once()) ->method('create') ->willReturn($jsonResultMock); - $jsonResultMock->expects($this->once()) ->method('setData') ->willReturnSelf(); - $this->loggerMock->expects($this->once()) ->method('critical') ->willReturnSelf(); - $this->dataProviderMock->expects($this->once()) - ->method('getConfigData') - ->willReturn([]); + $this->render->executeAjaxRequest(); + } - $this->uiComponentMock->expects($this->once()) - ->method('render') - ->willReturn($renderedData); - $this->uiComponentMock->expects($this->once()) - ->method('getChildComponents') - ->willReturn([]); - $this->uiComponentMock->expects($this->once()) - ->method('getContext') - ->willReturn($this->uiComponentContextMock); - $this->uiFactoryMock->expects($this->once()) - ->method('create') - ->willReturn($this->uiComponentMock); + public function testExecuteAjaxJsonRequest() + { + $namespace = 'test-name'; + $renderedData = '{"data": "test"}'; + $acceptType = 'json'; + + $this->prepareComponent($namespace, $renderedData, $acceptType); + $this->responseMock->expects($this->any()) + ->method('appendBody') + ->with($renderedData); + $this->responseMock->expects($this->once()) + ->method('setHeader') + ->with('Content-Type', 'application/json') + ->willReturnSelf(); $this->render->executeAjaxRequest(); } public function testExecuteAjaxRequest() { - $name = 'test-name'; + $namespace = 'test-name'; $renderedData = 'data'; - $this->requestMock->expects($this->any()) - ->method('getParam') - ->with('namespace') - ->willReturn($name); - $this->requestMock->expects($this->any()) - ->method('getParams') - ->willReturn([]); - $this->responseMock->expects($this->once()) + $this->prepareComponent($namespace, $renderedData); + $this->responseMock->expects($this->any()) ->method('appendBody') ->with($renderedData); - $this->dataProviderMock->expects($this->once()) - ->method('getConfigData') - ->willReturn([]); - - $this->uiComponentMock->expects($this->once()) - ->method('render') - ->willReturn($renderedData); - $this->uiComponentMock->expects($this->once()) - ->method('getChildComponents') - ->willReturn([]); - $this->uiComponentMock->expects($this->once()) - ->method('getContext') - ->willReturn($this->uiComponentContextMock); - $this->uiFactoryMock->expects($this->once()) - ->method('create') - ->willReturn($this->uiComponentMock); + $this->responseMock->expects($this->never()) + ->method('setHeader') + ->with('Content-type', 'application/json') + ->willReturnSelf(); $this->render->executeAjaxRequest(); } @@ -279,6 +256,13 @@ public function testExecuteAjaxRequestWithoutPermissions(array $dataProviderConf $this->requestMock->expects($this->any()) ->method('getParams') ->willReturn([]); + if ($isAllowed === false) { + $this->requestMock->expects($this->once()) + ->method('isAjax') + ->willReturn(true); + } + $this->responseMock->expects($this->never()) + ->method('setRedirect'); $this->responseMock->expects($this->any()) ->method('appendBody') ->with($renderedData); @@ -298,9 +282,12 @@ public function testExecuteAjaxRequestWithoutPermissions(array $dataProviderConf $this->uiComponentMock->expects($this->any()) ->method('getChildComponents') ->willReturn([]); - $this->uiComponentMock->expects($this->once()) + $this->uiComponentMock->expects($this->any()) ->method('getContext') ->willReturn($this->uiComponentContextMock); + $this->uiComponentContextMock->expects($this->any()) + ->method('getAcceptType') + ->willReturn('html'); $this->uiFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->uiComponentMock); @@ -330,4 +317,41 @@ public function executeAjaxRequestWithoutPermissionsDataProvider() ], ]; } + + /** + * Prepare component mock. + * + * @param string $namespace + * @param string $renderedData + * @param string $acceptType + * @return void + */ + private function prepareComponent($namespace, $renderedData, $acceptType = 'html') + { + $this->requestMock->expects($this->any()) + ->method('getParam') + ->with('namespace') + ->willReturn($namespace); + $this->requestMock->expects($this->any()) + ->method('getParams') + ->willReturn([]); + $this->dataProviderMock->expects($this->once()) + ->method('getConfigData') + ->willReturn([]); + $this->uiComponentMock->expects($this->once()) + ->method('render') + ->willReturn($renderedData); + $this->uiComponentMock->expects($this->once()) + ->method('getChildComponents') + ->willReturn([]); + $this->uiComponentMock->expects($this->exactly(2)) + ->method('getContext') + ->willReturn($this->uiComponentContextMock); + $this->uiComponentContextMock->expects($this->once()) + ->method('getAcceptType') + ->willReturn($acceptType); + $this->uiFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->uiComponentMock); + } } diff --git a/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php b/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php index 00a88437c8cb1..a0cec2258d658 100644 --- a/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php +++ b/app/code/Magento/Ui/Test/Unit/Model/ResourceModel/BookmarkRepositoryTest.php @@ -94,7 +94,8 @@ public function testSaveWithException() ->method('save') ->with($this->bookmarkMock) ->willThrowException(new \Exception($exceptionMessage)); - $this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class, __($exceptionMessage)); + $this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class); + $this->expectExceptionMessage($exceptionMessage); $this->bookmarkRepository->save($this->bookmarkMock); } @@ -143,7 +144,8 @@ public function testDeleteWithException() ->method('delete') ->with($this->bookmarkMock) ->willThrowException(new \Exception($exceptionMessage)); - $this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class, __($exceptionMessage)); + $this->expectException(\Magento\Framework\Exception\CouldNotDeleteException::class); + $this->expectExceptionMessage($exceptionMessage); $this->assertTrue($this->bookmarkRepository->delete($this->bookmarkMock)); } diff --git a/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php b/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php new file mode 100644 index 0000000000000..30a8e8005bbe8 --- /dev/null +++ b/app/code/Magento/Ui/Test/Unit/TemplateEngine/Xhtml/ResultTest.php @@ -0,0 +1,97 @@ +template = $this->createPartialMock(Template::class, ['append']); + $this->compiler = $this->createMock(CompilerInterface::class); + $this->component = $this->createMock(UiComponentInterface::class); + $this->structure = $this->createPartialMock(Structure::class, ['generate']); + $this->logger = $this->createMock(LoggerInterface::class); + + $this->objectManager = new ObjectManager($this); + $this->testModel = $this->objectManager->getObject(Result::class, [ + 'template' => $this->template, + 'compiler' => $this->compiler, + 'component' => $this->component, + 'structure' => $this->structure, + 'logger' => $this->logger, + ]); + } + + /** + * Test Append layout configuration method + */ + public function testAppendLayoutConfiguration() + { + $configWithCdata = 'text before '; + $this->structure->expects($this->once()) + ->method('generate') + ->with($this->component) + ->willReturn([$configWithCdata]); + $this->template->expects($this->once()) + ->method('append') + ->with(''); + + $this->testModel->appendLayoutConfiguration(); + } +} diff --git a/app/code/Magento/Ui/composer.json b/app/code/Magento/Ui/composer.json index f93b97b1b30fe..3a0d369ac4536 100644 --- a/app/code/Magento/Ui/composer.json +++ b/app/code/Magento/Ui/composer.json @@ -2,7 +2,7 @@ "name": "magento/module-ui", "description": "N/A", "require": { - "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "php": "~7.0.13|~7.1.0", "magento/module-backend": "100.2.*", "magento/framework": "101.0.*", "magento/module-eav": "101.0.*", @@ -13,7 +13,7 @@ "magento/module-config": "101.0.*" }, "type": "magento2-module", - "version": "101.0.0", + "version": "101.0.3", "license": [ "OSL-3.0", "AFL-3.0" diff --git a/app/code/Magento/Ui/i18n/en_US.csv b/app/code/Magento/Ui/i18n/en_US.csv index 1a1b56b379075..cff52a3fd6fed 100644 --- a/app/code/Magento/Ui/i18n/en_US.csv +++ b/app/code/Magento/Ui/i18n/en_US.csv @@ -179,3 +179,25 @@ settings/addAfter,settings/addAfter Action,Action CSV,CSV "Excel XML","Excel XML" +"Please select one of the options above.","Please select one of the options above." +"Please select a file.","Please select a file." +"Please select one of the options.","Please select one of the options." +"Please enter a value less than or equal to %s.","Please enter a value less than or equal to %s." +"Please enter a value greater than or equal to %s.","Please enter a value greater than or equal to %s." +"Card type does not match credit card number.","Card type does not match credit card number." +"Credit card number does not match credit card type.","Credit card number does not match credit card type." +"Incorrect credit card expiration date.","Incorrect credit card expiration date." +"Please enter less or equal than %1 symbols.","Please enter less or equal than %1 symbols." +"Please enter more or equal than %1 symbols.","Please enter more or equal than %1 symbols." +"Please enter a valid value from list","Please enter a valid value from list" +"Please enter valid SKU key.","Please enter valid SKU key." +"Please enter a valid number.","Please enter a valid number." +"Admin is a required field in each row.","Admin is a required field in each row." +"Please fix this field.","Please fix this field." +"Please enter a valid date (ISO).","Please enter a valid date (ISO)." +"Please enter only digits.","Please enter only digits." +"Please enter the same value again.","Please enter the same value again." +"Please enter no more than {0} characters.","Please enter no more than {0} characters." +"Please enter at least {0} characters.","Please enter at least {0} characters." +"Please enter a value between {0} and {1} characters long.","Please enter a value between {0} and {1} characters long." +"Please enter a value between {0} and {1}.","Please enter a value between {0} and {1}." diff --git a/app/code/Magento/Ui/view/base/ui_component/templates/container/default.xhtml b/app/code/Magento/Ui/view/base/ui_component/templates/container/default.xhtml index dd4a2038a53c4..5bbf252c8a787 100644 --- a/app/code/Magento/Ui/view/base/ui_component/templates/container/default.xhtml +++ b/app/code/Magento/Ui/view/base/ui_component/templates/container/default.xhtml @@ -5,7 +5,7 @@ * See COPYING.txt for license details. */ --> -
    +
    diff --git a/app/code/Magento/Ui/view/base/ui_component/templates/export/button.xhtml b/app/code/Magento/Ui/view/base/ui_component/templates/export/button.xhtml index 6dc91cf6b3d5b..977ea8374dfa8 100644 --- a/app/code/Magento/Ui/view/base/ui_component/templates/export/button.xhtml +++ b/app/code/Magento/Ui/view/base/ui_component/templates/export/button.xhtml @@ -5,7 +5,7 @@ * See COPYING.txt for license details. */ --> -
    +
    diff --git a/app/code/Magento/Ui/view/base/ui_component/templates/form/collapsible.xhtml b/app/code/Magento/Ui/view/base/ui_component/templates/form/collapsible.xhtml index baab52111aebe..aedf18961a719 100644 --- a/app/code/Magento/Ui/view/base/ui_component/templates/form/collapsible.xhtml +++ b/app/code/Magento/Ui/view/base/ui_component/templates/form/collapsible.xhtml @@ -5,7 +5,7 @@ * See COPYING.txt for license details. */ --> -
    +
    diff --git a/app/code/Magento/Ui/view/base/ui_component/templates/form/default.xhtml b/app/code/Magento/Ui/view/base/ui_component/templates/form/default.xhtml index 5e0d699ed3edc..9d7715db905ab 100644 --- a/app/code/Magento/Ui/view/base/ui_component/templates/form/default.xhtml +++ b/app/code/Magento/Ui/view/base/ui_component/templates/form/default.xhtml @@ -5,7 +5,7 @@ * See COPYING.txt for license details. */ --> -
    +
    diff --git a/app/code/Magento/Ui/view/base/ui_component/templates/listing/default.xhtml b/app/code/Magento/Ui/view/base/ui_component/templates/listing/default.xhtml index 88a8e42e2966b..661c7c0c23dfb 100644 --- a/app/code/Magento/Ui/view/base/ui_component/templates/listing/default.xhtml +++ b/app/code/Magento/Ui/view/base/ui_component/templates/listing/default.xhtml @@ -9,7 +9,7 @@ class="admin__data-grid-outer-wrap" data-bind="scope: '{{getName()}}.{{getName()}}'" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="../../../../../../Ui/etc/ui_template.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_template.xsd">
    diff --git a/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js b/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js index d4eea859b4d35..94a05e5fcde33 100644 --- a/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js +++ b/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js @@ -224,6 +224,14 @@ define([ return this; }, + /** @inheritdoc */ + destroy: function () { + if (this.dnd()) { + this.dnd().destroy(); + } + this._super(); + }, + /** * Calls 'initObservable' of parent * @@ -533,7 +541,8 @@ define([ * Init header elements */ initHeader: function () { - var data; + var labels = [], + data; if (!this.labels().length) { _.each(this.childTemplate.children, function (cell) { @@ -547,8 +556,9 @@ define([ sortOrder: cell.config.sortOrder }); - this.labels.push(data); + labels.push(data); }, this); + this.labels(_.sortBy(labels, 'sortOrder')); } }, diff --git a/app/code/Magento/Ui/view/base/web/js/form/components/html.js b/app/code/Magento/Ui/view/base/web/js/form/components/html.js index 82e51aff40287..c2da416c3d829 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/components/html.js +++ b/app/code/Magento/Ui/view/base/web/js/form/components/html.js @@ -19,8 +19,12 @@ define([ showSpinner: false, loading: false, visible: true, + error: false, template: 'ui/content/content', - additionalClasses: {} + additionalClasses: {}, + ignoreTmpls: { + content: true + } }, /** diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/abstract.js b/app/code/Magento/Ui/view/base/web/js/form/element/abstract.js index 6bbcb4416d33a..b6979121a1891 100755 --- a/app/code/Magento/Ui/view/base/web/js/form/element/abstract.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/abstract.js @@ -118,8 +118,8 @@ define([ this._super(); - scope = this.dataScope; - name = scope.split('.').slice(1); + scope = this.dataScope.split('.'); + name = scope.length > 1 ? scope.slice(1) : scope; valueUpdate = this.showFallbackReset ? 'afterkeydown' : this.valueUpdate; diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/country.js b/app/code/Magento/Ui/view/base/web/js/form/element/country.js index 49083374767ec..f64a80bf535ec 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/element/country.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/country.js @@ -28,7 +28,7 @@ define([ * @param {String} field */ filter: function (value, field) { - var result; + var result, defaultCountry, defaultValue; if (!field) { //validate field, if we are on update field = this.filterBy.field; @@ -46,6 +46,17 @@ define([ this.setOptions(result); this.reset(); + + if (!this.value()) { + defaultCountry = _.filter(result, function (item) { + return item['is_default'] && item['is_default'].includes(value); + }); + + if (defaultCountry.length) { + defaultValue = defaultCountry.shift(); + this.value(defaultValue.value); + } + } } }); }); diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/date.js b/app/code/Magento/Ui/view/base/web/js/form/element/date.js index a5eb7d5d1f570..586cc28b3abf1 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/element/date.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/date.js @@ -35,6 +35,17 @@ define([ */ inputDateFormat: 'y-MM-dd', + /** + * Format of date that comes from the + * server (ICU Date Format). + * + * Used only in date/time picker mode + * (this.options.showsTime == false). + * + * @type {String} + */ + inputDateTimeFormat: 'y-MM-dd h:mm', + /** * Format of date that should be sent to the * server (ICU Date Format). @@ -46,6 +57,25 @@ define([ */ outputDateFormat: 'MM/dd/y', + /** + * Format of date that should be sent to the + * server (ICU Date Format). + * + * Used only in datetime picker mode with disabled ISO format. + * (this.options.showsTime == true, this.options.outputDateTimeToISO == false) + * + * @type {String} + */ + outputDateTimeFormat: '', + + /** + * Converts output date/time to ISO string + * + * Used only in datetime picker mode + * (this.options.showsTime == false) + */ + outputDateTimeToISO: true, + /** * Date/time format that is used to display date in * the input field. @@ -118,10 +148,20 @@ define([ shiftedValue; if (value) { + if (this.options.showsTime && !this.outputDateTimeToISO) { + dateFormat = this.shiftedValue() ? + this.outputDateTimeFormat : + this.inputDateTimeFormat; + + value = moment(value, dateFormat).format(this.timezoneFormat); + } + if (this.options.showsTime) { shiftedValue = moment.tz(value, 'UTC').tz(this.storeTimeZone); } else { - dateFormat = this.shiftedValue() ? this.outputDateFormat : this.inputDateFormat; + dateFormat = this.shiftedValue() ? + this.outputDateFormat : + this.inputDateFormat; shiftedValue = moment(value, dateFormat); } @@ -145,6 +185,7 @@ define([ onShiftedValueChange: function (shiftedValue) { var value, formattedValue, + formattedValueUTC, momentValue; if (shiftedValue) { @@ -152,7 +193,11 @@ define([ if (this.options.showsTime) { formattedValue = moment(momentValue).format(this.timezoneFormat); - value = moment.tz(formattedValue, this.storeTimeZone).tz('UTC').toISOString(); + formattedValueUTC = moment.tz(formattedValue, this.storeTimeZone).tz('UTC'); + + value = this.outputDateTimeToISO ? + formattedValueUTC.toISOString() : + formattedValueUTC.format(this.outputDateTimeFormat); } else { value = momentValue.format(this.outputDateFormat); } @@ -184,8 +229,8 @@ define([ this.inputDateFormat = utils.convertToMomentFormat(this.inputDateFormat); this.outputDateFormat = utils.convertToMomentFormat(this.outputDateFormat); - this.validationParams.dateFormat = this.outputDateFormat; + this.outputDateTimeFormat = this.options.outputDateTimeFormat || this.pickerDateTimeFormat; } }); }); diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/region.js b/app/code/Magento/Ui/view/base/web/js/form/element/region.js index 1b2ce8889af10..0edb4c1966b54 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/element/region.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/region.js @@ -35,6 +35,11 @@ define([ return; } option = options[value]; + + if (typeof option === 'undefined') { + return; + } + defaultPostCodeResolver.setUseDefaultPostCode(!option['is_zipcode_optional']); if (this.skipValidation) { diff --git a/app/code/Magento/Ui/view/base/web/js/form/element/wysiwyg.js b/app/code/Magento/Ui/view/base/web/js/form/element/wysiwyg.js index d0655a98d2586..b8cd4a0f2c892 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/element/wysiwyg.js +++ b/app/code/Magento/Ui/view/base/web/js/form/element/wysiwyg.js @@ -45,7 +45,8 @@ define([ component: this, selector: 'button' }, function (element) { - this.$wysiwygEditorButton = $(element); + this.$wysiwygEditorButton = this.$wysiwygEditorButton ? + this.$wysiwygEditorButton.add($(element)) : $(element); }.bind(this)); return this; @@ -94,7 +95,7 @@ define([ this.$wysiwygEditorButton.attr('disabled', status); /* eslint-disable no-undef */ - if (tinyMCE) { + if (tinyMCE && tinyMCE.activeEditor) { _.each(tinyMCE.activeEditor.controlManager.controls, function (property, index, controls) { controls[property.id].setDisabled(status); }); diff --git a/app/code/Magento/Ui/view/base/web/js/form/provider.js b/app/code/Magento/Ui/view/base/web/js/form/provider.js index f43c03e046f44..d070e23c708bb 100644 --- a/app/code/Magento/Ui/view/base/web/js/form/provider.js +++ b/app/code/Magento/Ui/view/base/web/js/form/provider.js @@ -21,6 +21,9 @@ define([ save: '${ $.submit_url }', beforeSave: '${ $.validate_url }' } + }, + ignoreTmpls: { + data: true } }, diff --git a/app/code/Magento/Ui/view/base/web/js/grid/columns/date.js b/app/code/Magento/Ui/view/base/web/js/grid/columns/date.js index 396ad3ce307ad..81c0cc1ccdbb7 100644 --- a/app/code/Magento/Ui/view/base/web/js/grid/columns/date.js +++ b/app/code/Magento/Ui/view/base/web/js/grid/columns/date.js @@ -39,7 +39,7 @@ define([ getLabel: function (value, format) { var date = moment(this._super()); - date = date.isValid() ? + date = date.isValid() && value[this.index] ? date.format(format || this.dateFormat) : ''; diff --git a/app/code/Magento/Ui/view/base/web/js/grid/provider.js b/app/code/Magento/Ui/view/base/web/js/grid/provider.js index 25bf25e6f65c0..2ba8bd73af910 100644 --- a/app/code/Magento/Ui/view/base/web/js/grid/provider.js +++ b/app/code/Magento/Ui/view/base/web/js/grid/provider.js @@ -31,6 +31,9 @@ define([ listens: { params: 'onParamsChange', requestConfig: 'updateRequestConfig' + }, + ignoreTmpls: { + data: true } }, diff --git a/app/code/Magento/Ui/view/base/web/js/lib/core/class.js b/app/code/Magento/Ui/view/base/web/js/lib/core/class.js index aae3ca31bf803..5bfa87e650271 100644 --- a/app/code/Magento/Ui/view/base/web/js/lib/core/class.js +++ b/app/code/Magento/Ui/view/base/web/js/lib/core/class.js @@ -27,12 +27,12 @@ define([ * Creates constructor function which allows * initialization without usage of a 'new' operator. * - * @param {Object} protoProps - Prototypal propeties of a new consturctor. - * @param {Function} consturctor - * @returns {Function} Created consturctor. + * @param {Object} protoProps - Prototypal properties of a new constructor. + * @param {Function} constructor + * @returns {Function} Created constructor. */ - function createConstructor(protoProps, consturctor) { - var UiClass = consturctor; + function createConstructor(protoProps, constructor) { + var UiClass = constructor; if (!UiClass) { @@ -61,7 +61,7 @@ define([ Class = createConstructor({ /** - * Entry point to the initialization of consturctors' instance. + * Entry point to the initialization of constructors' instance. * * @param {Object} [options={}] * @returns {Class} Chainable. diff --git a/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js b/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js index 01a1575541408..759f74b95e8e0 100644 --- a/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js +++ b/app/code/Magento/Ui/view/base/web/js/lib/validation/rules.js @@ -84,8 +84,10 @@ define([ ], 'range-words': [ function (value, params) { - return utils.stripHtml(value).match(/\b\w+\b/g).length >= params[0] && - value.match(/bw+b/g).length < params[1]; + var match = utils.stripHtml(value).match(/\b\w+\b/g) || []; + + return match.length >= params[0] && + match.length <= params[1]; }, $.mage.__('Please enter between {0} and {1} words.') ], @@ -907,8 +909,10 @@ define([ ], 'validate-item-quantity': [ function (value, params) { - // obtain values for validation - var qty = utils.parseNumber(value), + var validator = this, + result = false, + // obtain values for validation + qty = utils.parseNumber(value), isMinAllowedValid = typeof params.minAllowed === 'undefined' || qty >= utils.parseNumber(params.minAllowed), isMaxAllowedValid = typeof params.maxAllowed === 'undefined' || @@ -916,9 +920,42 @@ define([ isQtyIncrementsValid = typeof params.qtyIncrements === 'undefined' || qty % utils.parseNumber(params.qtyIncrements) === 0; - return isMaxAllowedValid && isMinAllowedValid && isQtyIncrementsValid && qty > 0; - }, - '' + result = qty > 0; + + if (result === false) { + validator.itemQtyErrorMessage = $.mage.__('Please enter a quantity greater than 0.');//eslint-disable-line max-len + + return result; + } + + result = isMinAllowedValid; + + if (result === false) { + validator.itemQtyErrorMessage = $.mage.__('The fewest you may purchase is %1.').replace('%1', params.minAllowed);//eslint-disable-line max-len + + return result; + } + + result = isMaxAllowedValid; + + if (result === false) { + validator.itemQtyErrorMessage = $.mage.__('The maximum you may purchase is %1.').replace('%1', params.maxAllowed);//eslint-disable-line max-len + + return result; + } + + result = isQtyIncrementsValid; + + if (result === false) { + validator.itemQtyErrorMessage = $.mage.__('You can buy this product only in quantities of %1 at a time.').replace('%1', params.qtyIncrements);//eslint-disable-line max-len + + return result; + } + + return result; + }, function () { + return this.itemQtyErrorMessage; + } ], 'equalTo': [ function (value, param) { diff --git a/app/code/Magento/Ui/view/base/web/templates/content/content.html b/app/code/Magento/Ui/view/base/web/templates/content/content.html index 8cf47120865dc..62e5959a02559 100644 --- a/app/code/Magento/Ui/view/base/web/templates/content/content.html +++ b/app/code/Magento/Ui/view/base/web/templates/content/content.html @@ -17,3 +17,5 @@
    + +