diff --git a/.browserslistrc b/.browserslistrc deleted file mode 100644 index 0152f61ef03..00000000000 --- a/.browserslistrc +++ /dev/null @@ -1 +0,0 @@ -extends @wordpress/browserslist-config diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 1670203f9f4..00000000000 --- a/.editorconfig +++ /dev/null @@ -1,18 +0,0 @@ -# WordPress Coding Standards -# https://make.wordpress.org/core/handbook/coding-standards/ - -root = true - -[*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true -trim_trailing_whitespace = true -indent_style = tab - -[{.babelrc,.eslintrc,.rtlcssrc,*.json,*.yml}] -indent_style = space -indent_size = 2 - -[*.md] -trim_trailing_whitespace = false diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 49a3b042518..00000000000 --- a/.eslintignore +++ /dev/null @@ -1,6 +0,0 @@ -**/*.min.js -**/node_modules/** -**/vendor/** -**/assets/js/*.js -!assets/js/amp-service-worker-runtime-precaching.js -build/* diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index bd0dde687f8..00000000000 --- a/.eslintrc +++ /dev/null @@ -1,132 +0,0 @@ -{ - "root": true, - "extends": [ - "plugin:@wordpress/eslint-plugin/recommended-with-formatting", - "plugin:import/recommended", - "plugin:eslint-comments/recommended" - ], - "env": { - "browser": true - }, - "rules": { - "block-scoped-var": "error", - "complexity": ["error", { "max": 20 } ], - "consistent-return": "error", - "default-case": "error", - "guard-for-in": "error", - "no-await-in-loop": "error", - "no-extra-bind": "error", - "no-extra-label": "error", - "no-floating-decimal": "error", - "no-implicit-coercion": "error", - "no-implicit-globals": "error", - "no-implied-eval": "error", - "no-loop-func": "error", - "no-new": "error", - "no-new-func": "error", - "no-new-wrappers": "error", - "no-restricted-properties": "error", - "no-return-assign": "error", - "no-return-await": "error", - "no-sequences": "error", - "no-shadow": "error", - "no-template-curly-in-string": "error", - "no-throw-literal": "error", - "no-unmodified-loop-condition": "error", - "no-unused-vars": [ - "error", - { - "ignoreRestSiblings": true - } - ], - "no-useless-call": "error", - "no-useless-concat": "error", - "prefer-object-spread": "error", - "prefer-promise-reject-errors": "error", - "prefer-rest-params": "error", - "prefer-spread": "error", - "radix": [ "error", "as-needed" ], - "require-await": "error", - "rest-spread-spacing": [ "error", "never" ], - "react/prop-types": "error", - "react-hooks/exhaustive-deps": [ "error", { "additionalHooks": "useSelect" } ], - "react/jsx-closing-tag-location": "error", - "react/jsx-fragments": "error", - "react/jsx-first-prop-new-line": "error", - "react/jsx-max-props-per-line": [ "error", { "when": "multiline" } ], - "react/jsx-no-literals": "error", - "react/jsx-no-useless-fragment": "error", - "react/jsx-one-expression-per-line": "error", - "react/no-unused-prop-types": "error", - "react/self-closing-comp": "error", - "import/no-unresolved": [ "error", { - "ignore": [ "jquery", "amp-block-editor-data", "amp-settings", "amp-themes", "amp-plugins", "amp-support", "amp-block-validation", "amp-site-scan-notice" ] - } ], - "import/order": [ "error", { "groups": [ "builtin", [ "external", "unknown" ], "internal", "parent", "sibling", "index" ] } ], - "jsdoc/check-indentation": "error", - "@wordpress/dependency-group": "error", - "@wordpress/react-no-unsafe-timeout": "error" - }, - "overrides": [ - { - "files":[ - "**/__tests__/**/*.js", - "**/test/*.js", - "**/?(*.)test.js", - "tests/js/**/*.js" - ], - "extends": [ - "plugin:jest/all" - ], - "rules": { - "jest/prefer-lowercase-title": [ - "error", - { - "ignore": [ "describe" ] - } - ], - "jest/no-hooks": "off", - "jest/prefer-expect-assertions": "off", - "jest/prefer-inline-snapshots": "off", - "jest/prefer-snapshot-hint": "off" - } - }, - { - "files": [ "tests/e2e/**/*.js" ], - "extends": [ - "plugin:@wordpress/eslint-plugin/test-e2e", - "plugin:jest/all" - ], - "rules": { - "jest/prefer-lowercase-title": [ - "error", - { - "ignore": [ "describe" ] - } - ], - "jest/no-hooks": "off", - "jest/prefer-expect-assertions": "off", - "jest/prefer-inline-snapshots": "off" - } - }, - { - "files": [ - "assets/src/mobile-redirection.js" - ], - "globals": { - "AMP_MOBILE_REDIRECTION": false, - "location": false, - "navigator": false, - "sessionStorage": false - } - }, - { - "files": [ - "assets/src/customizer/amp-customize-controls.js" - ], - "globals": { - "HTMLAnchorElement": false - } - } - ] -} diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 5d4880561be..00000000000 --- a/.gitattributes +++ /dev/null @@ -1,10 +0,0 @@ -# Improve diff output for PHP files. -*.php diff=php - -# Mark generated files so diffs are hidden by default. -*.snap linguist-generated=true -includes/sanitizers/class-amp-allowed-tags-generated.php linguist-generated=true -docs/**/*.md linguist-generated=true -docs/docs.json linguist-generated=true -**/__data__/*.js linguist-generated=true -includes/ecosystem-data/*.php linguist-generated=true diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 9ea11a6f61b..00000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: 🐛 Bug report -description: Create a report to help us improve. -labels: - - Bug - -body: - - type: textarea - attributes: - label: Bug Description - description: Please describe clearly and concisely what the bug is. - validations: - required: true - - - type: textarea - attributes: - label: Expected Behaviour - description: Please describe clearly and concisely what the expected behaviour should be. - validations: - required: true - - - type: textarea - attributes: - label: Screenshots - description: > - Please provide detailed steps on how to reproduce the bug. Provide a URL where the issue can be seen on the - frontend when possible, otherwise go to “View source” in the browser and copy all to paste in a - [Gist](https://gist.github.com/) and share it. - - - type: input - attributes: - label: PHP Version - description: Specify which PHP version the bug occurs on. - placeholder: e.g. 8.1 - validations: - required: false - - - type: input - attributes: - label: Plugin Version - description: Specify which plugin version the bug occurs on. - placeholder: e.g. 2.1.4 - validations: - required: true - - - type: dropdown - attributes: - label: AMP plugin template mode - description: Specify which template mode the bug occurs on. - multiple: true - options: - - Standard - - Transitional - - Reader - validations: - required: true - - - type: input - attributes: - label: WordPress Version - description: If applicable, specify which WordPress version the bug occurs on. - placeholder: e.g. 5.8 - - - type: textarea - attributes: - label: Site Health - description: > - If you would like to, please provide your Site Health information. You can also submit it privately via our - [AMP Plugin Escalations form](https://docs.google.com/forms/d/1JTQmphDlk9YgHpDoFRbHXpkDqv8-QmzTT7MDR4AstyQ). - - - type: input - attributes: - label: Gutenberg Version - description: If applicable, specify which Gutenberg version the bug occurs on. - placeholder: e.g. 11.2.1 - - - type: input - attributes: - label: OS(s) Affected - description: If applicable, specify which operating system(s) are affected. - placeholder: e.g. Windows, Android - - - type: input - attributes: - label: Browser(s) Affected - description: If applicable, specify which browser(s) are affected. - placeholder: e.g. Chrome, Firefox - - - type: input - attributes: - label: Device(s) Affected - description: If applicable, specify which device(s) are affected. - placeholder: e.g. iPhone 12, Pixel 5 - - - type: markdown - attributes: - value: | - --- - _**Do not alter anything below. The following fields will be managed by moderators only.**_ - - - type: textarea - attributes: - label: Acceptance Criteria - description: One or more bullet points for acceptance criteria. - - - type: textarea - attributes: - label: Implementation Brief - description: > - One or more bullet points for how to technically resolve the issue. For significant Implementation Design, - it is ok use a Google document **accessible by anyone**. - - - type: textarea - attributes: - label: QA Testing Instructions - description: One or more bullet points to describe how to test the implementation in QA. - - - type: textarea - attributes: - label: Demo - description: A video or screenshots demoing the implementation. - - - type: textarea - attributes: - label: Changelog Entry - description: One sentence summarizing the PR, to be used in the changelog. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index e39bc45f4b2..00000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,11 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: ❓ Plugin Support Forum - url: https://wordpress.org/support/plugin/amp/ - about: For plugin usage questions and compatibility issues with other plugins, please use the plugin's support forum. Before opening a new topic, please search the forum for existing topics as someone else has likely reported the issue already. - - name: ℹ️ AMP for WordPress - url: https://amp-wp.org/ - about: Find documentation, a showcase of sites using the official AMP plugin, an ecosystem directory of compatible themes/plugins, and a blog with news on the plugin site. - - name: 📺 Video Series - url: https://www.youtube.com/playlist?list=PLXTOW_XMsIDRGRr5QDffrvND8Qh1RndFb - about: Check out our video series on YouTube for an introduction to the plugin and how you can leverage it on your site. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index b7a710abdf5..00000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: ✨ Feature request -description: Suggest an idea for this project. -labels: - - Enhancement - -body: - - type: textarea - attributes: - label: Feature Description - description: > - Please describe clear and concisely which problem the feature would solve or which publisher needs - it would address. - validations: - required: true - - - type: markdown - attributes: - value: | - --- - _**Do not alter anything below. The following fields will be managed by moderators only.**_ - - - type: textarea - attributes: - label: Acceptance Criteria - description: One or more bullet points for acceptance criteria. - - - type: textarea - attributes: - label: Implementation Brief - description: > - One or more bullet points for how to technically resolve the issue. For significant Implementation Design, - it is ok use a Google document **accessible by anyone**. - - - type: textarea - attributes: - label: QA Testing Instructions - description: One or more bullet points to describe how to test the implementation in QA. - - - type: textarea - attributes: - label: Demo - description: A video or screenshots demoing the implementation. - - - type: textarea - attributes: - label: Changelog Entry - description: One sentence summarizing the PR, to be used in the changelog. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 4f08a8ff005..00000000000 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,9 +0,0 @@ -## Summary - - -Fixes # - -## Checklist - -- [ ] My code is tested and passes existing [tests](https://github.com/ampproject/amp-wp/wiki/Engineering-Guidelines#tests). -- [ ] My code follows the [Engineering Guidelines](https://github.com/ampproject/amp-wp/wiki/Engineering-Guidelines) (updates are often made to the guidelines, check it out periodically). diff --git a/.github/actions/draft-release/.eslintrc b/.github/actions/draft-release/.eslintrc deleted file mode 100644 index f7e10048984..00000000000 --- a/.github/actions/draft-release/.eslintrc +++ /dev/null @@ -1,23 +0,0 @@ -{ - "root": true, - "extends": [ - "airbnb", - "prettier" - ], - "env": { - "es6": true, - "node": true - }, - "rules": { - "prettier/prettier": [ - "error", - { - "singleQuote": true, - "printWidth": 120 - } - ] - }, - "plugins": [ - "prettier" - ] -} diff --git a/.github/actions/draft-release/.gitattributes b/.github/actions/draft-release/.gitattributes deleted file mode 100644 index fd1b52eb044..00000000000 --- a/.github/actions/draft-release/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Mark generated files so diffs are hidden by default. -dist/index.js linguist-generated=true diff --git a/.github/actions/draft-release/README.md b/.github/actions/draft-release/README.md deleted file mode 100644 index f4f317dafbc..00000000000 --- a/.github/actions/draft-release/README.md +++ /dev/null @@ -1,25 +0,0 @@ -# Draft release action - -This action drafts a release for the specified milestone and release branch. - -## Inputs - -### `milestone` - -**Required** Milestone name. - -## Outputs - -### `asset_upload_url` - -The URL for uploading assets to the release. - -## Example usage - -```yaml -uses: ./.github/actions/draft-release -env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -with: - milestone: v3.2.1 -``` diff --git a/.github/actions/draft-release/action.yml b/.github/actions/draft-release/action.yml deleted file mode 100644 index bde8b1394b3..00000000000 --- a/.github/actions/draft-release/action.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: 'Draft release' -description: 'Drafts a release based on the specified milestone' -inputs: - milestone: - description: 'Milestone name' - required: true - release_branch: - description: 'Release branch name' - required: true -outputs: - asset_upload_url: - description: 'The URL for uploading assets to the release' -runs: - using: 'node12' - main: 'dist/index.js' diff --git a/.github/actions/draft-release/dist/index.js b/.github/actions/draft-release/dist/index.js deleted file mode 100644 index 3353a60e148..00000000000 --- a/.github/actions/draft-release/dist/index.js +++ /dev/null @@ -1,32863 +0,0 @@ -module.exports = -/******/ (function(modules, runtime) { // webpackBootstrap -/******/ "use strict"; -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete installedModules[moduleId]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ __webpack_require__.ab = __dirname + "/"; -/******/ -/******/ // the startup function -/******/ function startup() { -/******/ // Load entry module and return exports -/******/ return __webpack_require__(676); -/******/ }; -/******/ // initialize runtime -/******/ runtime(__webpack_require__); -/******/ -/******/ // run startup -/******/ return startup(); -/******/ }) -/************************************************************************/ -/******/ ({ - -/***/ 4: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -var BOMChar = '\uFEFF'; - -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} - -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } - - return this.encoder.write(str); -} - -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} - - -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} - -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; - - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } - - this.pass = true; - return res; -} - -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} - - - -/***/ }), - -/***/ 6: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var deprecation = __webpack_require__(310); -var once = _interopDefault(__webpack_require__(661)); - -const logOnceCode = once(deprecation => console.warn(deprecation)); -const logOnceHeaders = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = "HttpError"; - this.status = statusCode; - let headers; - - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; - } // redact request credentials without mutating original request options - - - const requestCopy = Object.assign({}, options.request); - - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") - }); - } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; // deprecations - - Object.defineProperty(this, "code", { - get() { - logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - Object.defineProperty(this, "headers", { - get() { - logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); - return headers || {}; - } - - }); - } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 7: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var endpoint = __webpack_require__(655); -var universalUserAgent = __webpack_require__(323); -var isPlainObject = __webpack_require__(999); -var nodeFetch = _interopDefault(__webpack_require__(149)); -var requestError = __webpack_require__(6); - -const VERSION = "5.6.1"; - -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -function fetchWrapper(requestOptions) { - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - - if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - - let headers = {}; - let status; - let url; - const fetch = requestOptions.request && requestOptions.request.fetch || nodeFetch; - return fetch(requestOptions.url, Object.assign({ - method: requestOptions.method, - body: requestOptions.body, - headers: requestOptions.headers, - redirect: requestOptions.redirect - }, // `requestOptions.request.agent` type is incompatible - // see https://github.com/octokit/types.ts/pull/264 - requestOptions.request)).then(async response => { - url = response.url; - status = response.status; - - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - - if ("deprecation" in headers) { - const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn(`[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}`); - } - - if (status === 204 || status === 205) { - return; - } // GitHub API returns 200 for HEAD requests - - - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - - throw new requestError.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: undefined - }, - request: requestOptions - }); - } - - if (status === 304) { - throw new requestError.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - - if (status >= 400) { - const data = await getResponseData(response); - const error = new requestError.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - - return getResponseData(response); - }).then(data => { - return { - status, - url, - headers, - data - }; - }).catch(error => { - if (error instanceof requestError.RequestError) throw error; - throw new requestError.RequestError(error.message, 500, { - request: requestOptions - }); - }); -} - -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - - if (/application\/json/.test(contentType)) { - return response.json(); - } - - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } - - return getBufferResponse(response); -} - -function toErrorMessage(data) { - if (typeof data === "string") return data; // istanbul ignore else - just in case - - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; - } - - return data.message; - } // istanbul ignore next - just in case - - - return `Unknown error: ${JSON.stringify(data)}`; -} - -function withDefaults(oldEndpoint, newDefaults) { - const endpoint = oldEndpoint.defaults(newDefaults); - - const newApi = function (route, parameters) { - const endpointOptions = endpoint.merge(route, parameters); - - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint.parse(endpointOptions)); - } - - const request = (route, parameters) => { - return fetchWrapper(endpoint.parse(endpoint.merge(route, parameters))); - }; - - Object.assign(request, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); - return endpointOptions.request.hook(request, endpointOptions); - }; - - return Object.assign(newApi, { - endpoint, - defaults: withDefaults.bind(null, endpoint) - }); -} - -const request = withDefaults(endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } -}); - -exports.request = request; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 11: -/***/ (function(module) { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), - -/***/ 16: -/***/ (function(module) { - -module.exports = require("tls"); - -/***/ }), - -/***/ 17: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; - if (checkBypass(reqUrl)) { - return proxyUrl; - } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); - } - return proxyUrl; -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (let upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; - - -/***/ }), - -/***/ 21: -/***/ (function(module) { - -"use strict"; - - -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} - -/***/ }), - -/***/ 49: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var wrappy = __webpack_require__(11) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), - -/***/ 68: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; - - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; -} - -exports.isPlainObject = isPlainObject; - - -/***/ }), - -/***/ 82: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 87: -/***/ (function(module) { - -module.exports = require("os"); - -/***/ }), - -/***/ 102: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -// For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.issueCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__webpack_require__(747)); -const os = __importStar(__webpack_require__(87)); -const utils_1 = __webpack_require__(82); -function issueCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueCommand = issueCommand; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 115: -/***/ (function(module) { - -module.exports = {"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]}; - -/***/ }), - -/***/ 123: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -const Endpoints = { - actions: { - addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - approveWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve"], - cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], - createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], - createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], - createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], - deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], - deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"], - disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"], - downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], - downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], - downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"], - enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"], - getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], - getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"], - getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], - getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], - getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { - renamed: ["actions", "getGithubActionsPermissionsRepository"] - }], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], - getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"], - listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], - listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], - listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], - listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], - setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"], - setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"], - setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], - setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], - setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], - setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], - checkToken: ["POST /applications/{client_id}/token"], - createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createContentAttachmentForRepo: ["POST /repos/{owner}/{repo}/content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], - getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], - listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: ["POST /app/hook/deliveries/{delivery_id}/attempts"], - removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], - getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], - getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], - setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"], - getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { - renamedParameters: { - alert_id: "alert_number" - } - }], - getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", {}, { - renamed: ["codeScanning", "listAlertInstances"] - }], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"], - getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] - } - }] - }, - emojis: { - get: ["GET /emojis"] - }, - enterpriseAdmin: { - disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], - getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], - listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], - setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], - setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], - setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] - }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, { - renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] - }], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"], - removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, { - renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] - }], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, { - renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] - }] - }, - issues: { - addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: ["POST /repos/{owner}/{repo}/issues/{issue_number}/comments"], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}"], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: ["DELETE /repos/{owner}/{repo}/milestones/{milestone_number}"], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: ["GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", { - mediaType: { - previews: ["mockingbird"] - } - }], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels"], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/labels"], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels"], - removeAssignees: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees"], - removeLabel: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}"], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: ["PATCH /repos/{owner}/{repo}/milestones/{milestone_number}"] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: ["POST /markdown/raw", { - headers: { - "content-type": "text/plain; charset=utf-8" - } - }] - }, - meta: { - get: ["GET /meta"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: ["DELETE /repos/{owner}/{repo}/import"], - deleteArchiveForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - deleteArchiveForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - downloadArchiveForOrg: ["GET /orgs/{org}/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getArchiveForAuthenticatedUser: ["GET /user/migrations/{migration_id}/archive", { - mediaType: { - previews: ["wyandotte"] - } - }], - getCommitAuthors: ["GET /repos/{owner}/{repo}/import/authors"], - getImportStatus: ["GET /repos/{owner}/{repo}/import"], - getLargeFiles: ["GET /repos/{owner}/{repo}/import/large_files"], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForAuthenticatedUser: ["GET /user/migrations", { - mediaType: { - previews: ["wyandotte"] - } - }], - listForOrg: ["GET /orgs/{org}/migrations", { - mediaType: { - previews: ["wyandotte"] - } - }], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] - } - }], - listReposForUser: ["GET /user/migrations/{migration_id}/repositories", { - mediaType: { - previews: ["wyandotte"] - } - }], - mapCommitAuthor: ["PATCH /repos/{owner}/{repo}/import/authors/{author_id}"], - setLfsPreference: ["PATCH /repos/{owner}/{repo}/import/lfs"], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: ["PUT /repos/{owner}/{repo}/import"], - unlockRepoForAuthenticatedUser: ["DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - unlockRepoForOrg: ["DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock", { - mediaType: { - previews: ["wyandotte"] - } - }], - updateImport: ["PATCH /repos/{owner}/{repo}/import"] - }, - orgs: { - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: ["PUT /orgs/{org}/outside_collaborators/{username}"], - createInvitation: ["POST /orgs/{org}/invitations"], - createWebhook: ["POST /orgs/{org}/hooks"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - get: ["GET /orgs/{org}"], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: ["GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}"], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: ["POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: ["DELETE /orgs/{org}/outside_collaborators/{username}"], - removePublicMembershipForAuthenticatedUser: ["DELETE /orgs/{org}/public_members/{username}"], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: ["PUT /orgs/{org}/public_members/{username}"], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: ["PATCH /user/memberships/orgs/{org}"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"], - deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"], - deletePackageForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}"], - deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - deletePackageVersionForUser: ["DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] - }], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, { - renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"] - }], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"], - getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"], - getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"], - getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"], - getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"], - getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /user/{username}/packages"], - restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}"], - restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], - restorePackageVersionForUser: ["POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - createCard: ["POST /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - createColumn: ["POST /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - createForAuthenticatedUser: ["POST /user/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForOrg: ["POST /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - createForRepo: ["POST /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - delete: ["DELETE /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteCard: ["DELETE /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - deleteColumn: ["DELETE /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - get: ["GET /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getCard: ["GET /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getColumn: ["GET /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }], - getPermissionForUser: ["GET /projects/{project_id}/collaborators/{username}/permission", { - mediaType: { - previews: ["inertia"] - } - }], - listCards: ["GET /projects/columns/{column_id}/cards", { - mediaType: { - previews: ["inertia"] - } - }], - listCollaborators: ["GET /projects/{project_id}/collaborators", { - mediaType: { - previews: ["inertia"] - } - }], - listColumns: ["GET /projects/{project_id}/columns", { - mediaType: { - previews: ["inertia"] - } - }], - listForOrg: ["GET /orgs/{org}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForRepo: ["GET /repos/{owner}/{repo}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listForUser: ["GET /users/{username}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - moveCard: ["POST /projects/columns/cards/{card_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - moveColumn: ["POST /projects/columns/{column_id}/moves", { - mediaType: { - previews: ["inertia"] - } - }], - removeCollaborator: ["DELETE /projects/{project_id}/collaborators/{username}", { - mediaType: { - previews: ["inertia"] - } - }], - update: ["PATCH /projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateCard: ["PATCH /projects/columns/cards/{card_id}", { - mediaType: { - previews: ["inertia"] - } - }], - updateColumn: ["PATCH /projects/columns/{column_id}", { - mediaType: { - previews: ["inertia"] - } - }] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies"], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - deletePendingReview: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - deleteReviewComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - dismissReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals"], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments"], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - listReviewComments: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/comments"], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: ["DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - requestReviewers: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers"], - submitReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events"], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch", { - mediaType: { - previews: ["lydian"] - } - }], - updateReview: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}"], - updateReviewComment: ["PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}"] - }, - rateLimit: { - get: ["GET /rate_limit"] - }, - reactions: { - createForCommitComment: ["POST /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssue: ["POST /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForIssueComment: ["POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForPullRequestReviewComment: ["POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForRelease: ["POST /repos/{owner}/{repo}/releases/{release_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - createForTeamDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssue: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForIssueComment: ["DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForPullRequestComment: ["DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussion: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteForTeamDiscussionComment: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - deleteLegacy: ["DELETE /reactions/{reaction_id}", { - mediaType: { - previews: ["squirrel-girl"] - } - }, { - deprecated: "octokit.rest.reactions.deleteLegacy() is deprecated, see https://docs.github.com/rest/reference/reactions/#delete-a-reaction-legacy" - }], - listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForIssueComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForPullRequestReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }], - listForTeamDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", { - mediaType: { - previews: ["squirrel-girl"] - } - }] - }, - repos: { - acceptInvitation: ["PATCH /user/repository_invitations/{invitation_id}"], - addAppAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - addTeamAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - addUserAccessRestrictions: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: ["GET /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: ["GET /repos/{owner}/{repo}/compare/{basehead}"], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: ["POST /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - createCommitSignatureProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentStatus: ["POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createUsingTemplate: ["POST /repos/{template_owner}/{template_repo}/generate", { - mediaType: { - previews: ["baptiste"] - } - }], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: ["DELETE /user/repository_invitations/{invitation_id}"], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: ["DELETE /repos/{owner}/{repo}/deployments/{deployment_id}"], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: ["DELETE /repos/{owner}/{repo}/invitations/{invitation_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages", { - mediaType: { - previews: ["switcheroo"] - } - }], - deletePullRequestReviewProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: ["DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: ["DELETE /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - disableVulnerabilityAlerts: ["DELETE /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - downloadArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}", {}, { - renamed: ["repos", "downloadZipballArchive"] - }], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: ["PUT /repos/{owner}/{repo}/automated-security-fixes", { - mediaType: { - previews: ["london"] - } - }], - enableVulnerabilityAlerts: ["PUT /repos/{owner}/{repo}/vulnerability-alerts", { - mediaType: { - previews: ["dorian"] - } - }], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], - getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], - getAllTopics: ["GET /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - getAppsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps"], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: ["GET /repos/{owner}/{repo}/collaborators/{username}/permission"], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { - mediaType: { - previews: ["zzzax"] - } - }], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], - getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getStatusChecksProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - getTeamsWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams"], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users"], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/config"], - getWebhookDelivery: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", { - mediaType: { - previews: ["groot"] - } - }], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/comments"], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/statuses"], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentStatuses: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses"], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: ["GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", { - mediaType: { - previews: ["groot"] - } - }], - listReleaseAssets: ["GET /repos/{owner}/{repo}/releases/{release_id}/assets"], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: ["GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts"], - removeAppAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - removeCollaborator: ["DELETE /repos/{owner}/{repo}/collaborators/{username}"], - removeStatusCheckContexts: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - removeStatusCheckProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - removeTeamAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { - mediaType: { - previews: ["mercy"] - } - }], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: ["POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], - setAppAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", {}, { - mapToData: "apps" - }], - setStatusCheckContexts: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", {}, { - mapToData: "contexts" - }], - setTeamAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", {}, { - mapToData: "teams" - }], - setUserAccessRestrictions: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { - mapToData: "users" - }], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: ["PUT /repos/{owner}/{repo}/branches/{branch}/protection"], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: ["PATCH /repos/{owner}/{repo}/invitations/{invitation_id}"], - updatePullRequestReviewProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: ["PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}"], - updateStatusCheckPotection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", {}, { - renamed: ["repos", "updateStatusCheckProtection"] - }], - updateStatusCheckProtection: ["PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks"], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config"], - uploadReleaseAsset: ["POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", { - baseUrl: "https://uploads.github.com" - }] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits", { - mediaType: { - previews: ["cloak"] - } - }], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics", { - mediaType: { - previews: ["mercy"] - } - }], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: ["GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - updateAlert: ["PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}"] - }, - teams: { - addOrUpdateMembershipForUserInOrg: ["PUT /orgs/{org}/teams/{team_slug}/memberships/{username}"], - addOrUpdateProjectPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - addOrUpdateRepoPermissionsInOrg: ["PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - checkPermissionsForProjectInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects/{project_id}", { - mediaType: { - previews: ["inertia"] - } - }], - checkPermissionsForRepoInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - deleteDiscussionInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - getDiscussionInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - getMembershipForUserInOrg: ["GET /orgs/{org}/teams/{team_slug}/memberships/{username}"], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments"], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: ["GET /orgs/{org}/teams/{team_slug}/invitations"], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects", { - mediaType: { - previews: ["inertia"] - } - }], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}"], - removeProjectInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}"], - removeRepoInOrg: ["DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}"], - updateDiscussionCommentInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}"], - updateDiscussionInOrg: ["PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}"], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: ["POST /user/emails"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: ["POST /user/keys"], - deleteEmailForAuthenticated: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: ["DELETE /user/keys/{key_id}"], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: ["GET /user/keys/{key_id}"], - list: ["GET /users"], - listBlockedByAuthenticated: ["GET /user/blocks"], - listEmailsForAuthenticated: ["GET /user/emails"], - listFollowedByAuthenticated: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: ["GET /user/keys"], - setPrimaryEmailVisibilityForAuthenticated: ["PATCH /user/email/visibility"], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; - -const VERSION = "5.10.4"; - -function endpointsToMethods(octokit, endpointsMap) { - const newMethods = {}; - - for (const [scope, endpoints] of Object.entries(endpointsMap)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign({ - method, - url - }, defaults); - - if (!newMethods[scope]) { - newMethods[scope] = {}; - } - - const scopeMethods = newMethods[scope]; - - if (decorations) { - scopeMethods[methodName] = decorate(octokit, scope, methodName, endpointDefaults, decorations); - continue; - } - - scopeMethods[methodName] = octokit.request.defaults(endpointDefaults); - } - } - - return newMethods; -} - -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - /* istanbul ignore next */ - - function withDecorations(...args) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - let options = requestWithDefaults.endpoint.merge(...args); // There are currently no other decorations than `.mapToData` - - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: undefined - }); - return requestWithDefaults(options); - } - - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn(`octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`); - } - - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - - if (decorations.renamedParameters) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - const options = requestWithDefaults.endpoint.merge(...args); - - for (const [name, alias] of Object.entries(decorations.renamedParameters)) { - if (name in options) { - octokit.log.warn(`"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead`); - - if (!(alias in options)) { - options[alias] = options[name]; - } - - delete options[name]; - } - } - - return requestWithDefaults(options); - } // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488 - - - return requestWithDefaults(...args); - } - - return Object.assign(withDecorations, requestWithDefaults); -} - -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit, Endpoints); - return _objectSpread2(_objectSpread2({}, api), {}, { - rest: api - }); -} -legacyRestEndpointMethods.VERSION = VERSION; - -exports.legacyRestEndpointMethods = legacyRestEndpointMethods; -exports.restEndpointMethods = restEndpointMethods; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 127: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__webpack_require__(539)); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; -} -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 141: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -var net = __webpack_require__(631); -var tls = __webpack_require__(16); -var http = __webpack_require__(605); -var https = __webpack_require__(211); -var events = __webpack_require__(614); -var assert = __webpack_require__(357); -var util = __webpack_require__(669); - - -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - - -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; - - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); - -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } - - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); - - function onFree() { - self.emit('free', socket, options); - } - - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); - } - }); -}; - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port - } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); - } - - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } - - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); - - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - - function onError(cause) { - connectReq.removeAllListeners(); - - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } -}; - -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); - - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; - -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); - - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} - - -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} - -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} - - -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); - } -} else { - debug = function() {}; -} -exports.debug = debug; // for test - - -/***/ }), - -/***/ 149: -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__webpack_require__(794)); -var http = _interopDefault(__webpack_require__(605)); -var Url = _interopDefault(__webpack_require__(835)); -var https = _interopDefault(__webpack_require__(211)); -var zlib = _interopDefault(__webpack_require__(761)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); - - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} - -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); - -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ - -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); - - this.message = message; - this.type = type; - - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = __webpack_require__(203).convert; -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; - -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } - - this[INTERNALS].disturbed = true; - - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; - - return new Body.Promise(function (resolve, reject) { - let resTimeout; - - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } - - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } - - accumBytes += chunk.length; - accum.push(chunk); - }); - - body.on('end', function () { - if (abort) { - return; - } - - clearTimeout(resTimeout); - - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} - -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} - -const INTERNAL = Symbol('internal'); - -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} - -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } - - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; -} - -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; - -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); - -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); - -const INTERNALS$2 = Symbol('Request internals'); - -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} - -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parse_url(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parse_url(`${input}`); - } - input = {}; - } else { - parsedURL = parse_url(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } - - get redirect() { - return this[INTERNALS$2].redirect; - } - - get signal() { - return this[INTERNALS$2].signal; - } - - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} - -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} - -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ - -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); - - this.type = 'aborted'; - this.message = message; - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; - -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; -const resolve_url = Url.resolve; - -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - - Body.Promise = fetch.Promise; - - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); - - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - - let response = null; - - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - - // send request - const req = send(options); - let reqTimeout; - - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } - - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } - - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } - - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); - }); - - req.on('response', function (res) { - clearTimeout(reqTimeout); - - const headers = createHeadersLenient(res.headers); - - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); - - // HTTP fetch step 5.3 - const locationURL = location === null ? null : resolve_url(request.url, location); - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; - - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } - - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } - - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); - - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; - - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); - - // HTTP-network fetch step 12.1.1.4: handle content codings - - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } - - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; - - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } - - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - return; - } - - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } - - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); - - writeToStream(req, request); - }); -} -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; - -// expose Promise -fetch.Promise = global.Promise; - -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; - - -/***/ }), - -/***/ 171: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var register = __webpack_require__(494) -var addHook = __webpack_require__(351) -var removeHook = __webpack_require__(824) - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) - -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef - - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} - -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} - -function HookCollection () { - var state = { - registry: {} - } - - var hook = register.bind(null, state) - bindApi(hook, state) - - return hook -} - -var collectionHookDeprecationMessageDisplayed = false -function Hook () { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true - } - return HookCollection() -} - -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() - -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection - - -/***/ }), - -/***/ 182: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -const VERSION = "2.16.3"; - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ -function normalizePaginatedListResponse(response) { - // endpoints can respond with 204 if repository is empty - if (!response.data) { - return _objectSpread2(_objectSpread2({}, response), {}, { - data: [] - }); - } - - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - - response.data.total_count = totalCount; - return response; -} - -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) return { - done: true - }; - - try { - const response = await requestMethod({ - method, - url, - headers - }); - const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set - - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; - } catch (error) { - if (error.status !== 409) throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - - }) - }; -} - -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; - } - - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); -} - -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { - if (result.done) { - return results; - } - - let earlyExit = false; - - function done() { - earlyExit = true; - } - - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - - if (earlyExit) { - return results; - } - - return gather(octokit, results, iterator, mapFn); - }); -} - -const composePaginateRest = Object.assign(paginate, { - iterator -}); - -const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/packages", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/secret-scanning/alerts", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/autolinks", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/packages", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /user/{username}/packages", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; - -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } -} - -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; - -exports.composePaginateRest = composePaginateRest; -exports.isPaginatingEndpoint = isPaginatingEndpoint; -exports.paginateRest = paginateRest; -exports.paginatingEndpoints = paginatingEndpoints; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 203: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var iconvLite = __webpack_require__(997); - -// Expose to the world -module.exports.convert = convert; - -/** - * Convert encoding of an UTF-8 string or a buffer - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convert(str, to, from) { - from = checkEncoding(from || 'UTF-8'); - to = checkEncoding(to || 'UTF-8'); - str = str || ''; - - var result; - - if (from !== 'UTF-8' && typeof str === 'string') { - str = Buffer.from(str, 'binary'); - } - - if (from === to) { - if (typeof str === 'string') { - result = Buffer.from(str); - } else { - result = str; - } - } else { - try { - result = convertIconvLite(str, to, from); - } catch (E) { - console.error(E); - result = str; - } - } - - if (typeof result === 'string') { - result = Buffer.from(result, 'utf-8'); - } - - return result; -} - -/** - * Convert encoding of astring with iconv-lite - * - * @param {String|Buffer} str String to be converted - * @param {String} to Encoding to be converted to - * @param {String} [from='UTF-8'] Encoding to be converted from - * @return {Buffer} Encoded string - */ -function convertIconvLite(str, to, from) { - if (to === 'UTF-8') { - return iconvLite.decode(str, from); - } else if (from === 'UTF-8') { - return iconvLite.encode(str, to); - } else { - return iconvLite.encode(iconvLite.decode(str, from), to); - } -} - -/** - * Converts charset name if needed - * - * @param {String} name Character set - * @return {String} Character set name - */ -function checkEncoding(name) { - return (name || '') - .toString() - .trim() - .replace(/^latin[\-_]?(\d+)$/i, 'ISO-8859-$1') - .replace(/^win(?:dows)?[\-_]?(\d+)$/i, 'WINDOWS-$1') - .replace(/^utf[\-_]?(\d+)$/i, 'UTF-$1') - .replace(/^ks_c_5601\-1987$/i, 'CP949') - .replace(/^us[\-_]?ascii$/i, 'ASCII') - .toUpperCase(); -} - - -/***/ }), - -/***/ 211: -/***/ (function(module) { - -module.exports = require("https"); - -/***/ }), - -/***/ 214: -/***/ (function(module) { - -module.exports = [["0","\u0000",127],["8ea1","。",62],["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"],["a2a1","◆□■△▲▽▼※〒→←↑↓〓"],["a2ba","∈∋⊆⊇⊂⊃∪∩"],["a2ca","∧∨¬⇒⇔∀∃"],["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["a2f2","ʼn♯♭♪†‡¶"],["a2fe","◯"],["a3b0","0",9],["a3c1","A",25],["a3e1","a",25],["a4a1","ぁ",82],["a5a1","ァ",85],["a6a1","Α",16,"Σ",6],["a6c1","α",16,"σ",6],["a7a1","А",5,"ЁЖ",25],["a7d1","а",5,"ёж",25],["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["ada1","①",19,"Ⅰ",9],["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"],["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"],["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"],["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"],["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"],["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"],["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"],["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"],["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"],["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"],["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"],["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"],["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"],["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"],["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"],["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"],["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"],["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"],["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"],["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"],["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"],["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"],["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"],["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"],["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"],["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"],["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"],["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"],["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"],["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"],["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"],["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"],["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"],["f4a1","堯槇遙瑤凜熙"],["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"],["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"],["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["fcf1","ⅰ",9,"¬¦'""],["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"],["8fa2c2","¡¦¿"],["8fa2eb","ºª©®™¤№"],["8fa6e1","ΆΈΉΊΪ"],["8fa6e7","Ό"],["8fa6e9","ΎΫ"],["8fa6ec","Ώ"],["8fa6f1","άέήίϊΐόςύϋΰώ"],["8fa7c2","Ђ",10,"ЎЏ"],["8fa7f2","ђ",10,"ўџ"],["8fa9a1","ÆĐ"],["8fa9a4","Ħ"],["8fa9a6","IJ"],["8fa9a8","ŁĿ"],["8fa9ab","ŊØŒ"],["8fa9af","ŦÞ"],["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"],["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"],["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"],["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"],["8fabbd","ġĥíìïîǐ"],["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"],["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"],["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"],["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"],["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"],["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"],["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"],["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"],["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"],["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"],["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"],["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"],["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"],["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"],["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"],["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"],["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"],["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"],["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"],["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"],["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"],["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"],["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"],["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"],["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"],["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"],["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"],["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"],["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"],["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"],["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"],["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"],["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"],["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"],["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"],["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5],["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"],["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"],["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"],["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"],["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"],["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"],["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"],["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"],["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"],["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"],["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"],["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"],["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"],["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"],["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"],["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"],["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"],["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"],["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"],["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"],["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"],["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"],["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4],["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"],["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"],["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"],["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"]]; - -/***/ }), - -/***/ 262: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Context = void 0; -const fs_1 = __webpack_require__(747); -const os_1 = __webpack_require__(87); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if (fs_1.existsSync(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse(fs_1.readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } -} -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 269: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -var request = __webpack_require__(7); -var universalUserAgent = __webpack_require__(323); - -const VERSION = "4.8.0"; - -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors:\n` + data.errors.map(e => ` - ${e.message}`).join("\n"); -} - -class GraphqlResponseError extends Error { - constructor(request, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; // Expose the errors and response data in their shorthand properties. - - this.errors = response.errors; - this.data = response.data; // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - -} - -const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; -const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject(new Error(`[@octokit/graphql] "query" cannot be used as variable name`)); - } - - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject(new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`)); - } - } - - const parsedOptions = typeof query === "string" ? Object.assign({ - query - }, options) : query; - const requestOptions = Object.keys(parsedOptions).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - - if (!result.variables) { - result.variables = {}; - } - - result.variables[key] = parsedOptions[key]; - return result; - }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix - // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 - - const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; - - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - - return request(requestOptions).then(response => { - if (response.data.errors) { - const headers = {}; - - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - - throw new GraphqlResponseError(requestOptions, headers, response.data); - } - - return response.data.data; - }); -} - -function withDefaults(request$1, newDefaults) { - const newRequest = request$1.defaults(newDefaults); - - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: request.request.endpoint - }); -} - -const graphql$1 = withDefaults(request.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); -} - -exports.GraphqlResponseError = GraphqlResponseError; -exports.graphql = graphql$1; -exports.withCustomRequest = withCustomRequest; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 280: -/***/ (function(module) { - -module.exports = register; - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - - -/***/ }), - -/***/ 289: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var Buffer = __webpack_require__(572).Buffer; - -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). - -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } - - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; - - this.encodeBuf = encodeBuf; -} - -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; - - -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} - -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} - -SBCSEncoder.prototype.end = function() { -} - - -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} - -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); -} - -SBCSDecoder.prototype.end = function() { -} - - -/***/ }), - -/***/ 293: -/***/ (function(module) { - -module.exports = require("buffer"); - -/***/ }), - -/***/ 299: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -const VERSION = "2.13.5"; - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - - if (enumerableOnly) { - symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - } - - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ -function normalizePaginatedListResponse(response) { - // endpoints can respond with 204 if repository is empty - if (!response.data) { - return _objectSpread2(_objectSpread2({}, response), {}, { - data: [] - }); - } - - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - - response.data.total_count = totalCount; - return response; -} - -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) return { - done: true - }; - - try { - const response = await requestMethod({ - method, - url, - headers - }); - const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set - - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; - } catch (error) { - if (error.status !== 409) throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - - }) - }; -} - -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; - } - - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); -} - -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { - if (result.done) { - return results; - } - - let earlyExit = false; - - function done() { - earlyExit = true; - } - - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); - - if (earlyExit) { - return results; - } - - return gather(octokit, results, iterator, mapFn); - }); -} - -const composePaginateRest = Object.assign(paginate, { - iterator -}); - -const paginatingEndpoints = ["GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; - -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } -} - -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ - -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; - -exports.composePaginateRest = composePaginateRest; -exports.isPaginatingEndpoint = isPaginatingEndpoint; -exports.paginateRest = paginateRest; -exports.paginatingEndpoints = paginatingEndpoints; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 304: -/***/ (function(module) { - -module.exports = require("string_decoder"); - -/***/ }), - -/***/ 310: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'Deprecation'; - } - -} - -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 323: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - - return ""; -} - -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 351: -/***/ (function(module) { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} - - -/***/ }), - -/***/ 353: -/***/ (function(__unusedmodule, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony reexport (default from non-harmony) */ __webpack_require__.d(__webpack_exports__, "makeRelease", function() { return _make_release__WEBPACK_IMPORTED_MODULE_0___default.a; }); -/* harmony import */ var _make_release__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(911); -/* harmony import */ var _make_release__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_make_release__WEBPACK_IMPORTED_MODULE_0__); -// eslint-disable-next-line import/prefer-default-export - - - -/***/ }), - -/***/ 354: -/***/ (function(module, __unusedexports, __webpack_require__) { - -/** - * External dependencies - */ -const _ = __webpack_require__( 682 ); - -/** - * Utility function to paginate a GraphQL function using Relay-style cursor pagination. - * - * Adapted from https://github.com/release-drafter/release-drafter/blob/8cf80318bad9d4877359714d6b5699662cc2597f/lib/pagination.js. - * - * @param {Function} queryFn Function used to query the GraphQL API. - * @param {string} query GraphQL query, must include `nodes` and `pageInfo` fields for the field that will be paginated. - * @param {Object} variables GraphQL Query variables. - * @param {string[]} paginatePath Path to field to paginate. - */ -async function paginateByPath( queryFn, query, variables, paginatePath ) { - const nodesPath = [ ...paginatePath, 'nodes' ]; - const pageInfoPath = [ ...paginatePath, 'pageInfo' ]; - const endCursorPath = [ ...pageInfoPath, 'endCursor' ]; - const hasNextPagePath = [ ...pageInfoPath, 'hasNextPage' ]; - const hasNextPage = ( data ) => _.get( data, hasNextPagePath ); - - const data = await queryFn( query, variables ); - - if ( ! _.has( data, nodesPath ) ) { - throw new Error( - "Data doesn't contain `nodes` field. Make sure the `paginatePath` is set to the field you wish to paginate and that the query includes the `nodes` field.", - ); - } - - if ( ! _.has( data, pageInfoPath ) || ! _.has( data, endCursorPath ) || ! _.has( data, hasNextPagePath ) ) { - throw new Error( - "Data doesn't contain `pageInfo` field with `endCursor` and `hasNextPage` fields. Make sure the `paginatePath` is set to the field you wish to paginate and that the query includes the `pageInfo` field.", - ); - } - - while ( hasNextPage( data ) ) { - // eslint-disable-next-line no-await-in-loop - const newData = await queryFn( query, { - ...variables, - after: _.get( data, [ ...pageInfoPath, 'endCursor' ] ), - } ); - const newNodes = _.get( newData, nodesPath ); - const newPageInfo = _.get( newData, pageInfoPath ); - - _.set( data, pageInfoPath, newPageInfo ); - _.update( data, nodesPath, ( d ) => d.concat( newNodes ) ); - } - - return data; -} - -module.exports = paginateByPath; - - -/***/ }), - -/***/ 356: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - if (isObject(o) === false) return false; - - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; - - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; - - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } - - // Most likely a plain Object - return true; -} - -exports.isPlainObject = isPlainObject; - - -/***/ }), - -/***/ 357: -/***/ (function(module) { - -module.exports = require("assert"); - -/***/ }), - -/***/ 369: -/***/ (function(module) { - -module.exports = [["0","\u0000",127,"€"],["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"],["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"],["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11],["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"],["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"],["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5],["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"],["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"],["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"],["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"],["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"],["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"],["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4],["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6],["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"],["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7],["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"],["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"],["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"],["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5],["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"],["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6],["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"],["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4],["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4],["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"],["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"],["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6],["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"],["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"],["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"],["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6],["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"],["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"],["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"],["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"],["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"],["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"],["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8],["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"],["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"],["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"],["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"],["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5],["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"],["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"],["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"],["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"],["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5],["9980","檧檨檪檭",114,"欥欦欨",6],["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"],["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"],["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"],["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"],["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"],["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5],["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"],["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"],["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6],["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"],["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"],["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4],["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19],["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"],["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"],["a2a1","ⅰ",9],["a2b1","⒈",19,"⑴",19,"①",9],["a2e5","㈠",9],["a2f1","Ⅰ",11],["a3a1","!"#¥%",88," ̄"],["a4a1","ぁ",82],["a5a1","ァ",85],["a6a1","Α",16,"Σ",6],["a6c1","α",16,"σ",6],["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"],["a6ee","︻︼︷︸︱"],["a6f4","︳︴"],["a7a1","А",5,"ЁЖ",25],["a7d1","а",5,"ёж",25],["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6],["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"],["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"],["a8bd","ńň"],["a8c0","ɡ"],["a8c5","ㄅ",36],["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"],["a959","℡㈱"],["a95c","‐"],["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8],["a980","﹢",4,"﹨﹩﹪﹫"],["a996","〇"],["a9a4","─",75],["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8],["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"],["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4],["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4],["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11],["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"],["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12],["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"],["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"],["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"],["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"],["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"],["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"],["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"],["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"],["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"],["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4],["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"],["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"],["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"],["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9],["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"],["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"],["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"],["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"],["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"],["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16],["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"],["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"],["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"],["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"],["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"],["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"],["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"],["bb40","籃",9,"籎",36,"籵",5,"籾",9],["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"],["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5],["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"],["bd40","紷",54,"絯",7],["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"],["be40","継",12,"綧",6,"綯",42],["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"],["bf40","緻",62],["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"],["c040","繞",35,"纃",23,"纜纝纞"],["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"],["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"],["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"],["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"],["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"],["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"],["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"],["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"],["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"],["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"],["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"],["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"],["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"],["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"],["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"],["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"],["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"],["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"],["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"],["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10],["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"],["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"],["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"],["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"],["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"],["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"],["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"],["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"],["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"],["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9],["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"],["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"],["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"],["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5],["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"],["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"],["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"],["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6],["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"],["d440","訞",31,"訿",8,"詉",21],["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"],["d540","誁",7,"誋",7,"誔",46],["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"],["d640","諤",34,"謈",27],["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"],["d740","譆",31,"譧",4,"譭",25],["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"],["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"],["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"],["d940","貮",62],["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"],["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"],["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"],["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"],["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"],["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7],["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"],["dd40","軥",62],["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"],["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"],["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"],["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"],["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"],["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"],["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"],["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"],["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"],["e240","釦",62],["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"],["e340","鉆",45,"鉵",16],["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"],["e440","銨",5,"銯",24,"鋉",31],["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"],["e540","錊",51,"錿",10],["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"],["e640","鍬",34,"鎐",27],["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"],["e740","鏎",7,"鏗",54],["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"],["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"],["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"],["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42],["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"],["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"],["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"],["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"],["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"],["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7],["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"],["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46],["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"],["ee40","頏",62],["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"],["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4],["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"],["f040","餈",4,"餎餏餑",28,"餯",26],["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"],["f140","馌馎馚",10,"馦馧馩",47],["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"],["f240","駺",62],["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"],["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"],["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"],["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5],["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"],["f540","魼",62],["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"],["f640","鯜",62],["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"],["f740","鰼",62],["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"],["f840","鳣",62],["f880","鴢",32],["f940","鵃",62],["f980","鶂",32],["fa40","鶣",62],["fa80","鷢",32],["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"],["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"],["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6],["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"],["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38],["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"],["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"]]; - -/***/ }), - -/***/ 385: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -var isPlainObject = __webpack_require__(356); -var universalUserAgent = __webpack_require__(796); - -function lowercaseKeys(object) { - if (!object) { - return {}; - } - - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} - -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject.isPlainObject(options[key])) { - if (!(key in defaults)) Object.assign(result, { - [key]: options[key] - });else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { - [key]: options[key] - }); - } - }); - return result; -} - -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === undefined) { - delete obj[key]; - } - } - - return obj; -} - -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); - } else { - options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - - - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); - } - - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); - return mergedOptions; -} - -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - - if (names.length === 0) { - return url; - } - - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -const urlVariableRegex = /\{[^}]+\}/g; - -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} - -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - - if (!matches) { - return []; - } - - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} - -function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); -} - -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* istanbul ignore file */ -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - - return part; - }).join(""); -} - -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} - -function isDefined(value) { - return value !== undefined && value !== null; -} - -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} - -function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; - - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - - return result; -} - -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} - -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - - expression.split(/,/g).forEach(function (variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - - if (operator && operator !== "+") { - var separator = ","; - - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - }); -} - -function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later - - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - - if (!isBinaryRequest) { - if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); - } - - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters - - - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } else { - headers["content-length"] = 0; - } - } - } // default content-type for JSON if body is set - - - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string - - - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present - - - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); -} - -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), - parse - }); -} - -const VERSION = "6.0.12"; - -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. - -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; - -const endpoint = withDefaults(null, DEFAULTS); - -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 409: -/***/ (function(module, __unusedexports, __webpack_require__) { - -/** - * External dependencies - */ -const github = __webpack_require__( 864 ); - -/** - * Internal dependencies - */ -const paginateByPath = __webpack_require__( 354 ); - -const findIssuesWithinMilestoneQuery = ` - query ( - $after: String - $searchQuery: String! - ) { - search(query: $searchQuery, type: ISSUE, first: 100, after: $after) { - pageInfo { - endCursor - hasNextPage - } - nodes { - ... on Issue { - title - number - author { - ... on User { - name - login - } - } - participants(first: 100) { - nodes { - login - name - } - } - } - ... on PullRequest { - number - title - bodyText - author { - ... on User { - name - login - } - } - participants(first: 100) { - nodes { - login - name - } - } - commits(first: 200) { - nodes { - commit { - authors(first: 10) { - nodes { - user { - login - name - } - } - } - } - } - } - } - } - } - } -`; - -class Changelog { - constructor( repo, milestone, token ) { - this.changelogEntries = new Map(); - this.contributorEntries = new Map(); - this.octokit = github.getOctokit( token ); - - this.authorsToIgnore = [ 'CLAassistant', 'dependabot', 'dependabot-preview[bot]', 'googlebot', 'renovate-bot' ]; - - this.graphQlVariables = { - searchQuery: `repo:${ repo } milestone:${ milestone } is:closed`, - }; - } - - async generate() { - const { search } = await paginateByPath( this.octokit.graphql, findIssuesWithinMilestoneQuery, this.graphQlVariables, [ - 'search', - ] ); - - search.nodes.forEach( ( issueOrPr ) => { - // Skip if author is in ignore list, or an empty author object was returned (usually happens when the author is a bot). - if ( this.authorsToIgnore.includes( issueOrPr.author.login ) || Object.entries( issueOrPr.author ).length === 0 ) { - return; - } - - // Add issue/PR author as a contributor. - if ( ! this.contributorEntries.has( issueOrPr.author.login ) ) { - this.contributorEntries.set( issueOrPr.author.login, issueOrPr.author.name ); - } - - // Add participants of issue/PR to list of contributors. - issueOrPr.participants.nodes.forEach( ( participant ) => { - if ( ! this.contributorEntries.has( participant.login ) ) { - this.contributorEntries.set( participant.login, participant.name ); - } - } ); - - const currentClosedItems = - 'closedItems' in ( this.changelogEntries.get( issueOrPr.number ) || {} ) - ? this.changelogEntries.get( issueOrPr.number ).closedItems - : []; - const currentChangelogEntry = { - title: issueOrPr.title, - closedItems: [ issueOrPr.number, ...currentClosedItems ], - }; - - // It's a PR if it has commits. - if ( 'commits' in issueOrPr ) { - this.handlePr( issueOrPr, currentChangelogEntry ); - } else { - // It's an issue. - this.handleIssue( issueOrPr, currentChangelogEntry ); - } - } ); - - return `## Changelog\n${ this.generateChangelog() }\n\n## Contributors\n${ this.generateContributors() }`; - } - - handlePr( pr, currentChangelogEntry ) { - const commits = pr.commits.nodes; - - // Retrieve list of commit authors and add them as contributors. - commits.forEach( ( commit ) => { - const authors = commit.commit.authors.nodes; - - authors.forEach( ( author ) => { - if ( ! this.contributorEntries.has( author.user.login ) ) { - this.contributorEntries.set( author.user.login, author.user.name ); - } - } ); - } ); - - const closedItems = [ ...pr.bodyText.matchAll( /(?:Fixes|Fixed|Fix|Closes|Closed|Close)\s+#(\d+)/gi ) ]; - - // Add changelog entry for PR if it doesn't close any issues/PRs. - if ( closedItems.length === 0 ) { - this.changelogEntries.set( pr.number, currentChangelogEntry ); - return; - } - - closedItems.forEach( ( [ , closedItemNumber ] ) => { - const itemNumber = parseInt( closedItemNumber ); - if ( ! this.changelogEntries.has( itemNumber ) ) { - this.changelogEntries.set( itemNumber, { closedItems: [ pr.number ] } ); - } else { - const closedItemNumberEntry = this.changelogEntries.get( itemNumber ); - if ( closedItemNumberEntry.closedItems.includes( pr.number ) ) { - return; - } - closedItemNumberEntry.closedItems.push( pr.number ); - } - } ); - } - - handleIssue( issue, currentChangelogEntry ) { - this.changelogEntries.set( issue.number, currentChangelogEntry ); - } - - generateChangelog() { - return [ ...this.changelogEntries.entries() ] - .map( ( [ itemNumber, details ] ) => { - if ( ! details.title ) { - throw new Error( `Title for #${ itemNumber } was not set. Is it apart of the milestone?` ); - } - - return `- ${ details.title }. (${ details.closedItems.map( ( closedItem ) => `#${ closedItem }` ).join( ', ' ) })`; - } ) - .join( '\n' ); - } - - generateContributors() { - return [ ...this.contributorEntries.entries() ] - .filter( ( [ username ] ) => ! this.authorsToIgnore.includes( username ) ) - .sort( ( [ aUsername, aName ], [ bUsername, bName ] ) => { - const aComparator = aName || aUsername; - const bComparator = bName || bUsername; - - if ( aComparator.toLowerCase() < bComparator.toLowerCase() ) { - return -1; - } - if ( aComparator.toLowerCase() > bComparator.toLowerCase() ) { - return 1; - } - return 0; - } ) - .map( ( [ username, name ] ) => ( name === null ? `@${ username }` : `${ name } (@${ username })` ) ) - .join( ', ' ); - } -} - -module.exports = Changelog; - - -/***/ }), - -/***/ 413: -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = __webpack_require__(141); - - -/***/ }), - -/***/ 426: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var Buffer = __webpack_require__(572).Buffer; - -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - -// == UTF16-BE codec. ========================================================== - -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} - -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf16BEEncoder() { -} - -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; -} - -Utf16BEEncoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf16BEDecoder() { - this.overflowByte = -1; -} - -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; - - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; - - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } - - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } - - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - - return buf2.slice(0, j).toString('ucs2'); -} - -Utf16BEDecoder.prototype.end = function() { - this.overflowByte = -1; -} - - -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); - -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). - -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} - -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - - -// -- Encoding (pass-through) - -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} - -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} - -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} - - -// -- Decoding - -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - - this.options = options || {}; - this.iconv = codec.iconv; -} - -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - - if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below) - return ''; - - // We have enough bytes -> detect endianness. - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - - return this.decoder.write(buf); -} - -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - var trail = this.decoder.end(); - if (trail) - resStr += trail; - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - return this.decoder.end(); -} - -function detectEncoding(bufs, defaultEncoding) { - var b = []; - var charsProcessed = 0; - var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE. - - outer_loop: - for (var i = 0; i < bufs.length; i++) { - var buf = bufs[i]; - for (var j = 0; j < buf.length; j++) { - b.push(buf[j]); - if (b.length === 2) { - if (charsProcessed === 0) { - // Check BOM first. - if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le'; - if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be'; - } - - if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; - if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; - - b.length = 0; - charsProcessed++; - - if (charsProcessed >= 100) { - break outer_loop; - } - } - } - } - - // Make decisions. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - if (asciiCharsBE > asciiCharsLE) return 'utf-16be'; - if (asciiCharsBE < asciiCharsLE) return 'utf-16le'; - - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-16le'; -} - - - - -/***/ }), - -/***/ 431: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__webpack_require__(87)); -const utils_1 = __webpack_require__(82); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map - -/***/ }), - -/***/ 432: -/***/ (function(module) { - -module.exports = [["0","\u0000",127],["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],["8361","긝",18,"긲긳긵긶긹긻긼"],["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],["8741","놞",9,"놩",15],["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],["8a61","둧",4,"둭",18,"뒁뒂"],["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],["8c41","똀",15,"똒똓똕똖똗똙",4],["8c61","똞",6,"똦",5,"똭",6,"똵",5],["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],["8d41","뛃",16,"뛕",8],["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],["8e61","럂",4,"럈럊",19],["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],["8f41","뢅",7,"뢎",17],["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],["9061","륾",5,"릆릈릋릌릏",15],["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],["9461","봞",5,"봥",6,"봭",12],["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],["9641","뺸",23,"뻒뻓"],["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],["9741","뾃",16,"뾕",8],["9761","뾞",17,"뾱",7],["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],["9841","쁀",16,"쁒",5,"쁙쁚쁛"],["9861","쁝쁞쁟쁡",6,"쁪",15],["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],["9a41","숤숥숦숧숪숬숮숰숳숵",16],["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],["9b61","쌳",17,"썆",7],["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],["9c61","쏿",8,"쐉",6,"쐑",9],["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],["9d41","쒪",13,"쒹쒺쒻쒽",8],["9d61","쓆",25],["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],["a141","좥좦좧좩",18,"좾좿죀죁"],["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"],["a241","줐줒",5,"줙",18],["a261","줭",6,"줵",18],["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],["a361","즑",6,"즚즜즞",16],["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"],["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],["a481","쨦쨧쨨쨪",28,"ㄱ",93],["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],["a561","쩫",17,"쩾",5,"쪅쪆"],["a581","쪇",16,"쪙",14,"ⅰ",9],["a5b0","Ⅰ",9],["a5c1","Α",16,"Σ",6],["a5e1","α",16,"σ",6],["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],["a761","쬪",22,"쭂쭃쭄"],["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],["a841","쭭",10,"쭺",14],["a861","쮉",18,"쮝",6],["a881","쮤",19,"쮹",11,"ÆЪĦ"],["a8a6","IJ"],["a8a8","ĿŁØŒºÞŦŊ"],["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],["a941","쯅",14,"쯕",10],["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],["aa81","챳챴챶",29,"ぁ",82],["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],["acd1","а",5,"ёж",25],["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],["ae41","췆",5,"췍췎췏췑",16],["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],["af41","츬츭츮츯츲츴츶",19],["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],["b041","캚",5,"캢캦",5,"캮",12],["b061","캻",5,"컂",19],["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],["b161","켥",6,"켮켲",5,"켹",11],["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],["b261","쾎",18,"쾢",5,"쾩"],["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],["b541","킕",14,"킦킧킩킪킫킭",5],["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],["b641","턅",7,"턎",17],["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],["b741","텮",13,"텽",6,"톅톆톇톉톊"],["b761","톋",20,"톢톣톥톦톧"],["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],["b841","퇐",7,"퇙",17],["b861","퇫",8,"퇵퇶퇷퇹",13],["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],["be41","퐸",7,"푁푂푃푅",14],["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],["bf41","풞",10,"풪",14],["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],["c061","픞",25],["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],["c161","햌햍햎햏햑",19,"햦햧"],["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],["c361","홢",4,"홨홪",5,"홲홳홵",11],["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],["c641","힍힎힏힑",6,"힚힜힞",5],["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]]; - -/***/ }), - -/***/ 446: -/***/ (function(module) { - -module.exports = [["0","\u0000",127],["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"],["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"],["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"],["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21],["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10],["a3a1","ㄐ",25,"˙ˉˊˇˋ"],["a3e1","€"],["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"],["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"],["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"],["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"],["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"],["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"],["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"],["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"],["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"],["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"],["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"],["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"],["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"],["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"],["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"],["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"],["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"],["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"],["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"],["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"],["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"],["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"],["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"],["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"],["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"],["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"],["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"],["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"],["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"],["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"],["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"],["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"],["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"],["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"],["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"],["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"],["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"],["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"],["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"],["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"],["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"],["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"],["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"],["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"],["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"],["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"],["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"],["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"],["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"],["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"],["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"],["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"],["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"],["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"],["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"],["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"],["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"],["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"],["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"],["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"],["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"],["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"],["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"],["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"],["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"],["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"],["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"],["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"],["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"],["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"],["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"],["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"],["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"],["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"],["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"],["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"],["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"],["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"],["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"],["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"],["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"],["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"],["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"],["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"],["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"],["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"],["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"],["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"],["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"],["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"],["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"],["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"],["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"],["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"],["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"],["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"],["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"],["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"],["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"],["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"],["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"],["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"],["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"],["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"],["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"],["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"],["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"],["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"],["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"],["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"],["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"],["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"],["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"],["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"],["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"],["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"],["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"],["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"],["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"],["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"],["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"],["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"],["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"],["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"],["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"],["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"],["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"],["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"],["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"],["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"],["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"],["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"],["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"],["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"],["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"],["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"],["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"],["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"],["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"],["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"],["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"],["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"],["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"],["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"],["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"],["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"],["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"],["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"],["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"],["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"],["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"],["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"],["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"],["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"],["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"],["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"],["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"],["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"],["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"],["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"],["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"],["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"],["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"],["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"],["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"],["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"],["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"]]; - -/***/ }), - -/***/ 448: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -var universalUserAgent = __webpack_require__(796); -var beforeAfterHook = __webpack_require__(523); -var request = __webpack_require__(753); -var graphql = __webpack_require__(898); -var authToken = __webpack_require__(813); - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -const VERSION = "3.5.1"; - -const _excluded = ["authStrategy"]; -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; // prepend default user agent with `options.userAgent` if set - - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. - - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, _excluded); - - const auth = authStrategy(Object.assign({ - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ - - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 - - - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); - } - - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); - } - - }; - return OctokitWithDefaults; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - - - static plugin(...newPlugins) { - var _a; - - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; - } - -} -Octokit.VERSION = VERSION; -Octokit.plugins = []; - -exports.Octokit = Octokit; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 454: -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__webpack_require__(794)); -var http = _interopDefault(__webpack_require__(605)); -var Url = _interopDefault(__webpack_require__(835)); -var https = _interopDefault(__webpack_require__(211)); -var zlib = _interopDefault(__webpack_require__(761)); - -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js - -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; - -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); - -class Blob { - constructor() { - this[TYPE] = ''; - - const blobParts = arguments[0]; - const options = arguments[1]; - - const buffers = []; - let size = 0; - - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } - - this[BUFFER] = Buffer.concat(buffers); - - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; - - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); - - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} - -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); - -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ - -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); - - this.message = message; - this.type = type; - - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = __webpack_require__(203).convert; -} catch (e) {} - -const INTERNALS = Symbol('Body internals'); - -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; - -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; - - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; - - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; - - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; - - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } -} - -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - - get bodyUsed() { - return this[INTERNALS].disturbed; - }, - - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, - - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, - - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; - - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, - - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, - - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; - - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; - -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); - -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; - -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } - - this[INTERNALS].disturbed = true; - - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } - - let body = this.body; - - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is blob - if (isBlob(body)) { - body = body.stream(); - } - - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } - - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; - - return new Body.Promise(function (resolve, reject) { - let resTimeout; - - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } - - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } - - accumBytes += chunk.length; - accum.push(chunk); - }); - - body.on('end', function () { - if (abort) { - return; - } - - clearTimeout(resTimeout); - - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} - -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; - - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } - - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); - - // html5 - if (!res && str) { - res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - this[MAP] = Object.create(null); - - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - - return; - } - - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } - - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } - - return this[MAP][key].join(', '); - } - - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } - - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } - - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); - -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} - -const INTERNAL = Symbol('internal'); - -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} - -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } - - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; - - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; -} - -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); - -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; - -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - Body.call(this, body, opts); - - const status = opts.status || 200; - const headers = new Headers(opts.headers); - - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } - - get url() { - return this[INTERNALS$1].url || ''; - } - - get status() { - return this[INTERNALS$1].status; - } - - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - - get redirected() { - return this[INTERNALS$1].counter > 0; - } - - get statusText() { - return this[INTERNALS$1].statusText; - } - - get headers() { - return this[INTERNALS$1].headers; - } - - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} - -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); - -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); - -const INTERNALS$2 = Symbol('Request internals'); - -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; - -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; - -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} - -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parse_url(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parse_url(`${input}`); - } - input = {}; - } else { - parsedURL = parse_url(input.url); - } - - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); - - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); - - const headers = new Headers(init.headers || input.headers || {}); - - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; - - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } - - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; - - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } - - get method() { - return this[INTERNALS$2].method; - } - - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } - - get headers() { - return this[INTERNALS$2].headers; - } - - get redirect() { - return this[INTERNALS$2].redirect; - } - - get signal() { - return this[INTERNALS$2].signal; - } - - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } -} - -Body.mixIn(Request.prototype); - -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); - -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); - -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); - - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } - - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } - - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } - - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js - - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} - -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ - -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); - - this.type = 'aborted'; - this.message = message; - - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; - -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; -const resolve_url = Url.resolve; - -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } - - Body.Promise = fetch.Promise; - - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); - - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; - - let response = null; - - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; - - if (signal && signal.aborted) { - abort(); - return; - } - - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - - // send request - const req = send(options); - let reqTimeout; - - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } - - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } - - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } - - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); - finalize(); - }); - - req.on('response', function (res) { - clearTimeout(reqTimeout); - - const headers = createHeadersLenient(res.headers); - - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); - - // HTTP fetch step 5.3 - const locationURL = location === null ? null : resolve_url(request.url, location); - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; - - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } - - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } - - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); - - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; - - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); - - // HTTP-network fetch step 12.1.1.4: handle content codings - - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } - - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; - - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } - - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - return; - } - - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } - - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); - - writeToStream(req, request); - }); -} -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; - -// expose Promise -fetch.Promise = global.Promise; - -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; - - -/***/ }), - -/***/ 455: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const http = __webpack_require__(605); -const https = __webpack_require__(211); -const pm = __webpack_require__(17); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __webpack_require__(734); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - }); - } -} -exports.HttpClient = HttpClient; - - -/***/ }), - -/***/ 463: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var deprecation = __webpack_require__(692); -var once = _interopDefault(__webpack_require__(49)); - -const logOnceCode = once(deprecation => console.warn(deprecation)); -const logOnceHeaders = once(deprecation => console.warn(deprecation)); -/** - * Error with extra properties to help with debugging - */ - -class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = "HttpError"; - this.status = statusCode; - let headers; - - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; - } // redact request credentials without mutating original request options - - - const requestCopy = Object.assign({}, options.request); - - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") - }); - } - - requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; // deprecations - - Object.defineProperty(this, "code", { - get() { - logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - } - - }); - Object.defineProperty(this, "headers", { - get() { - logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); - return headers || {}; - } - - }); - } - -} - -exports.RequestError = RequestError; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 469: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__webpack_require__(262)); -const utils_1 = __webpack_require__(521); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options) { - return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); -} -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map - -/***/ }), - -/***/ 470: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __webpack_require__(431); -const file_command_1 = __webpack_require__(102); -const utils_1 = __webpack_require__(82); -const os = __importStar(__webpack_require__(87)); -const path = __importStar(__webpack_require__(622)); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - const delimiter = '_GitHubActionsFileCommandDelimeter_'; - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); - } -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueCommand('PATH', inputPath); - } - else { - command_1.issueCommand('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - return inputs; -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - */ -function error(message) { - command_1.issue('error', message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds an warning issue - * @param message warning issue message. Errors will be converted to string via toString() - */ -function warning(message) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 475: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -var Buffer = __webpack_require__(572).Buffer; - -// == UTF32-LE/BE codec. ========================================================== - -exports._utf32 = Utf32Codec; - -function Utf32Codec(codecOptions, iconv) { - this.iconv = iconv; - this.bomAware = true; - this.isLE = codecOptions.isLE; -} - -exports.utf32le = { type: '_utf32', isLE: true }; -exports.utf32be = { type: '_utf32', isLE: false }; - -// Aliases -exports.ucs4le = 'utf32le'; -exports.ucs4be = 'utf32be'; - -Utf32Codec.prototype.encoder = Utf32Encoder; -Utf32Codec.prototype.decoder = Utf32Decoder; - -// -- Encoding - -function Utf32Encoder(options, codec) { - this.isLE = codec.isLE; - this.highSurrogate = 0; -} - -Utf32Encoder.prototype.write = function(str) { - var src = Buffer.from(str, 'ucs2'); - var dst = Buffer.alloc(src.length * 2); - var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE; - var offset = 0; - - for (var i = 0; i < src.length; i += 2) { - var code = src.readUInt16LE(i); - var isHighSurrogate = (0xD800 <= code && code < 0xDC00); - var isLowSurrogate = (0xDC00 <= code && code < 0xE000); - - if (this.highSurrogate) { - if (isHighSurrogate || !isLowSurrogate) { - // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low - // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character - // (technically wrong, but expected by some applications, like Windows file names). - write32.call(dst, this.highSurrogate, offset); - offset += 4; - } - else { - // Create 32-bit value from high and low surrogates; - var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000; - - write32.call(dst, codepoint, offset); - offset += 4; - this.highSurrogate = 0; - - continue; - } - } - - if (isHighSurrogate) - this.highSurrogate = code; - else { - // Even if the current character is a low surrogate, with no previous high surrogate, we'll - // encode it as a semi-invalid stand-alone character for the same reasons expressed above for - // unpaired high surrogates. - write32.call(dst, code, offset); - offset += 4; - this.highSurrogate = 0; - } - } - - if (offset < dst.length) - dst = dst.slice(0, offset); - - return dst; -}; - -Utf32Encoder.prototype.end = function() { - // Treat any leftover high surrogate as a semi-valid independent character. - if (!this.highSurrogate) - return; - - var buf = Buffer.alloc(4); - - if (this.isLE) - buf.writeUInt32LE(this.highSurrogate, 0); - else - buf.writeUInt32BE(this.highSurrogate, 0); - - this.highSurrogate = 0; - - return buf; -}; - -// -- Decoding - -function Utf32Decoder(options, codec) { - this.isLE = codec.isLE; - this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0); - this.overflow = []; -} - -Utf32Decoder.prototype.write = function(src) { - if (src.length === 0) - return ''; - - var i = 0; - var codepoint = 0; - var dst = Buffer.alloc(src.length + 4); - var offset = 0; - var isLE = this.isLE; - var overflow = this.overflow; - var badChar = this.badChar; - - if (overflow.length > 0) { - for (; i < src.length && overflow.length < 4; i++) - overflow.push(src[i]); - - if (overflow.length === 4) { - // NOTE: codepoint is a signed int32 and can be negative. - // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer). - if (isLE) { - codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24); - } else { - codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24); - } - overflow.length = 0; - - offset = _writeCodepoint(dst, offset, codepoint, badChar); - } - } - - // Main loop. Should be as optimized as possible. - for (; i < src.length - 3; i += 4) { - // NOTE: codepoint is a signed int32 and can be negative. - if (isLE) { - codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24); - } else { - codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24); - } - offset = _writeCodepoint(dst, offset, codepoint, badChar); - } - - // Keep overflowing bytes. - for (; i < src.length; i++) { - overflow.push(src[i]); - } - - return dst.slice(0, offset).toString('ucs2'); -}; - -function _writeCodepoint(dst, offset, codepoint, badChar) { - // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations. - if (codepoint < 0 || codepoint > 0x10FFFF) { - // Not a valid Unicode codepoint - codepoint = badChar; - } - - // Ephemeral Planes: Write high surrogate. - if (codepoint >= 0x10000) { - codepoint -= 0x10000; - - var high = 0xD800 | (codepoint >> 10); - dst[offset++] = high & 0xff; - dst[offset++] = high >> 8; - - // Low surrogate is written below. - var codepoint = 0xDC00 | (codepoint & 0x3FF); - } - - // Write BMP char or low surrogate. - dst[offset++] = codepoint & 0xff; - dst[offset++] = codepoint >> 8; - - return offset; -}; - -Utf32Decoder.prototype.end = function() { - this.overflow.length = 0; -}; - -// == UTF-32 Auto codec ============================================================= -// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic. -// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32 -// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'}); - -// Encoder prepends BOM (which can be overridden with (addBOM: false}). - -exports.utf32 = Utf32AutoCodec; -exports.ucs4 = 'utf32'; - -function Utf32AutoCodec(options, iconv) { - this.iconv = iconv; -} - -Utf32AutoCodec.prototype.encoder = Utf32AutoEncoder; -Utf32AutoCodec.prototype.decoder = Utf32AutoDecoder; - -// -- Encoding - -function Utf32AutoEncoder(options, codec) { - options = options || {}; - - if (options.addBOM === undefined) - options.addBOM = true; - - this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options); -} - -Utf32AutoEncoder.prototype.write = function(str) { - return this.encoder.write(str); -}; - -Utf32AutoEncoder.prototype.end = function() { - return this.encoder.end(); -}; - -// -- Decoding - -function Utf32AutoDecoder(options, codec) { - this.decoder = null; - this.initialBufs = []; - this.initialBufsLen = 0; - this.options = options || {}; - this.iconv = codec.iconv; -} - -Utf32AutoDecoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBufs.push(buf); - this.initialBufsLen += buf.length; - - if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below) - return ''; - - // We have enough bytes -> detect endianness. - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - - return this.decoder.write(buf); -}; - -Utf32AutoDecoder.prototype.end = function() { - if (!this.decoder) { - var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var resStr = ''; - for (var i = 0; i < this.initialBufs.length; i++) - resStr += this.decoder.write(this.initialBufs[i]); - - var trail = this.decoder.end(); - if (trail) - resStr += trail; - - this.initialBufs.length = this.initialBufsLen = 0; - return resStr; - } - - return this.decoder.end(); -}; - -function detectEncoding(bufs, defaultEncoding) { - var b = []; - var charsProcessed = 0; - var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE. - var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE. - - outer_loop: - for (var i = 0; i < bufs.length; i++) { - var buf = bufs[i]; - for (var j = 0; j < buf.length; j++) { - b.push(buf[j]); - if (b.length === 4) { - if (charsProcessed === 0) { - // Check BOM first. - if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) { - return 'utf-32le'; - } - if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) { - return 'utf-32be'; - } - } - - if (b[0] !== 0 || b[1] > 0x10) invalidBE++; - if (b[3] !== 0 || b[2] > 0x10) invalidLE++; - - if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; - if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; - - b.length = 0; - charsProcessed++; - - if (charsProcessed >= 100) { - break outer_loop; - } - } - } - } - - // Make decisions. - if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be'; - if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le'; - - // Couldn't decide (likely all zeros or not enough data). - return defaultEncoding || 'utf-32le'; -} - - -/***/ }), - -/***/ 486: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - -var Buffer = __webpack_require__(572).Buffer; - -// Export Node.js internal encodings. - -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", - - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", - - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, - - // Codec. - _internal: InternalCodec, -}; - -//------------------------------------------------------------------------------ - -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; - - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; - - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } -} - -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; - -//------------------------------------------------------------------------------ - -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = __webpack_require__(304).StringDecoder; - -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; - - -function InternalDecoder(options, codec) { - this.decoder = new StringDecoder(codec.enc); -} - -InternalDecoder.prototype.write = function(buf) { - if (!Buffer.isBuffer(buf)) { - buf = Buffer.from(buf); - } - - return this.decoder.write(buf); -} - -InternalDecoder.prototype.end = function() { - return this.decoder.end(); -} - - -//------------------------------------------------------------------------------ -// Encoder is mostly trivial - -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} - -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} - -InternalEncoder.prototype.end = function() { -} - - -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. - -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} - -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); - - return Buffer.from(str, "base64"); -} - -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} - - -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. - -function InternalEncoderCesu8(options, codec) { -} - -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - } - return buf.slice(0, bufIdx); -} - -InternalEncoderCesu8.prototype.end = function() { -} - -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ - -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} - -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } - - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } - } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} - -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; -} - - -/***/ }), - -/***/ 494: -/***/ (function(module) { - -module.exports = register; - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - - -/***/ }), - -/***/ 510: -/***/ (function(module) { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} - - -/***/ }), - -/***/ 515: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getApiBaseUrl = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__webpack_require__(455)); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; -} -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 521: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOctokitOptions = exports.GitHub = exports.context = void 0; -const Context = __importStar(__webpack_require__(262)); -const Utils = __importStar(__webpack_require__(127)); -// octokit + plugins -const core_1 = __webpack_require__(448); -const plugin_rest_endpoint_methods_1 = __webpack_require__(842); -const plugin_paginate_rest_1 = __webpack_require__(299); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -const defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl) - } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; - } - return opts; -} -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 523: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var register = __webpack_require__(280) -var addHook = __webpack_require__(510) -var removeHook = __webpack_require__(866) - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) - -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef - - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} - -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} - -function HookCollection () { - var state = { - registry: {} - } - - var hook = register.bind(null, state) - bindApi(hook, state) - - return hook -} - -var collectionHookDeprecationMessageDisplayed = false -function Hook () { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true - } - return HookCollection() -} - -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() - -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection - - -/***/ }), - -/***/ 539: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const http = __webpack_require__(605); -const https = __webpack_require__(211); -const pm = __webpack_require__(950); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __webpack_require__(413); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - }); - } -} -exports.HttpClient = HttpClient; - - -/***/ }), - -/***/ 541: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -var Buffer = __webpack_require__(572).Buffer; - -// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), -// we opt to dependency-inject it instead of creating a hard dependency. -module.exports = function(stream_module) { - var Transform = stream_module.Transform; - - // == Encoder stream ======================================================= - - function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); - } - - IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } - }); - - IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } - } - - IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } - } - - IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; - } - - - // == Decoder stream ======================================================= - - function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); - } - - IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } - }); - - IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } - } - - IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } - } - - IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; - } - - return { - IconvLiteEncoderStream: IconvLiteEncoderStream, - IconvLiteDecoderStream: IconvLiteDecoderStream, - }; -}; - - -/***/ }), - -/***/ 572: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; -/* eslint-disable node/no-deprecated-api */ - - - -var buffer = __webpack_require__(293) -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer - - -/***/ }), - -/***/ 595: -/***/ (function(module, __unusedexports, __webpack_require__) { - -"use strict"; - - -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. - -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - - 'shiftjis': { - type: '_dbcs', - table: function() { return __webpack_require__(675) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', - - 'eucjp': { - type: '_dbcs', - table: function() { return __webpack_require__(214) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, - - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - - - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', - - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __webpack_require__(369) }, - }, - - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return __webpack_require__(369).concat(__webpack_require__(984)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', - - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return __webpack_require__(369).concat(__webpack_require__(984)) }, - gb18030: function() { return __webpack_require__(115) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, - - 'chinese': 'gb18030', - - - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __webpack_require__(432) }, - }, - - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', - - - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __webpack_require__(446) }, - }, - - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return __webpack_require__(446).concat(__webpack_require__(871)) }, - encodeSkipVals: [ - // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of - // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU. - // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter. - 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe, - 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca, - 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62, - 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef, - 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed, - - // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345 - 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce, - ], - }, - - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; - - -/***/ }), - -/***/ 605: -/***/ (function(module) { - -module.exports = require("http"); - -/***/ }), - -/***/ 614: -/***/ (function(module) { - -module.exports = require("events"); - -/***/ }), - -/***/ 622: -/***/ (function(module) { - -module.exports = require("path"); - -/***/ }), - -/***/ 631: -/***/ (function(module) { - -module.exports = require("net"); - -/***/ }), - -/***/ 633: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -var universalUserAgent = __webpack_require__(323); -var beforeAfterHook = __webpack_require__(171); -var request = __webpack_require__(7); -var graphql = __webpack_require__(269); -var authToken = __webpack_require__(638); - -function _objectWithoutPropertiesLoose(source, excluded) { - if (source == null) return {}; - var target = {}; - var sourceKeys = Object.keys(source); - var key, i; - - for (i = 0; i < sourceKeys.length; i++) { - key = sourceKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - target[key] = source[key]; - } - - return target; -} - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - - var target = _objectWithoutPropertiesLoose(source, excluded); - - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; - } - } - - return target; -} - -const VERSION = "3.5.1"; - -const _excluded = ["authStrategy"]; -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; // prepend default user agent with `options.userAgent` if set - - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. - - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ - - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, _excluded); - - const auth = authStrategy(Object.assign({ - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, options.auth)); // @ts-ignore ¯\_(ツ)_/¯ - - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 - - - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); - } - - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); - } - - }; - return OctokitWithDefaults; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - - - static plugin(...newPlugins) { - var _a; - - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; - } - -} -Octokit.VERSION = VERSION; -Octokit.plugins = []; - -exports.Octokit = Octokit; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 638: -/***/ (function(__unusedmodule, exports) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -async function auth(token) { - const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; - return { - type: "token", - token: token, - tokenType - }; -} - -/** - * Prefix token for usage in the Authorization header - * - * @param token OAuth token or JSON Web Token - */ -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - - return `token ${token}`; -} - -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} - -const createTokenAuth = function createTokenAuth(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - - if (typeof token !== "string") { - throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string"); - } - - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -exports.createTokenAuth = createTokenAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 655: -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, '__esModule', { value: true }); - -var isPlainObject = __webpack_require__(68); -var universalUserAgent = __webpack_require__(323); - -function lowercaseKeys(object) { - if (!object) { - return {}; - } - - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} - -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject.isPlainObject(options[key])) { - if (!(key in defaults)) Object.assign(result, { - [key]: options[key] - });else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { - [key]: options[key] - }); - } - }); - return result; -} - -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === undefined) { - delete obj[key]; - } - } - - return obj; -} - -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); - } else { - options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - - - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging - - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten - - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); - } - - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); - return mergedOptions; -} - -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - - if (names.length === 0) { - return url; - } - - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -const urlVariableRegex = /\{[^}]+\}/g; - -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); -} - -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - - if (!matches) { - return []; - } - - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); -} - -function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); -} - -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* istanbul ignore file */ -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - - return part; - }).join(""); -} - -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} - -function isDefined(value) { - return value !== undefined && value !== null; -} - -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} - -function getValues(context, operator, key, modifier) { - var value = context[key], - result = []; - - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - - return result; -} - -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} - -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - - expression.split(/,/g).forEach(function (variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - - if (operator && operator !== "+") { - var separator = ","; - - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - }); -} - -function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible - - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, ["method", "baseUrl", "url", "headers", "request", "mediaType"]); // extract variable names from URL to calculate remaining variables later - - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - - const omittedParameters = Object.keys(options).filter(option => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - - if (!isBinaryRequest) { - if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); - } - - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map(preview => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters - - - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } else { - headers["content-length"] = 0; - } - } - } // default content-type for JSON if body is set - - - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string - - - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present - - - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); -} - -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), - parse - }); -} - -const VERSION = "6.0.12"; - -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. - -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; - -const endpoint = withDefaults(null, DEFAULTS); - -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 661: -/***/ (function(module, __unusedexports, __webpack_require__) { - -var wrappy = __webpack_require__(945) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), - -/***/ 669: -/***/ (function(module) { - -module.exports = require("util"); - -/***/ }), - -/***/ 675: -/***/ (function(module) { - -module.exports = [["0","\u0000",128],["a1","。",62],["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"],["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"],["81b8","∈∋⊆⊇⊂⊃∪∩"],["81c8","∧∨¬⇒⇔∀∃"],["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["81f0","ʼn♯♭♪†‡¶"],["81fc","◯"],["824f","0",9],["8260","A",25],["8281","a",25],["829f","ぁ",82],["8340","ァ",62],["8380","ム",22],["839f","Α",16,"Σ",6],["83bf","α",16,"σ",6],["8440","А",5,"ЁЖ",25],["8470","а",5,"ёж",7],["8480","о",17],["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["8740","①",19,"Ⅰ",9],["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["877e","㍻"],["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"],["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"],["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"],["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["eeef","ⅰ",9,"¬¦'""],["f040","",62],["f080","",124],["f140","",62],["f180","",124],["f240","",62],["f280","",124],["f340","",62],["f380","",124],["f440","",62],["f480","",124],["f540","",62],["f580","",124],["f640","",62],["f680","",124],["f740","",62],["f780","",124],["f840","",62],["f880","",124],["f940",""],["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"],["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"],["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"],["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"],["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]]; - -/***/ }), - -/***/ 676: -/***/ (function(__unusedmodule, __unusedexports, __webpack_require__) { - -const fs = __webpack_require__(747); -const path = __webpack_require__(622); -const core = __webpack_require__(470); -const github = __webpack_require__(469); -const { makeRelease } = __webpack_require__(353); -const ReleaseChangelog = __webpack_require__(409); - -async function main() { - try { - const milestone = core.getInput('milestone', { required: true }); - - // Do a sanity check on the milestone name. - if (!/^v[0-9]+\.[0-9]+(\.[0-9]+)?$/.test(milestone)) { - throw new Error('Milestone name is invalid.'); - } - - // Get tag name from plugin main PHP file. - const pluginFile = fs.readFileSync(path.resolve(process.cwd(), 'amp.php')).toString(); - const matches = /\*\s+Version:\s+(\d+(\.\d+)+-\w+)/.exec(pluginFile); - const tagName = matches && matches[1] ? matches[1] : null; - - if (!tagName) { - throw new Error('Unable to parse Version from plugin bootstrap PHP file.'); - } - - if (!tagName.startsWith(milestone)) { - throw new Error('Milestone mismatch with PHP plugin bootstrap version.'); - } - - // Get target branch. - const targetBranch = github.context.ref.replace('refs/heads/', ''); - - core.info(`Tag: ${tagName}`); - core.info(`Milestone: ${milestone}`); - core.info(`Target branch: ${targetBranch}`); - - // Generate release changelog. - const repo = process.env.GITHUB_REPOSITORY; - const token = process.env.GITHUB_TOKEN; - const releaseBody = await new ReleaseChangelog(repo, milestone, token).generate(); - - // Make GitHub release. - const { - data: { html_url: htmlUrl, upload_url: assetUploadUrl } - } = await makeRelease(tagName, releaseBody, targetBranch); - - core.info(`Release draft URL: ${htmlUrl}`); - core.setOutput('asset_upload_url', assetUploadUrl); - } catch (error) { - core.setFailed(error.stack); - } -} - -main().catch(core.error); - - -/***/ }), - -/***/ 682: -/***/ (function(module, exports, __webpack_require__) { - -/* module decorator */ module = __webpack_require__.nmd(module); -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; - - /** Used as the semantic version number. */ - var VERSION = '4.17.21'; - - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; - - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function', - INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; - - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; - - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; - - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; - - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; - - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; - - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; - - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; - - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; - - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; - - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; - - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - 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 empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); - - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/; - - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; - - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; - - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - - /** - * Used to validate the `validate` option in `_.template` variable. - * - * Forbids characters which could potentially change the meaning of the function argument definition: - * - "()," (modification of function parameters) - * - "=" (default value) - * - "[]{}" (destructuring of function parameters) - * - "/" (beginning of a comment) - * - whitespace - */ - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; - - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; - - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; - - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; - - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; - - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; - - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); - - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); - - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); - - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; - - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; - - /** 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[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; - - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; - - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; - - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; - - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; - - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); - - /** Detect free variable `exports`. */ - var freeExports = true && exports && !exports.nodeType && exports; - - /** Detect free variable `module`. */ - var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; - - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; - - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); - - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - - /*--------------------------------------------------------------------------*/ - - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @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 == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @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 == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @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 == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); - - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } - - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } - - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @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 value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @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) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } - - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } - - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; - } - - /** - * 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 accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } - - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; - - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; - - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } - - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } - - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` 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 key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } - - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - function baseTrim(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string; - } - - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - - /** - * 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) { - return arrayMap(props, function(key) { - return object[key]; - }); - } - - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } - - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } - - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; - - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); - - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); - - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } - - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } - - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } - - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; - - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } - - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - - /** - * 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 = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } - - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @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 strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @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 strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } - - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } - - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } - - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - function trimmedEndIndex(string) { - var index = string.length; - - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; - } - - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; - - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to generate unique IDs. */ - var idCounter = 0; - - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; - - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); - - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; - - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); - - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; - - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; - - /** Used to lookup unminified function names. */ - var realNames = {}; - - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); - - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. 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 sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * 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`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.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, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); - - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } - - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } - - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; - - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; - - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; - } - - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } - - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); - - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; - - outer: - while (length-- && resIndex < takeCount) { - index += dir; - - var iterIndex = -1, - value = array[index]; - - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); - - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } - - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } - - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } - - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } - - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; - } - - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } - - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } - - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } - - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } - - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - - /*------------------------------------------------------------------------*/ - - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); - } - } - - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } - - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - - /*------------------------------------------------------------------------*/ - - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; - } - - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } - - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } - - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } - - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } - - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } - - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } - - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } - - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } - - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } - - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; - - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } - - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; - } - - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; - - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; - - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - } - - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); - - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; - } - - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; - - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } - - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); - - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); - - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } - - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; - - while (++index < length) { - var value = array[index], - current = iteratee(value); - - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } - - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; - - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } - - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } - - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } - - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `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(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @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 baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @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 object && baseFor(object, iteratee, keys); - } - - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } - - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } - - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } - - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } - - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } - - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } - - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } - - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; - - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; - - var index = -1, - seen = caches[0]; - - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } - - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } - - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - - /** - * 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); - - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(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 stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } - - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } - - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } - - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } - - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} 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; - } - - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } - - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; - } - - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee) { - if (isArray(iteratee)) { - return function(value) { - return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); - } - } - return iteratee; - }); - } else { - iteratees = [identity]; - } - - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; - - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } - - /** - * 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 accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; - - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; - - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; - - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } - - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); - - return result; - } - - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @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. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } - - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } - - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } - - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @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; - }; - - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; - - /** - * The base implementation of `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - - /** - * 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; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - 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; - } - - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection 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 baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } - - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * 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 baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } - - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which 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 iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - var low = 0, - high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } - - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); - - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } - - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} - - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } - - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } - - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); - - while (++index < length) { - var array = arrays[index], - othIndex = -1; - - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } - - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } - - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } - - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; - - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } - - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - - buffer.copy(result); - return result; - } - - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } - - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } - - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } - - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); - - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); - - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } - - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; - - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } - - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } - - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; - - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; - } - - /** - * 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 copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - - /** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; - - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } - - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - - /** - * 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) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @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 index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; - } - - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } - - /** - * 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 createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.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; - }; - } - - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } - - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } - - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; - - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; - - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } - - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` 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 createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; - - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; - - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } - - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; - } - - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); - } - - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); - - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); - } - - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` 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 wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; - } - - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } - - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @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} [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 createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; - - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; - - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); - } - - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number)) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); - - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; - } - - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; - - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - - /** - * 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 wrap. - * @param {number} bitmask The bitmask 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` - * 512 - `_.flip` - * @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 createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; - - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); - - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } - - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; - } - - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); - } - return objValue; - } - - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; - } - - /** - * 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; - } - - /** - * 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. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag: - var convert = mapToArray; - - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - - /** - * 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !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)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } - - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } - - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - - /** - * 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); - }; - - /** - * 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 = hasOwnProperty.call(realNames, result) ? array.length : 0; - - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result; - } - - /** - * Gets the argument placeholder value for `func`. - * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } - - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. - * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; - } - - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } - - /** - * Gets the property 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 = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, isStrictComparable(value)]; - } - return result; - } - - /** - * 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 = getValue(object, key); - return baseIsNative(value) ? value : undefined; - } - - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; - } - - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; - - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } - - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; - - while (++index < length) { - var data = transforms[index], - size = data.size; - - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } - - /** - * Extracts wrapper details from the `source` body comment. - * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } - - /** - * 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 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; - } - - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } - - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, 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 cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return new Ctor; - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return new Ctor; - - case symbolTag: - return cloneSymbol(object); - } - } - - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); - } - - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } - - /** - * 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) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); - } - - /** - * Checks if the given 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) - ) { - return eq(object[index], value); - } - return false; - } - - /** - * 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) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); - } - - /** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); - } - - /** - * 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]; - } - - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } - - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; - - /** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; - } - - /** - * 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); - } - - /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; - } - - /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } - - /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used 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` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined 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 < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_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; - } - - /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; - } - - /** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ - function objectToString(value) { - return nativeObjectToString.call(value); - } - - /** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; - } - - /** - * Gets the parent value at `path` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. - */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - - /** - * 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 = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; - } - - /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } - - if (key == '__proto__') { - return; - } - - return object[key]; - } - - /** - * 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://bugs.chromium.org/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 = shortOut(baseSetData); - - /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. - */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - - /** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var setToString = shortOut(baseSetToString); - - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. - * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - - /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; - } - - /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. - * - * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. - */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; - - array[rand] = array[index]; - array[index] = value; - } - array.length = size; - return array; - } - - /** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); - - /** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } - - /** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; - } - - /** - * Updates wrapper `details` based on `bitmask` flags. - * - * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. - */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - - /** - * Creates a clone of `wrapper`. - * - * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. - */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); - - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } - } - return result; - } - - /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - - /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); - - /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] - * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] - * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] - */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] - * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; - } - - /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] - */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; - } - - /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] - * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] - */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 - */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 - * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 - */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - - /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - - /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] - */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - - /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] - * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] - */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } - - /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example - * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } - */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; - } - - /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 - * - * _.head([]); - * // => undefined - */ - function head(array) { - return (array && array.length) ? array[0] : undefined; - } - - /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 - * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 - */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); - } - - /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - - /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersection([2, 1], [2, 3]); - * // => [2] - */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] - * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] - */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); - - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); - - /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example - * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' - */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); - } - - /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @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 == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } - - /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); - } - - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; - } - - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); - - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; - * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] - */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; - } - - /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] - */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; - } - - /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] - * - * console.log(pulled); - * // => ['b', 'd'] - */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); - - /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] - * - * console.log(evens); - * // => [2, 4] - */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } - var index = -1, - indexes = [], - length = array.length; - - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result; - } - - /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.reverse(array); - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - - /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @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 slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); - } - - /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([30, 50], 40); - * // => 1 - */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - - /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 - * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 - */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); - } - - /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 - */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 - */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } - - /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 - * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 - */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); - } - - /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 - */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] - */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; - } - - /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] - */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; - } - - /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.tail([1, 2, 3]); - * // => [2, 3] - */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - - /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.take([1, 2, 3], 0); - * // => [] - */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } - - /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] - * - * _.takeRight([1, 2, 3], 0); - * // => [] - */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); - } - - /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] - */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; - } - - /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] - * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] - */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; - } - - /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - - /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); - - /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniq([2, 1, 2]); - * // => [2, 1] - */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] - * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; - } - - /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] - */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; - } - - /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - - /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] - * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] - */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; - } - var result = unzip(array); - if (iteratee == null) { - return result; - } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); - } - - /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example - * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] - */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); - - /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example - * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] - */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - - /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); - - /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); - - /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ - var zip = baseRest(unzip); - - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); - } - - /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } - */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); - } - - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; - - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; - * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' - */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; - return result; - } - - /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example - * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] - */ - function tap(value, interceptor) { - interceptor(value); - return value; - } - - /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example - * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] - */ - function thru(value, interceptor) { - return interceptor(value); - } - - /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] - */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; - - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); - - /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } - * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } - */ - function wrapperChain() { - return chain(this); - } - - /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 - * - * console.log(array); - * // => [1, 2, 3] - */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - - /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } - * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } - */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; - - return { 'done': done, 'value': value }; - } - - /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true - * - * Array.from(wrapped); - * // => [1, 2] - */ - function wrapperToIterator() { - return this; - } - - /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] - * - * wrapped.value(); - * // => [1, 4] - */ - function wrapperPlant(value) { - var result, - parent = this; - - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; - } - previous.__wrapped__ = value; - return result; - } - - /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] - * - * console.log(array); - * // => [3, 2, 1] - */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - - /** - * Executes the chain sequence to resolve the unwrapped value. - * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example - * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] - */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - - /*------------------------------------------------------------------------*/ - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } - * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); - } - }); - - /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] - * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] - */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @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 } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' - */ - var find = createFind(findIndex); - - /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 - */ - var findLast = createFind(findLastIndex); - - /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] - */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); - } - - /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is 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 use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. - * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example - * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. - */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); - - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); - } - - /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); - - /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; - * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] - */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - - /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] - * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] - */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); - - /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); - } - - /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example - * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); - } - - /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] - */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - - /** - * Gets a random element from `collection`. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } - - /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] - * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] - */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); - } - - /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example - * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] - */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - - /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - - /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true - */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] - * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] - */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - - /*------------------------------------------------------------------------*/ - - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ - - /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. - */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] - */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); - } - - /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; - } - - /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * 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 doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @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 - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' - */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' - * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' - */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - - /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] - */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; - } - - /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] - * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] - */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; - } - - /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); - * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); - */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; - - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; - return result; - } - - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); - } - return result; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - - /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] - */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - - // Expose `MapCache`. - memoize.Cache = MapCache; - - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] - */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - - /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ - function once(func) { - return before(2, func); - } - - /** - * Creates a function that invokes `func` with its arguments transformed. - * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] - */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); - - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); - - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); - - /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' - */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); - - /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] - */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); - - /** - * 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://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @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 = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' - */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); - } - - /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); - * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 - */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); - - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } - - /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); - * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); - * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); - } - - /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example - * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] - */ - function unary(func) { - return ary(func, 1); - } - - /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' - */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } - - /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true - */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 - */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - - /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); - * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 - */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - - /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true - * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false - */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } - - /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ - function eq(value, other) { - return value === other || (value !== value && other !== other); - } - - /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false - * - * _.gt(1, 3); - * // => false - */ - var gt = createRelationalOperation(baseGt); - - /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false - */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); - - /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; - - /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ - var isArray = Array.isArray; - - /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true - * - * _.isArrayBuffer(new Array(2)); - * // => false - */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - - /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - - /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - - /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); - } - - /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ - var isBuffer = nativeIsBuffer || stubFalse; - - /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - * - * _.isDate('Mon April 23 2012'); - * // => false - */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - - /** - * Checks if `value` is likely a DOM element. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - * - * _.isElement(''); - * // => false - */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - - /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @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) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true - * - * object === other; - * // => false - */ - function isEqual(value, other) { - return baseIsEqual(value, other); - } - - /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; - * - * _.isEqualWith(array, other, customizer); - * // => true - */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; - } - - /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true - * - * _.isError(Error); - * // => false - */ - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); - } - - /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false - */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); - } - - /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ - function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - - /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @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(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); - } - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; - } - - /** - * Checks if `value` is classified as a `Map` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false - */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - - /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true - * - * _.isMatch(object, { 'b': 1 }); - * // => false - */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - - /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatchWith(object, source, customizer); - * // => true - */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - - /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @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 (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false - */ - function isNil(value) { - return value == null; - } - - /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @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) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; - } - - /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - - /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false - * - * _.isSafeInteger('3'); - * // => false - */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } - - /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true - * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); - } - - /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); - } - - /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - - /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @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; - } - - /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. - * @example - * - * _.isWeakMap(new WeakMap); - * // => true - * - * _.isWeakMap(new Map); - * // => false - */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - - /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. - * @example - * - * _.isWeakSet(new WeakSet); - * // => true - * - * _.isWeakSet(new Set); - * // => false - */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - - /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false - */ - var lt = createRelationalOperation(baseLt); - - /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true - * - * _.lte(3, 1); - * // => false - */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); - - /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] - */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); - } - - /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; - } - return value === value ? value : 0; - } - - /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; - } - - /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 - * - * _.toLength('3.2'); - * // => 3 - */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } - - /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); - } - - /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. - * @example - * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } - * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } - */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - - /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 - */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - } - - /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ - function toString(value) { - return value == null ? '' : baseToString(value); - } - - /*------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); - - /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } - */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); - - /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - - /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); - - /** - * Creates an array of values corresponding to `paths` of `object`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; - * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] - */ - var at = flatRest(baseAt); - - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); - } - - /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } - - return object; - }); - - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults - * @example - * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } - */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); - - /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' - */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } - - /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. - * @example - * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' - * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' - */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - - /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). - */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. - */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. - */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } - - /** - * Creates an array of function property names from own enumerable properties - * of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functions(new Foo); - * // => ['a', 'b'] - */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } - - /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions - * @example - * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] - */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } - - /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; - } - - /** - * Checks if `path` is a direct property of `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true - * - * _.has(other, 'a'); - * // => false - */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - - /** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - - /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } - */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); - - /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. - * @example - * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } - * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } - */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; - } - }, getIteratee); - - /** - * Invokes the method at `path` of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - * @example - * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] - */ - var invoke = baseRest(baseInvoke); - - /** - * 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/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @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'] - */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - - /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @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) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - - /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues - * @example - * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } - */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; - } - - /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; - } - - /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @example - * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; - * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; - * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } - */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - - /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; - * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } - */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); - - /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } - */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; - }); - - /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } - */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - - /** - * Creates an object composed of the picked `object` properties. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } - */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - - /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. - * @example - * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; - * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } - */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - - /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 - * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' - * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' - */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; - } - - /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 - * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 - */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); - } - - /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } - */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); - } - - /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) - */ - var toPairs = createToPairs(keys); - - /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) - */ - var toPairsIn = createToPairs(keysIn); - - /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. - * @example - * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } - */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; - } - - /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; - */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } - - /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 - */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } - - /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @example - * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } - */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } - - /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @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 object == null ? [] : baseValues(object, keys(object)); - } - - /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @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; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) - */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - - /*------------------------------------------------------------------------*/ - - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - * @example - * - * _.clamp(-10, -5, 5); - * // => -5 - * - * _.clamp(10, -5, 5); - * // => 5 - */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } - - /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. - * - * @static - * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight - * @example - * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false - * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); - * // => false - * - * _.inRange(-3, -2, -6); - * // => true - */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); - } - - /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. - * - * @static - * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); - } - - /*------------------------------------------------------------------------*/ - - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); - - /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - - /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } - - /** - * Checks if `string` ends with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. - * @example - * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true - */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } - - /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' - */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; - } - - /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' - */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; - } - - /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. - * @example - * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' - * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' - */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); - - /** - * Converts `string`, as space separated words, to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. - * @example - * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' - * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' - */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); - - /** - * Converts the first character of `string` to lower case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.lowerFirst('Fred'); - * // => 'fred' - * - * _.lowerFirst('FRED'); - * // => 'fRED' - */ - var lowerFirst = createCaseFirst('toLowerCase'); - - /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.pad('abc', 8); - * // => ' abc ' - * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' - * - * _.pad('abc', 3); - * // => 'abc' - */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); - } - - /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' - * - * _.padEnd('abc', 3); - * // => 'abc' - */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } - - /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. - * @example - * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' - * - * _.padStart('abc', 3); - * // => 'abc' - */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; - } - - /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. - * @example - * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] - */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } - - /** - * Repeats the given string `n` times. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. - * @example - * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' - */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); - } - - /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. - * @example - * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' - */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); - } - - /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. - * @example - * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' - */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); - - /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. - * @example - * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] - */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); - } - - /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). - * - * @static - * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. - * @example - * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' - */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); - - /** - * Checks if `string` starts with the given target string. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. - * @example - * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true - */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; - } - - /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. - * @example - * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': ''; - }, - ] -); diff --git a/tests/php/data/plugins/bad-hooks.php b/tests/php/data/plugins/bad-hooks.php deleted file mode 100644 index 2223bd2509f..00000000000 --- a/tests/php/data/plugins/bad-hooks.php +++ /dev/null @@ -1,20 +0,0 @@ -document.write("Bad action!!!");'; - } -); - -add_filter( - 'the_content', - function ( $content ) { - return $content . ''; - } -); diff --git a/tests/php/data/plugins/bad-shortcode.php b/tests/php/data/plugins/bad-shortcode.php deleted file mode 100644 index ee6a55bf731..00000000000 --- a/tests/php/data/plugins/bad-shortcode.php +++ /dev/null @@ -1,21 +0,0 @@ -document.write("Bad shortcode!!!");'; - } -); diff --git a/tests/php/data/plugins/bad-widget/bad-widget.php b/tests/php/data/plugins/bad-widget/bad-widget.php deleted file mode 100644 index 71f40d519d5..00000000000 --- a/tests/php/data/plugins/bad-widget/bad-widget.php +++ /dev/null @@ -1,42 +0,0 @@ - 'widget_bad_single' ]; - $control_ops = [ - 'width' => 500, - 'height' => 100, - 'id_base' => $id, - ]; - wp_register_sidebar_widget( - $id, - $name, - function( $args, $instance ) { - unset( $instance ); - echo $args['before_widget']; - echo $args['before_title'] . 'Bad Single Widget' . $args['after_title']; - echo ''; - echo $args['after_widget']; - }, - $widget_ops, - [] - ); - wp_register_widget_control( $id, $name, function() {}, $control_ops, [] ); - } -); diff --git a/tests/php/data/plugins/bad-widget/class-bad-widget.php b/tests/php/data/plugins/bad-widget/class-bad-widget.php deleted file mode 100644 index 62ea81229b1..00000000000 --- a/tests/php/data/plugins/bad-widget/class-bad-widget.php +++ /dev/null @@ -1,27 +0,0 @@ -document.write("Bad widget!!!");'; - echo $args['after_widget']; - } -} diff --git a/tests/php/data/themes/child-of-core/actions.php b/tests/php/data/themes/child-of-core/actions.php deleted file mode 100644 index 435121f821a..00000000000 --- a/tests/php/data/themes/child-of-core/actions.php +++ /dev/null @@ -1,8 +0,0 @@ -includeDirectory( "{$root_folder}/includes" ); -$filter->includeDirectory( "{$root_folder}/src" ); - -$coverage = new CodeCoverage( - ( new Selector() )->forLineCoverage( $filter ), - $filter -); - -$feature = getenv( 'BEHAT_FEATURE_TITLE' ); -$scenario = getenv( 'BEHAT_SCENARIO_TITLE' ); -$name = "{$feature} - {$scenario}"; - -$coverage->start( $name ); - -register_shutdown_function( - static function () use ( $coverage, $feature, $scenario, $name ) { - $coverage->stop(); - - $project_dir = getenv( 'BEHAT_PROJECT_DIR' ); - - $feature_suffix = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $feature ) ); - $scenario_suffix = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $scenario ) ); - $filename = "clover-behat/{$feature_suffix}-{$scenario_suffix}.xml"; - $destination = "{$project_dir}/build/logs/{$filename}"; - - ( new Clover() )->process( $coverage, $destination, $name ); - } -); - - - diff --git a/tests/php/register-wp-cli-commands.php b/tests/php/register-wp-cli-commands.php deleted file mode 100644 index b701ea8e0aa..00000000000 --- a/tests/php/register-wp-cli-commands.php +++ /dev/null @@ -1,13 +0,0 @@ -after_activation_site_scan = $this->injector->make( AfterActivationSiteScan::class ); - delete_option( 'amp-options' ); - } - - /** - * Tear down. - * - * @inheritdoc - */ - public function tear_down() { - parent::tear_down(); - $GLOBALS['wp_scripts'] = null; - $GLOBALS['wp_styles'] = null; - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( AfterActivationSiteScan::class, $this->after_activation_site_scan ); - $this->assertInstanceOf( Conditional::class, $this->after_activation_site_scan ); - $this->assertInstanceOf( Delayed::class, $this->after_activation_site_scan ); - $this->assertInstanceOf( Service::class, $this->after_activation_site_scan ); - $this->assertInstanceOf( Registerable::class, $this->after_activation_site_scan ); - } - - /** @return array */ - public function get_data_to_test_is_needed() { - return [ - 'not_admin_screen' => [ - 'screen_hook' => '', - 'query_params' => [], - 'expected' => false, - 'role' => 'administrator', - ], - 'not_admin_screen_with_get_activate' => [ - 'screen_hook' => '', - 'query_params' => [ 'activate' ], - 'expected' => false, - 'role' => 'administrator', - ], - 'admin_index_no_get_vars' => [ - 'screen_hook' => 'index.php', - 'query_params' => [], - 'expected' => false, - 'role' => 'administrator', - ], - 'plugins_screen_no_get_vars' => [ - 'screen_hook' => 'plugins.php', - 'query_params' => [], - 'expected' => false, - 'role' => 'administrator', - ], - 'admin_index_with_get_activate' => [ - 'screen_hook' => 'index.php', - 'query_params' => [ 'activate' ], - 'expected' => false, - 'role' => 'administrator', - ], - 'plugins_screen_with_get_activate' => [ - 'screen_hook' => 'plugins.php', - 'query_params' => [ 'activate' ], - 'expected' => true, - 'role' => 'administrator', - ], - 'plugins_screen_with_get_activate_not_admin' => [ - 'screen_hook' => 'plugins.php', - 'query_params' => [ 'activate' ], - 'expected' => false, - 'role' => 'editor', - ], - 'admin_index_with_get_activate_multi' => [ - 'screen_hook' => 'index.php', - 'query_params' => [ 'activate-multi' ], - 'expected' => false, - 'role' => 'administrator', - ], - 'plugins_screen_with_get_activate_multi' => [ - 'screen_hook' => 'plugins.php', - 'query_params' => [ 'activate-multi' ], - 'expected' => true, - 'role' => 'administrator', - ], - 'plugins_screen_with_get_activated' => [ - 'screen_hook' => 'plugins.php', - 'query_params' => [ 'activated' ], - 'expected' => false, - 'role' => 'administrator', - ], - 'themes_screen_no_get_vars' => [ - 'screen_hook' => 'themes.php', - 'query_params' => [], - 'expected' => false, - 'role' => 'administrator', - ], - 'admin_index_with_get_activated' => [ - 'screen_hook' => 'index.php', - 'query_params' => [ 'activated' ], - 'expected' => false, - 'role' => 'administrator', - ], - 'themes_screen_with_get_activated' => [ - 'screen_hook' => 'themes.php', - 'query_params' => [ 'activated' ], - 'expected' => true, - 'role' => 'administrator', - ], - 'themes_screen_with_get_activated_not_admin' => [ - 'screen_hook' => 'themes.php', - 'query_params' => [ 'activated' ], - 'expected' => false, - 'role' => 'editor', - ], - 'themes_screen_with_get_activate' => [ - 'screen_hook' => 'themes.php', - 'query_params' => [ 'activate' ], - 'expected' => false, - 'role' => 'administrator', - ], - ]; - } - - /** - * @covers ::is_needed() - * @dataProvider get_data_to_test_is_needed - * - * @param string $screen_hook Current screen hook. - * @param array $query_params GET query parameters. - * @param bool $expected Expected value. - * @param string $role User role. - */ - public function test_is_needed( $screen_hook, $query_params, $expected, $role ) { - global $pagenow; - - // If dependency support is absent, then abort because is_needed will never be true. - if ( ! Services::get( 'dependency_support' )->has_support() ) { - $this->markTestSkipped( 'WP install lacks dependency support.' ); - } - - $_GET = array_fill_keys( $query_params, true ); - - if ( ! empty( $screen_hook ) ) { - $pagenow = $screen_hook; - set_current_screen( $screen_hook ); - } - - wp_set_current_user( self::factory()->user->create( compact( 'role' ) ) ); - $this->assertEquals( $expected, AfterActivationSiteScan::is_needed() ); - } - - /** - * Tests AfterActivationSiteScan::register - * - * @covers ::register - */ - public function test_register_with_cap() { - $this->after_activation_site_scan->register(); - $this->assertEquals( 10, has_action( 'pre_current_active_plugins', [ $this->after_activation_site_scan, 'render_notice' ] ) ); - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->after_activation_site_scan, 'enqueue_assets' ] ) ); - } - - /** - * @covers ::render_notice - */ - public function test_render_notice() { - $this->assertStringContainsString( 'id="amp-site-scan-notice"', get_echo( [ $this->after_activation_site_scan, 'render_notice' ] ) ); - } - - /** @return array */ - public function get_can_validate_data() { - return [ - 'can_validate' => [ true ], - 'cannot_validate' => [ false ], - ]; - } - - /** - * @dataProvider get_can_validate_data - * @covers ::enqueue_assets - * @covers ::add_preload_rest_paths - * - * @param bool $can_validate - */ - public function test_enqueue_assets( $can_validate ) { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - if ( ! $can_validate ) { - add_filter( - 'map_meta_cap', - function ( $caps, $cap ) { - if ( AMP_Validation_Manager::VALIDATE_CAPABILITY === $cap ) { - $caps[] = 'do_not_allow'; - } - return $caps; - }, - 10, - 3 - ); - } - $this->assertEquals( $can_validate, AMP_Validation_Manager::has_cap() ); - - $handle = 'amp-site-scan-notice'; - - $rest_preloader = $this->get_private_property( $this->after_activation_site_scan, 'rest_preloader' ); - $this->assertCount( 0, $this->get_private_property( $rest_preloader, 'paths' ) ); - - $this->after_activation_site_scan->enqueue_assets(); - $this->assertTrue( wp_script_is( $handle ) ); - $this->assertTrue( wp_style_is( $handle ) ); - - $script_before = implode( '', wp_scripts()->get_data( $handle, 'before' ) ); - $this->assertStringContainsString( 'var ampSiteScanNotice', $script_before ); - $this->assertStringContainsString( 'AMP_COMPATIBLE_PLUGINS_URL', $script_before ); - $this->assertStringContainsString( 'AMP_COMPATIBLE_THEMES_URL', $script_before ); - $this->assertStringContainsString( 'VALIDATE_NONCE', $script_before ); - if ( $can_validate ) { - $this->assertStringContainsString( AMP_Validation_Manager::get_amp_validate_nonce(), $script_before ); - } else { - $this->assertStringNotContainsString( AMP_Validation_Manager::get_amp_validate_nonce(), $script_before ); - } - - if ( function_exists( 'rest_preload_api_request' ) ) { - $this->assertEqualSets( - [ - '/amp/v1/options', - '/amp/v1/scannable-urls?_fields%5B0%5D=url&_fields%5B1%5D=amp_url&_fields%5B2%5D=type&_fields%5B3%5D=label', - '/wp/v2/plugins?_fields%5B0%5D=author&_fields%5B1%5D=name&_fields%5B2%5D=plugin&_fields%5B3%5D=status&_fields%5B4%5D=version', - '/wp/v2/themes?_fields%5B0%5D=author&_fields%5B1%5D=name&_fields%5B2%5D=status&_fields%5B3%5D=stylesheet&_fields%5B4%5D=template&_fields%5B5%5D=version', - '/wp/v2/users/me', - ], - $this->get_private_property( $rest_preloader, 'paths' ) - ); - } - } - - /** - * @covers ::get_amp_compatible_plugins_url - */ - public function test_get_amp_compatible_plugins_url() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->assertStringContainsString( '/plugin-install.php?tab=amp-compatible', $this->call_private_method( $this->after_activation_site_scan, 'get_amp_compatible_plugins_url' ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'author' ] ) ); - $this->assertSame( 'https://amp-wp.org/ecosystem/plugins/', $this->call_private_method( $this->after_activation_site_scan, 'get_amp_compatible_plugins_url' ) ); - } - - /** - * @covers ::get_amp_compatible_themes_url - */ - public function test_get_amp_compatible_themes_url() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->assertStringContainsString( '/theme-install.php?browse=amp-compatible', $this->call_private_method( $this->after_activation_site_scan, 'get_amp_compatible_themes_url' ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'author' ] ) ); - $this->assertSame( 'https://amp-wp.org/ecosystem/themes/', $this->call_private_method( $this->after_activation_site_scan, 'get_amp_compatible_themes_url' ) ); - } -} diff --git a/tests/php/src/Admin/AmpPluginsTest.php b/tests/php/src/Admin/AmpPluginsTest.php deleted file mode 100644 index 27b2ca17e6a..00000000000 --- a/tests/php/src/Admin/AmpPluginsTest.php +++ /dev/null @@ -1,348 +0,0 @@ -instance = new AmpPlugins(); - - $this->original_wp_version = $wp_version; - } - - /** - * Tear down. - * - * @inheritDoc - */ - public function tear_down() { - parent::tear_down(); - - global $wp_version; - $wp_version = $this->original_wp_version; - } - - /** - * @covers ::get_plugins() - */ - public function test_get_plugins() { - - $plugins = $this->instance->get_plugins(); - - $expected_plugins = include TESTS_PLUGIN_DIR . '/includes/ecosystem-data/plugins.php'; - - $expected = array_map( - static function ( $theme ) { - - return AmpPlugins::normalize_plugin_data( $theme ); - }, - $expected_plugins - ); - - $this->assertEqualSets( $expected, $plugins ); - } - - /** - * @covers ::normalize_plugin_data() - */ - public function test_normalize_plugin_data() { - - $input = [ - 'name' => 'Plugin Name', - 'slug' => 'plugin-name', - 'ratings' => [ - '1' => 10, - 2 => 45, - ], - 'icons' => [ - '1x' => 'http://sample.test/plugin-icon.png', - ], - ]; - - $expected = [ - 'name' => 'Plugin Name', - 'slug' => 'plugin-name', - 'version' => '', - 'author' => '', - 'author_profile' => '', - 'requires' => '', - 'tested' => '', - 'requires_php' => '', - 'rating' => 0, - 'ratings' => [ - 1 => 10, - 2 => 45, - 3 => 0, - 4 => 0, - 5 => 0, - ], - 'num_ratings' => 0, - 'support_threads' => 0, - 'support_threads_resolved' => 0, - 'active_installs' => 0, - 'downloaded' => 0, - 'last_updated' => '', - 'added' => '', - 'homepage' => '', - 'short_description' => '', - 'description' => '', - 'download_link' => '', - 'tags' => [], - 'donate_link' => '', - 'icons' => [ - '1x' => 'http://sample.test/plugin-icon.png', - '2x' => '', - 'svg' => '', - ], - 'wporg' => false, - ]; - - $this->assertEquals( - $expected, - AmpPlugins::normalize_plugin_data( $input ) - ); - } - - /** - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - - $this->assertEquals( 'current_screen', AmpPlugins::get_registration_action() ); - } - - /** - * @covers ::is_needed() - */ - public function test_is_needed() { - global $wp_version; - - // Test 1: Not admin request. - $this->assertFalse( AmpPlugins::is_needed() ); - - // Test 2: Check with older version of WordPress. - $wp_version = '4.9'; - $this->assertFalse( AmpPlugins::is_needed() ); - - // Test 3: Admin request in supported WordPress . - $wp_version = '5.6'; - set_current_screen( 'index.php' ); - $this->assertTrue( AmpPlugins::is_needed() ); - - // Test 4: Filter disables. - add_filter( - 'amp_compatible_ecosystem_shown', - static function ( $shown, $type ) { - if ( 'plugins' === $type ) { - $shown = false; - } - - return $shown; - }, - 10, - 2 - ); - $this->assertFalse( AmpPlugins::is_needed() ); - - set_current_screen( 'front' ); - } - - /** - * @covers ::register() - */ - public function test_register() { - - $this->instance->register(); - $this->assertFalse( has_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_scripts' ] ) ); - - $this->assertEquals( - 10, - has_filter( 'install_plugins_tabs', [ $this->instance, 'add_tab' ] ) - ); - $this->assertEquals( - 10, - has_filter( - 'install_plugins_table_api_args_amp-compatible', - [ $this->instance, 'filter_plugins_table_api_args' ] - ) - ); - $this->assertEquals( - 10, - has_filter( 'plugins_api', [ $this->instance, 'filter_plugins_api' ] ) - ); - $this->assertEquals( - 10, - has_filter( 'plugin_install_action_links', [ $this->instance, 'filter_action_links' ] ) - ); - $this->assertEquals( - 10, - has_filter( 'plugin_row_meta', [ $this->instance, 'filter_plugin_row_meta' ] ) - ); - $this->assertEquals( - 10, - has_action( 'install_plugins_amp-compatible', 'display_plugins_table' ) - ); - - set_current_screen( 'plugin-install' ); - $this->instance->register(); - $this->assertEquals( - 10, - has_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_scripts' ] ) - ); - set_current_screen( 'front' ); - } - - /** - * @covers ::enqueue_scripts() - */ - public function test_enqueue_scripts() { - $this->instance->enqueue_scripts(); - $this->assertTrue( wp_script_is( AmpPlugins::ASSET_HANDLE ) ); - $this->assertTrue( wp_style_is( 'amp-admin' ) ); - } - - /** - * @covers ::add_tab() - */ - public function test_add_tab() { - - $this->assertArrayHasKey( - 'amp-compatible', - $this->instance->add_tab( [] ) - ); - } - - /** - * @covers ::filter_plugins_table_api_args() - */ - public function test_filter_plugins_table_api_args() { - - $output = $this->instance->filter_plugins_table_api_args(); - - $this->assertArrayHasKey( 'amp-compatible', $output ); - $this->assertArrayHasKey( 'per_page', $output ); - $this->assertArrayHasKey( 'page', $output ); - } - - /** - * @covers ::filter_plugins_api() - */ - public function test_filter_plugins_api() { - $this->instance->register(); - $response = new stdClass(); - - // Test 1: Normal request. - $response = $this->instance->filter_plugins_api( $response, 'query_themes', [ 'per_page' => 36 ] ); - $this->assertEmpty( (array) $response ); - - // Test 2: Request for AMP-compatible data. - $args = [ - 'amp-compatible' => true, - 'per_page' => 36, - ]; - - $response = $this->instance->filter_plugins_api( $response, 'query_themes', $args ); - - $this->assertIsArray( $response->info ); - $this->assertArrayHasKey( 'page', $response->info ); - $this->assertArrayHasKey( 'pages', $response->info ); - $this->assertArrayHasKey( 'results', $response->info ); - $this->assertIsArray( $response->plugins ); - } - - /** - * @covers ::filter_action_links() - */ - public function test_filter_action_links() { - - // Test 1: wporg plugins - $actions = [ - 'test action', - ]; - $plugin_data = [ - 'wporg' => true, - ]; - $output = $this->instance->filter_action_links( $actions, $plugin_data ); - $this->assertEquals( $actions, $output ); - - // Test 2: wporg plugin. - $plugin_data = [ - 'wporg' => false, - 'name' => 'Sample Plugin', - 'homepage' => 'https://sample-plugin.com', - ]; - $output = $this->instance->filter_action_links( $actions, $plugin_data ); - $this->assertIsArray( $output ); - $this->assertEquals( - sprintf( - '%s(opens in a new tab)%s', - esc_url( $plugin_data['homepage'] ), - esc_html( $plugin_data['name'] ), - esc_html__( 'Visit site', 'amp' ), - '' - ), - $output[0] - ); - } - - /** - * @covers ::filter_plugin_row_meta() - */ - public function test_filter_plugin_row_meta() { - - $this->instance->register(); - - $plugin_meta = [ - 'meta_1', - 'meta_2', - ]; - - // Test 1: None AMP plugin. - $output = $this->instance->filter_plugin_row_meta( $plugin_meta, '', [ 'slug' => 'example' ] ); - $this->assertEquals( $plugin_meta, $output ); - - // Test 2: None AMP plugin. - $output = $this->instance->filter_plugin_row_meta( $plugin_meta, '', [ 'slug' => 'akismet' ] ); - - $this->assertContains( - 'AMP Compatible', - $output - ); - } -} diff --git a/tests/php/src/Admin/AmpThemesTest.php b/tests/php/src/Admin/AmpThemesTest.php deleted file mode 100644 index 98ee5cc4fdb..00000000000 --- a/tests/php/src/Admin/AmpThemesTest.php +++ /dev/null @@ -1,242 +0,0 @@ -instance = new AmpThemes(); - - $this->original_wp_version = $wp_version; - } - - /** - * Tear down. - * - * @inheritDoc - */ - public function tear_down() { - parent::tear_down(); - - global $wp_version; - $wp_version = $this->original_wp_version; - } - - /** - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - - $this->assertEquals( 'admin_init', AmpThemes::get_registration_action() ); - } - - /** - * @covers ::is_needed() - */ - public function test_is_needed() { - global $wp_version; - - set_current_screen( 'front' ); - - // Test 1: Not admin request. - $this->assertFalse( is_admin() ); - $this->assertFalse( AmpThemes::is_needed() ); - - // Test 2: Check with older version of WordPress. - $wp_version = '4.9'; - $this->assertFalse( AmpThemes::is_needed() ); - - // Test 3: Admin request. - $wp_version = '5.6'; - set_current_screen( 'index.php' ); - $this->assertTrue( is_admin() ); - $this->assertTrue( AmpThemes::is_needed() ); - - // Test 4: Filter disables. - add_filter( - 'amp_compatible_ecosystem_shown', - static function ( $shown, $type ) { - if ( 'themes' === $type ) { - $shown = false; - } - return $shown; - }, - 10, - 2 - ); - $this->assertFalse( AmpThemes::is_needed() ); - - set_current_screen( 'front' ); - } - - /** - * @covers ::get_themes() - */ - public function test_get_themes() { - $themes = $this->instance->get_themes(); - - $expected_themes = include TESTS_PLUGIN_DIR . '/includes/ecosystem-data/themes.php'; - - $expected = array_map( - static function ( $theme ) { - return AmpThemes::normalize_theme_data( $theme ); - }, - $expected_themes - ); - - $this->assertEqualSets( $expected, $themes ); - } - - /** - * @covers ::normalize_theme_data() - */ - public function test_normalize_theme_data() { - - $input = [ - 'name' => 'sample theme', - 'author' => [ - 'user_nicename' => 'author_nicename', - ], - ]; - - $expected = [ - 'name' => 'sample theme', - 'slug' => '', - 'version' => '', - 'preview_url' => '', - 'author' => [ - 'user_nicename' => 'author_nicename', - 'profile' => '', - 'avatar' => '', - 'display_name' => '', - 'author' => '', - 'author_url' => '', - ], - 'screenshot_url' => '', - 'rating' => 0, - 'num_ratings' => 0, - 'homepage' => '', - 'description' => '', - 'requires' => '', - 'requires_php' => '', - ]; - - $this->assertEquals( - $expected, - AmpThemes::normalize_theme_data( $input ) - ); - } - - /** - * @covers ::register() - */ - public function test_register() { - - set_current_screen( 'index.php' ); - - $this->instance->register(); - - $this->assertEquals( 10, has_filter( 'themes_api', [ $this->instance, 'filter_themes_api' ] ) ); - $this->assertEquals( 10, has_filter( 'theme_row_meta', [ $this->instance, 'filter_theme_row_meta' ] ) ); - $this->assertEquals( 10, has_action( 'current_screen', [ $this->instance, 'register_hooks' ] ) ); - - set_current_screen( 'front' ); - } - - /** - * @covers ::register_hooks() - */ - public function test_register_hooks() { - - set_current_screen( 'themes' ); - - $this->instance->register_hooks(); - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_scripts' ] ) ); - } - - /** - * @covers ::enqueue_scripts() - */ - public function test_enqueue_scripts() { - $this->instance->enqueue_scripts(); - $this->assertTrue( wp_script_is( AmpThemes::ASSET_HANDLE ) ); - $this->assertTrue( wp_style_is( 'amp-admin' ) ); - } - - /** - * @covers ::filter_themes_api() - */ - public function test_filter_themes_api() { - $this->instance->register(); - $response = new stdClass(); - - // Test 1: Normal request. - $response = $this->instance->filter_themes_api( $response, 'query_themes', [ 'per_page' => 36 ] ); - $this->assertEmpty( (array) $response ); - - // Test 2: Request for AMP-compatible data. - $args = [ - 'browse' => 'amp-compatible', - 'per_page' => 36, - ]; - - $response = $this->instance->filter_themes_api( $response, 'query_themes', $args ); - $this->assertIsArray( $response->info ); - $this->assertArrayHasKey( 'page', $response->info ); - $this->assertArrayHasKey( 'pages', $response->info ); - $this->assertArrayHasKey( 'results', $response->info ); - $this->assertIsArray( $response->themes ); - } - - /** - * @covers ::filter_theme_row_meta() - */ - public function test_filter_theme_row_meta() { - - $this->assertEmpty( $this->instance->filter_theme_row_meta( [], 'non-amp' ) ); - - $this->assertEquals( - [ - 'AMP Compatible', - ], - $this->instance->filter_theme_row_meta( [], 'astra' ) - ); - - } -} diff --git a/tests/php/src/Admin/AnalyticsOptionsSubmenuTest.php b/tests/php/src/Admin/AnalyticsOptionsSubmenuTest.php deleted file mode 100644 index c314cbfa80f..00000000000 --- a/tests/php/src/Admin/AnalyticsOptionsSubmenuTest.php +++ /dev/null @@ -1,97 +0,0 @@ -injector->make( SiteHealth::class ); - - $this->options_menu_instance = new OptionsMenu( - new GoogleFonts(), - new ReaderThemes(), - new RESTPreloader(), - new DependencySupport(), - new LoadingError(), - $site_health - ); - $this->instance = new AnalyticsOptionsSubmenu( $this->options_menu_instance ); - } - - /** - * Test register. - * - * @covers ::register() - */ - public function test_register() { - $this->instance->register(); - $this->assertEquals( 99, has_action( 'admin_menu', [ $this->instance, 'add_submenu_link' ] ) ); - } - - /** - * Test add_submenu_link. - * - * @covers ::add_submenu_link() - */ - public function test_link_is_added() { - global $submenu; - - $original_submenu = $submenu; - - $test_user = self::factory()->user->create( - [ - 'role' => 'administrator', - ] - ); - wp_set_current_user( $test_user ); - - $this->options_menu_instance->add_menu_items(); - $this->instance->add_submenu_link(); - - $this->assertContains( 'Analytics', wp_list_pluck( $submenu[ $this->options_menu_instance->get_menu_slug() ], 0 ) ); - - $submenu = $original_submenu; - } -} diff --git a/tests/php/src/Admin/GoogleFontsTest.php b/tests/php/src/Admin/GoogleFontsTest.php deleted file mode 100644 index 993d207e769..00000000000 --- a/tests/php/src/Admin/GoogleFontsTest.php +++ /dev/null @@ -1,59 +0,0 @@ -instance = new GoogleFonts(); - } - - public function test__construct() { - $this->assertInstanceOf( GoogleFonts::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - } - - /** - * Tests GoogleFonts::register - * - * @covers ::get_handle - * @covers ::register - */ - public function test_register_style() { - $this->instance->register_style( wp_styles() ); - - $this->assertTrue( wp_style_is( 'amp-admin-google-fonts', 'registered' ) ); - } -} diff --git a/tests/php/src/Admin/OnboardingWizardSubmenuPageTest.php b/tests/php/src/Admin/OnboardingWizardSubmenuPageTest.php deleted file mode 100644 index b24e354f452..00000000000 --- a/tests/php/src/Admin/OnboardingWizardSubmenuPageTest.php +++ /dev/null @@ -1,244 +0,0 @@ -onboarding_wizard_submenu_page = $this->injector->make( OnboardingWizardSubmenuPage::class ); - - $this->options_menu = $this->injector->make( OptionsMenu::class ); - - $this->add_reader_themes_request_filter(); - } - - /** - * Tear down. - * - * @inheritdoc - */ - public function tear_down() { - parent::tear_down(); - $GLOBALS['wp_scripts'] = null; - $GLOBALS['wp_styles'] = null; - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( OnboardingWizardSubmenuPage::class, $this->onboarding_wizard_submenu_page ); - $this->assertInstanceOf( Delayed::class, $this->onboarding_wizard_submenu_page ); - $this->assertInstanceOf( Service::class, $this->onboarding_wizard_submenu_page ); - $this->assertInstanceOf( Registerable::class, $this->onboarding_wizard_submenu_page ); - } - - /** - * Tests OnboardingWizardSubmenuPage::register - * - * @covers ::register() - */ - public function test_register() { - $this->onboarding_wizard_submenu_page->register(); - - $this->assertEquals( 10, has_action( 'admin_head-admin_page_amp-onboarding-wizard', [ $this->onboarding_wizard_submenu_page, 'override_template' ] ) ); - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->onboarding_wizard_submenu_page, 'enqueue_assets' ] ) ); - $this->assertEquals( 10, add_filter( 'admin_title', [ $this->onboarding_wizard_submenu_page, 'override_title' ] ) ); - } - - /** - * Tests OnboardingWizardSubmenuPage::override_title() - * - * @covers ::override_title() - */ - public function test_override_title() { - set_current_screen( 'index.php' ); - - $this->assertEquals( 'Index - WordPress', $this->onboarding_wizard_submenu_page->override_title( 'Index - WordPress' ) ); - - set_current_screen( $this->onboarding_wizard_submenu_page->screen_handle() ); - - $this->assertEquals( 'AMP Onboarding Wizard - WordPress', $this->onboarding_wizard_submenu_page->override_title( ' - WordPress' ) ); - } - - /** - * Tests OnboardingWizardSubmenuPage::render() - * - * @covers ::render() - */ - public function test_render() { - wp_scripts(); // Make sure $wp_scripts global is defined for wp_check_widget_editor_deps(). - set_current_screen( 'admin_page_amp-onboarding-wizard' ); - - ob_start(); - - $this->onboarding_wizard_submenu_page->render(); - - $this->assertStringContainsString( '
', ob_get_clean() ); - } - - /** - * Tests OnboardingWizardSubmenuPage::screen_handle() - * - * @covers ::screen_handle() - */ - public function test_screen_handle() { - $this->assertEquals( $this->onboarding_wizard_submenu_page->screen_handle(), 'admin_page_amp-onboarding-wizard' ); - } - - /** @return array */ - public function get_can_validate_data() { - return [ - 'can_validate' => [ true ], - 'cannot_validate' => [ false ], - ]; - } - - /** - * Tests OnboardingWizardSubmenuPage::enqueue_assets - * - * @dataProvider get_can_validate_data - * @covers ::enqueue_assets() - * @covers ::add_preload_rest_paths() - * - * @param bool $can_validate - */ - public function test_enqueue_assets( $can_validate ) { - $handle = 'amp-onboarding-wizard'; - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - if ( ! $can_validate ) { - add_filter( - 'map_meta_cap', - function ( $caps, $cap ) { - if ( AMP_Validation_Manager::VALIDATE_CAPABILITY === $cap ) { - $caps[] = 'do_not_allow'; - } - return $caps; - }, - 10, - 3 - ); - } - $this->assertEquals( $can_validate, AMP_Validation_Manager::has_cap() ); - - $rest_preloader = $this->get_private_property( $this->onboarding_wizard_submenu_page, 'rest_preloader' ); - $this->assertCount( 0, $this->get_private_property( $rest_preloader, 'paths' ) ); - - $this->onboarding_wizard_submenu_page->enqueue_assets( $this->onboarding_wizard_submenu_page->screen_handle() ); - $this->assertTrue( wp_script_is( $handle ) ); - $this->assertTrue( wp_style_is( $handle ) ); - - $script_before = implode( '', wp_scripts()->get_data( $handle, 'before' ) ); - $this->assertStringContainsString( 'var ampSettings', $script_before ); - $this->assertStringContainsString( 'AMP_OPTIONS_KEY', $script_before ); - $this->assertStringContainsString( 'VALIDATE_NONCE', $script_before ); - if ( $can_validate ) { - $this->assertStringContainsString( AMP_Validation_Manager::get_amp_validate_nonce(), $script_before ); - } else { - $this->assertStringNotContainsString( AMP_Validation_Manager::get_amp_validate_nonce(), $script_before ); - } - - if ( function_exists( 'rest_preload_api_request' ) ) { - $this->assertEqualSets( - [ - '/amp/v1/options', - '/amp/v1/reader-themes', - '/amp/v1/scannable-urls?_fields%5B0%5D=url&_fields%5B1%5D=amp_url&_fields%5B2%5D=type&_fields%5B3%5D=label&force_standard_mode=1', - '/wp/v2/plugins?_fields%5B0%5D=author&_fields%5B1%5D=name&_fields%5B2%5D=plugin&_fields%5B3%5D=status&_fields%5B4%5D=version', - '/wp/v2/settings', - '/wp/v2/themes?_fields%5B0%5D=author&_fields%5B1%5D=name&_fields%5B2%5D=status&_fields%5B3%5D=stylesheet&_fields%5B4%5D=template&_fields%5B5%5D=version', - '/wp/v2/users/me', - ], - $this->get_private_property( $rest_preloader, 'paths' ) - ); - } - } - - /** @return array */ - public function get_referrer_links() { - return [ - 'tools_page' => [ - static function () { - return admin_url( 'tools.php' ); - }, - true, - ], - 'amp_settings_page' => [ - static function () { - return admin_url( 'admin.php?page=amp-options' ); - }, - true, - ], - 'login_page' => [ - 'wp_login_url', - false, - ], - ]; - } - - /** - * Tests OnboardingWizardSubmenuPage::get_close_link() - * - * @covers ::get_close_link() - * @dataProvider get_referrer_links() - * - * @param callable $referrer_link_callback Referrer link callback. - * @param bool $expected_referrer_close Whether the close link is expected to be the referrer. - */ - public function test_get_close_link( $referrer_link_callback, $expected_referrer_close ) { - $this->options_menu->add_menu_items(); - - $referrer = $referrer_link_callback(); - $_SERVER['HTTP_REFERER'] = $referrer; - - $this->assertEquals( - $expected_referrer_close ? $referrer : menu_page_url( AMP_Options_Manager::OPTION_NAME, false ), - $this->onboarding_wizard_submenu_page->get_close_link() - ); - } -} diff --git a/tests/php/src/Admin/OnboardingWizardSubmenuTest.php b/tests/php/src/Admin/OnboardingWizardSubmenuTest.php deleted file mode 100644 index bb6706d1781..00000000000 --- a/tests/php/src/Admin/OnboardingWizardSubmenuTest.php +++ /dev/null @@ -1,66 +0,0 @@ -instance = new OnboardingWizardSubmenu(); - } - - public function test__construct() { - $this->assertInstanceOf( OnboardingWizardSubmenu::class, $this->instance ); - $this->assertInstanceOf( Delayed::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - } - - /** - * Tests OnboardingWizardSubmenu::register - * - * @covers ::register - */ - public function test_register() { - global $submenu; - - wp_set_current_user( 1 ); - - $this->instance->register(); - - $this->assertEquals( end( $submenu[''] )[2], 'amp-onboarding-wizard' ); - } -} diff --git a/tests/php/src/Admin/OptionsMenuTest.php b/tests/php/src/Admin/OptionsMenuTest.php deleted file mode 100644 index 427fa68783d..00000000000 --- a/tests/php/src/Admin/OptionsMenuTest.php +++ /dev/null @@ -1,297 +0,0 @@ -injector->make( SiteHealth::class ); - - $this->instance = new OptionsMenu( new GoogleFonts(), new ReaderThemes(), new RESTPreloader(), new DependencySupport(), new LoadingError(), $site_health ); - - $this->add_reader_themes_request_filter(); - $this->add_home_url_loopback_request_mocking(); - } - - /** - * Tear down. - * - * @inheritdoc - */ - public function tear_down() { - $GLOBALS['wp_scripts'] = null; - $GLOBALS['wp_styles'] = null; - parent::tear_down(); - } - - /** @covers ::is_needed() */ - public function test_is_needed() { - $this->assertFalse( is_admin() ); - set_current_screen( 'index.php' ); - $this->assertTrue( OptionsMenu::is_needed() ); - - add_filter( 'amp_options_menu_is_enabled', '__return_false' ); - $this->assertFalse( OptionsMenu::is_needed() ); - - add_filter( 'amp_options_menu_is_enabled', '__return_true', 20 ); - $this->assertTrue( OptionsMenu::is_needed() ); - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( OptionsMenu::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - $this->assertInstanceOf( Conditional::class, $this->instance ); - } - - /** - * Test constants. - * - * @see OptionsMenu::ICON_BASE64_SVG - */ - public function test_constants() { - $this->assertStringStartsWith( 'data:image/svg+xml;base64,', OptionsMenu::ICON_BASE64_SVG ); - } - - /** - * Test add_hooks. - * - * @see OptionsMenu::add_hooks() - * @cogers ::register() - */ - public function test_register() { - $this->instance->register(); - $this->assertEquals( 9, has_action( 'admin_menu', [ $this->instance, 'add_menu_items' ] ) ); - - $this->assertEquals( 10, has_filter( 'plugin_action_links_amp/amp.php', [ $this->instance, 'add_plugin_action_links' ] ) ); - - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_assets' ] ) ); - } - - /** @covers ::add_plugin_action_links() */ - public function test_add_plugin_action_links() { - $links = [ - 'example' => 'example!', - ]; - - $filtered_links = $this->instance->add_plugin_action_links( $links ); - - $this->assertArrayHasKey( 'example', $filtered_links ); - $this->assertArrayHasKey( 'settings', $filtered_links ); - } - - /** @covers ::get_menu_slug() */ - public function test_get_menu_slug() { - $this->assertSame( - AMP_Options_Manager::OPTION_NAME, - $this->instance->get_menu_slug() - ); - } - - /** - * Test admin_menu. - * - * @covers ::add_menu_items() - */ - public function test_add_menu_items() { - global $_parent_pages, $submenu; - - $original_submenu = $submenu; - $original_parent_pages = $_parent_pages; - - wp_set_current_user( - self::factory()->user->create( - [ - 'role' => 'administrator', - ] - ) - ); - - $this->instance->add_menu_items(); - $this->assertArrayHasKey( 'amp-options', $_parent_pages ); - $this->assertEquals( 'amp-options', $_parent_pages['amp-options'] ); - - $this->assertArrayHasKey( 'amp-options', $submenu ); - $this->assertCount( 1, $submenu['amp-options'] ); - $this->assertEquals( 'amp-options', $submenu['amp-options'][0][2] ); - - $submenu = $original_submenu; - $_parent_pages = $original_parent_pages; - } - - /** @covers ::screen_handle() */ - public function test_screen_handle() { - $this->assertSame( - 'toplevel_page_' . $this->instance->get_menu_slug(), - $this->instance->screen_handle() - ); - } - - /** @covers ::get_analytics_vendors() */ - public function test_get_analytics_vendors() { - $vendors = $this->instance->get_analytics_vendors(); - $this->assertIsArray( $vendors ); - $this->assertNotEmpty( $vendors ); - $pairs = []; - foreach ( $vendors as $vendor ) { - $this->assertIsArray( $vendor ); - $this->assertArrayHasKey( 'value', $vendor ); - $this->assertArrayHasKey( 'label', $vendor ); - $pairs[] = $vendor['value'] . ':' . $vendor['label']; - } - $this->assertIndexedArrayContains( - [ - 'adobeanalytics:Adobe Analytics', - 'googleanalytics:Google Analytics', - 'gtag:gtag', - ], - $pairs - ); - } - - /** @covers ::enqueue_assets() */ - public function test_enqueue_assets_wrong_hook_suffix() { - $this->instance->enqueue_assets( 'nope' ); - $this->assertEquals( 0, did_action( 'amp_register_polyfills' ) ); - $this->assertFalse( wp_script_is( OptionsMenu::ASSET_HANDLE, 'enqueued' ) ); - $this->assertFalse( wp_style_is( OptionsMenu::ASSET_HANDLE, 'enqueued' ) ); - } - - /** @return array */ - public function get_can_validate_data() { - return [ - 'can_validate' => [ true ], - 'cannot_validate' => [ false ], - ]; - } - - /** - * @dataProvider get_can_validate_data - * @covers ::enqueue_assets() - * @covers ::add_preload_rest_paths() - * - * @param bool $can_validate - */ - public function test_enqueue_assets_right_hook_suffix( $can_validate ) { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - set_current_screen( $this->instance->screen_handle() ); - if ( ! $can_validate ) { - add_filter( - 'map_meta_cap', - function ( $caps, $cap ) { - if ( AMP_Validation_Manager::VALIDATE_CAPABILITY === $cap ) { - $caps[] = 'do_not_allow'; - } - return $caps; - }, - 10, - 3 - ); - } - $this->assertEquals( $can_validate, AMP_Validation_Manager::has_cap() ); - - $rest_preloader = $this->get_private_property( $this->instance, 'rest_preloader' ); - $this->assertCount( 0, $this->get_private_property( $rest_preloader, 'paths' ) ); - - $this->assertFalse( wp_script_is( OptionsMenu::ASSET_HANDLE, 'enqueued' ) ); - $this->assertFalse( wp_style_is( OptionsMenu::ASSET_HANDLE, 'enqueued' ) ); - - add_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_assets' ] ); - do_action( 'admin_enqueue_scripts', $this->instance->screen_handle() ); - $this->assertEquals( 1, did_action( 'amp_register_polyfills' ) ); - - $this->assertTrue( wp_script_is( OptionsMenu::ASSET_HANDLE, 'enqueued' ) ); - $this->assertTrue( wp_style_is( OptionsMenu::ASSET_HANDLE, 'enqueued' ) ); - - $script_before = implode( "\n", wp_scripts()->get_data( OptionsMenu::ASSET_HANDLE, 'before' ) ); - $this->assertStringContainsString( 'var ampSettings', $script_before ); - $this->assertStringContainsString( 'USER_FIELD_DEVELOPER_TOOLS_ENABLED', $script_before ); - $this->assertStringContainsString( 'USERS_RESOURCE_REST_PATH', $script_before ); - if ( $can_validate ) { - $this->assertStringContainsString( AMP_Validation_Manager::get_amp_validate_nonce(), $script_before ); - } else { - $this->assertStringNotContainsString( AMP_Validation_Manager::get_amp_validate_nonce(), $script_before ); - } - - if ( function_exists( 'rest_preload_api_request' ) ) { - $this->assertEqualSets( - [ - '/amp/v1/options', - '/amp/v1/reader-themes', - '/amp/v1/scannable-urls?_fields%5B0%5D=url&_fields%5B1%5D=amp_url&_fields%5B2%5D=type&_fields%5B3%5D=label&_fields%5B4%5D=validation_errors&_fields%5B5%5D=stale', - '/wp/v2/plugins?_fields%5B0%5D=author&_fields%5B1%5D=name&_fields%5B2%5D=plugin&_fields%5B3%5D=status&_fields%5B4%5D=version', - '/wp/v2/settings', - '/wp/v2/themes?_fields%5B0%5D=author&_fields%5B1%5D=name&_fields%5B2%5D=status&_fields%5B3%5D=stylesheet&_fields%5B4%5D=template&_fields%5B5%5D=version', - '/wp/v2/users/me', - ], - $this->get_private_property( $rest_preloader, 'paths' ) - ); - } - } - - /** - * Test render_screen for admin users. - * - * @covers ::render_screen() - */ - public function test_render_screen_for_admin_user() { - wp_set_current_user( - self::factory()->user->create( - [ - 'role' => 'administrator', - ] - ) - ); - - ob_start(); - $this->instance->render_screen(); - $this->assertStringContainsString( '
', ob_get_clean() ); - } -} diff --git a/tests/php/src/Admin/PairedBrowsingTest.php b/tests/php/src/Admin/PairedBrowsingTest.php deleted file mode 100644 index 07388bf763f..00000000000 --- a/tests/php/src/Admin/PairedBrowsingTest.php +++ /dev/null @@ -1,253 +0,0 @@ -instance = $this->injector->make( PairedBrowsing::class ); - } - - /** @covers ::is_needed() */ - public function test_is_needed() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->assertFalse( PairedBrowsing::is_needed() ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - $this->assertFalse( PairedBrowsing::is_needed() ); - - $admin_user_id = self::factory()->user->create( [ 'role' => 'administrator' ] ); - wp_set_current_user( $admin_user_id ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->assertSame( Services::get( 'dependency_support' )->has_support(), PairedBrowsing::is_needed() ); - wp_set_current_user( 0 ); - $this->assertFalse( PairedBrowsing::is_needed() ); - wp_set_current_user( $admin_user_id ); - add_filter( 'amp_dev_mode_enabled', '__return_false' ); - $this->assertFalse( PairedBrowsing::is_needed() ); - remove_filter( 'amp_dev_mode_enabled', '__return_false' ); - $this->assertSame( Services::get( 'dependency_support' )->has_support(), PairedBrowsing::is_needed() ); - - // Case where Reader theme is set to be the same as the active theme. - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::READER_THEME, get_stylesheet() ); - $this->assertSame( Services::get( 'dependency_support' )->has_support(), PairedBrowsing::is_needed() ); - } - - /** @covers ::get_requirements() */ - public function test_get_requirements() { - $this->assertSame( [ 'dependency_support' ], PairedBrowsing::get_requirements() ); - } - - /** @covers ::get_registration_action() */ - public function test_get_registration_action() { - $this->assertSame( 'wp_loaded', PairedBrowsing::get_registration_action() ); - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( PairedBrowsing::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - $this->assertInstanceOf( Conditional::class, $this->instance ); - $this->assertInstanceOf( Delayed::class, $this->instance ); - $this->assertInstanceOf( HasRequirements::class, $this->instance ); - } - - /** @covers ::register() */ - public function test_register() { - $this->instance->register(); - $this->assertEquals( PHP_INT_MAX, has_action( 'wp', [ $this->instance, 'init_frontend' ] ) ); - $this->assertEquals( 10, has_filter( 'amp_dev_mode_element_xpaths', [ $this->instance, 'filter_dev_mode_element_xpaths' ] ) ); - $this->assertEquals( 10, has_filter( 'amp_validated_url_status_actions', [ $this->instance, 'filter_validated_url_status_actions' ] ) ); - } - - /** @covers ::filter_dev_mode_element_xpaths() */ - public function test_filter_dev_mode_element_xpaths() { - $xpaths = $this->instance->filter_dev_mode_element_xpaths( [ '//div' ] ); - $this->assertCount( 2, $xpaths ); - } - - /** @covers ::filter_validated_url_status_actions() */ - public function test_filter_validated_url_status_actions() { - $post = self::factory()->post->create_and_get(); - $actions = $this->instance->filter_validated_url_status_actions( [ 'foo' => 'bar' ], $post ); - $this->assertCount( 2, $actions ); - $this->assertArrayHasKey( 'foo', $actions ); - $this->assertArrayHasKey( 'paired_browsing', $actions ); - } - - /** @covers ::init_frontend() */ - public function test_init_frontend_short_circuited() { - $post = self::factory()->post->create_and_get(); - - $assert_short_circuited = function () { - $this->assertFalse( has_action( 'template_redirect', [ $this->instance, 'ensure_app_location' ] ) ); - $this->assertFalse( has_action( 'admin_bar_menu', [ $this->instance, 'add_admin_bar_menu_item' ] ) ); - }; - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->go_to( get_permalink( $post ) ); - - // Check first short-circuit condition. - add_filter( 'amp_skip_post', '__return_true' ); - $this->assertFalse( amp_is_available() ); - $this->instance->init_frontend(); - $assert_short_circuited(); - remove_all_filters( 'amp_skip_post' ); - } - - /** - * @covers ::init_frontend() - * @covers ::init_app() - */ - public function test_init_frontend_app() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $post = self::factory()->post->create_and_get(); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->go_to( add_query_arg( PairedBrowsing::APP_QUERY_VAR, '1', get_permalink( $post ) ) ); - - add_filter( 'amp_skip_post', '__return_false' ); - $this->instance->init_frontend(); - - // Check that init_app() was called. - $this->assertEquals( 10, has_action( 'template_redirect', [ $this->instance, 'ensure_app_location' ] ) ); - $this->assertEquals( PHP_INT_MAX, has_filter( 'template_include', [ $this->instance, 'filter_template_include_for_app' ] ) ); - - // Check that init_client() was not called. - $this->assertFalse( has_action( 'admin_bar_menu', [ $this->instance, 'add_admin_bar_menu_item' ] ) ); - $this->assertEquals( 0, did_action( 'amp_register_polyfills' ) ); - } - - /** - * @covers ::init_frontend() - * @covers ::init_client() - */ - public function test_init_frontend_client() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $post = self::factory()->post->create_and_get(); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - - add_filter( 'amp_skip_post', '__return_false' ); - $this->go_to( $this->instance->paired_routing->add_endpoint( get_permalink( $post ) ) ); - $this->assertTrue( amp_is_request() ); - $this->instance->init_frontend(); - - // Check that init_client() was called. - $this->assertEquals( 102, has_action( 'admin_bar_menu', [ $this->instance, 'add_admin_bar_menu_item' ] ) ); - $this->assertEquals( 1, did_action( 'amp_register_polyfills' ) ); - $this->assertTrue( wp_script_is( 'amp-paired-browsing-client' ) ); - $printed_scripts = get_echo( 'wp_print_scripts' ); - $this->assertStringContainsString( DevMode::DEV_MODE_ATTRIBUTE, $printed_scripts ); - $this->assertStringContainsString( 'ampPairedBrowsingClientData', $printed_scripts ); - $this->assertStringContainsString( 'isAmpDocument', $printed_scripts ); - $this->assertStringContainsString( 'amp-paired-browsing-client.js', $printed_scripts ); - - // Check that init_app() was not called. - $this->assertFalse( has_action( 'template_redirect', [ $this->instance, 'ensure_app_location' ] ) ); - } - - /** @covers ::add_admin_bar_menu_item() */ - public function test_add_admin_bar_menu_item() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - require_once ABSPATH . WPINC . '/class-wp-admin-bar.php'; - add_filter( 'show_admin_bar', '__return_true' ); - $wp_admin_bar = new WP_Admin_Bar(); - - // Test when DevTools not enabled. - $this->assertFalse( $this->instance->dev_tools_user_access->is_user_enabled() ); - $this->instance->add_admin_bar_menu_item( $wp_admin_bar ); - $this->assertEmpty( $wp_admin_bar->get_node( 'amp-paired-browsing' ) ); - - // Test when DevTools enabled. - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - if ( ( new DependencySupport() )->has_support() ) { - $this->assertTrue( $this->instance->dev_tools_user_access->is_user_enabled() ); - $this->instance->add_admin_bar_menu_item( $wp_admin_bar ); - $this->assertNotEmpty( $wp_admin_bar->get_node( 'amp-paired-browsing' ) ); - } else { - $this->assertFalse( $this->instance->dev_tools_user_access->is_user_enabled() ); - } - } - - /** @covers ::get_paired_browsing_url() */ - public function test_get_paired_browsing_url() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $post_id = self::factory()->post->create(); - $this->go_to( amp_get_permalink( $post_id ) ); - - $this->assertStringContainsString( PairedBrowsing::APP_QUERY_VAR . '=1', $this->instance->get_paired_browsing_url() ); - $this->assertStringNotContainsString( amp_get_slug() . '=1', $this->instance->get_paired_browsing_url() ); - $this->assertEquals( - $this->instance->get_paired_browsing_url(), - $this->instance->get_paired_browsing_url( amp_get_current_url() ) - ); - } - - /** @covers ::ensure_app_location() */ - public function test_ensure_app_location() { - $redirected = false; - add_filter( - 'wp_redirect', - function () use ( &$redirected ) { - $redirected = true; - return false; - } - ); - - // Test that redirection is not needed. - $this->go_to( $this->instance->get_paired_browsing_url( home_url( '/' ) ) ); - $this->instance->ensure_app_location(); - $this->assertFalse( $redirected ); - - // Test that redirection is needed. - $this->go_to( add_query_arg( QueryVar::NOAMP, $this->instance->get_paired_browsing_url( home_url( '/' ) ) ) ); - $this->instance->ensure_app_location(); - $this->assertTrue( $redirected ); - } - - /** @covers ::filter_template_include_for_app() */ - public function test_filter_template_include_for_app_when_allowed() { - $this->assertEquals( 0, did_action( 'amp_register_polyfills' ) ); - - $include_path = $this->instance->filter_template_include_for_app(); - $this->assertEquals( 1, did_action( 'amp_register_polyfills' ) ); - $this->assertTrue( wp_style_is( 'amp-paired-browsing-app' ) ); - $this->assertTrue( wp_script_is( 'amp-paired-browsing-app' ) ); - - ob_start(); - load_template( $include_path ); - $template = ob_get_clean(); - - $this->assertStringContainsString( 'amp-paired-browsing-app.css', $template ); - $this->assertStringContainsString( 'amp-paired-browsing-app.js', $template ); - $this->assertStringContainsString( 'ampPairedBrowsingAppData', $template ); - $this->assertStringContainsString( 'ampPairedBrowsingQueryVar', $template ); - } -} diff --git a/tests/php/src/Admin/PluginActivationNoticeTest.php b/tests/php/src/Admin/PluginActivationNoticeTest.php deleted file mode 100644 index 817c9e799da..00000000000 --- a/tests/php/src/Admin/PluginActivationNoticeTest.php +++ /dev/null @@ -1,97 +0,0 @@ -plugin_activation_notice = new PluginActivationNotice(); - delete_option( 'amp-options' ); - } - - /** - * Tests PluginActivationNotice::register - * - * @covers ::register - */ - public function test_register() { - $this->plugin_activation_notice->register(); - $this->assertEquals( 10, has_action( 'admin_notices', [ $this->plugin_activation_notice, 'render_notice' ] ) ); - } - - /** - * @covers ::render_notice - */ - public function test_user_sees_notice() { - set_current_screen( 'plugins' ); - $this->assertStringContainsString( 'class="amp-plugin-notice', get_echo( [ $this->plugin_activation_notice, 'render_notice' ] ) ); - - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertStringNotContainsString( 'class="amp-plugin-notice', get_echo( [ $this->plugin_activation_notice, 'render_notice' ] ) ); - } - - /** - * @covers ::render_notice - */ - public function test_user_can_dismiss_notice() { - wp_set_current_user( 1 ); - update_user_meta( get_current_user_id(), 'dismissed_wp_pointers', PluginActivationNotice::NOTICE_ID ); - - set_current_screen( 'plugins' ); - $this->assertEmpty( get_echo( [ $this->plugin_activation_notice, 'render_notice' ] ) ); - - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertEmpty( get_echo( [ $this->plugin_activation_notice, 'render_notice' ] ) ); - - delete_user_meta( get_current_user_id(), 'dismissed_wp_pointers' ); - - $GLOBALS['current_screen'] = null; - } - - /** - * @covers ::render_notice - */ - public function test_notice_doesnt_show_if_wizard_completed() { - $original_option = AMP_Options_Manager::get_option( Option::PLUGIN_CONFIGURED ); - - AMP_Options_Manager::update_option( Option::PLUGIN_CONFIGURED, true ); - - set_current_screen( 'plugins' ); - $this->assertEmpty( get_echo( [ $this->plugin_activation_notice, 'render_notice' ] ) ); - - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertEmpty( get_echo( [ $this->plugin_activation_notice, 'render_notice' ] ) ); - - AMP_Options_Manager::update_option( Option::PLUGIN_CONFIGURED, $original_option ); - - $GLOBALS['current_screen'] = null; - } -} diff --git a/tests/php/src/Admin/PluginRowMetaTest.php b/tests/php/src/Admin/PluginRowMetaTest.php deleted file mode 100644 index 33f566bf619..00000000000 --- a/tests/php/src/Admin/PluginRowMetaTest.php +++ /dev/null @@ -1,91 +0,0 @@ -instance = new PluginRowMeta(); - } - - public function test__construct() { - $this->assertInstanceOf( PluginRowMeta::class, $this->instance ); - $this->assertInstanceOf( Delayed::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - } - - /** - * Test ::get_registration_action(). - * - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - self::assertEquals( 'admin_init', PluginRowMeta::get_registration_action() ); - } - - /** - * Test ::register(). - * - * @covers ::register() - */ - public function test_register() { - $this->instance->register(); - - self::assertEquals( 10, has_filter( 'plugin_row_meta', [ $this->instance, 'get_plugin_row_meta' ] ) ); - } - - /** - * Test ::get_plugin_row_meta(). - * - * @covers ::get_plugin_row_meta() - */ - public function test_get_plugin_row_meta() { - $initial_meta = [ - 'Link 1', - 'Link 2', - ]; - - $this->assertEquals( $initial_meta, $this->instance->get_plugin_row_meta( $initial_meta, 'foo.php' ) ); - - $expected_meta = array_merge( - $initial_meta, - [ - 'Leave review', - ] - ); - - $this->assertEquals( $expected_meta, $this->instance->get_plugin_row_meta( $initial_meta, 'amp/amp.php' ) ); - - } -} diff --git a/tests/php/src/Admin/PolyfillsTest.php b/tests/php/src/Admin/PolyfillsTest.php deleted file mode 100644 index 0785ea46ad3..00000000000 --- a/tests/php/src/Admin/PolyfillsTest.php +++ /dev/null @@ -1,109 +0,0 @@ -instance = new Polyfills(); - } - - /** - * Tear down. - * - * @inheritdoc - */ - public function tear_down() { - global $wp_scripts, $wp_styles; - $wp_scripts = null; - $wp_styles = null; - parent::tear_down(); - } - - public function test__construct() { - $this->assertInstanceOf( Polyfills::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Delayed::class, $this->instance ); - $this->assertInstanceOf( Conditional::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - $this->assertInstanceOf( HasRequirements::class, $this->instance ); - } - - /** @covers ::get_requirements() */ - public function test_get_requirements() { - $this->assertSame( [ 'dependency_support' ], Polyfills::get_requirements() ); - } - - /** - * Tests Polyfills::register - * - * @covers ::register - * @covers ::register_shimmed_scripts - * @covers ::register_shimmed_styles - */ - public function test_registration() { - if ( function_exists( 'is_gutenberg_page' ) ) { - $this->assertFalse( is_gutenberg_page() ); - } - if ( function_exists( 'get_current_screen' ) ) { - $screen = get_current_screen(); - $this->assertTrue( empty( $screen->is_block_editor ) ); - } - - $this->instance->register(); - - // These should pass in WP < 5.6. - $this->assertTrue( wp_script_is( 'lodash', 'registered' ) ); - $this->assertStringContainsString( '_.noConflict();', wp_scripts()->print_inline_script( 'lodash', 'after', false ) ); - - $this->assertTrue( wp_script_is( 'wp-api-fetch', 'registered' ) ); - $this->assertStringContainsString( 'createRootURLMiddleware', wp_scripts()->print_inline_script( 'wp-api-fetch', 'after', false ) ); - $this->assertStringContainsString( 'createNonceMiddleware', wp_scripts()->print_inline_script( 'wp-api-fetch', 'after', false ) ); - - $this->assertTrue( wp_script_is( 'wp-hooks', 'registered' ) ); - $this->assertTrue( wp_script_is( 'wp-i18n', 'registered' ) ); - $this->assertTrue( wp_script_is( 'wp-dom-ready', 'registered' ) ); - $this->assertTrue( wp_script_is( 'wp-polyfill', 'registered' ) ); - $this->assertTrue( wp_script_is( 'wp-url', 'registered' ) ); - - $this->assertTrue( wp_style_is( 'wp-components', 'registered' ) ); - } -} diff --git a/tests/php/src/Admin/RESTPreloaderTest.php b/tests/php/src/Admin/RESTPreloaderTest.php deleted file mode 100644 index e01acc7d0a2..00000000000 --- a/tests/php/src/Admin/RESTPreloaderTest.php +++ /dev/null @@ -1,64 +0,0 @@ -markTestSkipped( 'Requires WordPress 5.0.' ); - } - - $this->instance = new RESTPreloader(); - } - - /** - * @covers ::add_preloaded_path - * @covers ::preload_data - */ - public function test_adding_preloaded_data() { - global $wp_scripts; - - set_current_screen( 'index.php' ); - $this->instance->add_preloaded_path( '/wp/v2/posts' ); - do_action( 'admin_enqueue_scripts' ); - - $result = end( $wp_scripts->registered['wp-api-fetch']->extra['after'] ); - - $this->assertEquals( - 'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( {"\/wp\/v2\/posts":{"body":[],"headers":{"X-WP-Total":0,"X-WP-TotalPages":0}}} ) );', - $result - ); - - set_current_screen( 'front' ); - } -} diff --git a/tests/php/src/Admin/ReaderThemesTest.php b/tests/php/src/Admin/ReaderThemesTest.php deleted file mode 100644 index 9f47f43aa26..00000000000 --- a/tests/php/src/Admin/ReaderThemesTest.php +++ /dev/null @@ -1,384 +0,0 @@ -markTestSkipped( 'Requires WordPress 5.0.' ); - } - - delete_transient( 'amp_themes_wporg' ); - $this->add_reader_themes_request_filter(); - - switch_theme( 'twentytwenty' ); - $this->reader_themes = new ReaderThemes(); - - $this->register_core_themes(); - } - - public function tear_down() { - $this->restore_theme_directories(); - parent::tear_down(); - } - - /** - * Test for get_themes. - * - * @covers ::get_themes - * @covers ::get_default_reader_themes - * @covers ::get_legacy_theme - */ - public function test_get_themes() { - register_theme_directory( __DIR__ . '/../../data/themes' ); - delete_site_transient( 'theme_roots' ); - - $extra_theme_and_plugin_headers = new ExtraThemeAndPluginHeaders(); - $extra_theme_and_plugin_headers->register(); - - $themes = $this->reader_themes->get_themes(); - $this->assertEquals( 'legacy', end( $themes )['slug'] ); - - $keys = [ - 'name', - 'slug', - 'preview_url', - 'screenshot_url', - 'homepage', - 'description', - 'requires', - 'requires_php', - 'availability', - ]; - foreach ( $themes as $theme ) { - $this->assertEqualSets( $keys, array_keys( $theme ) ); - } - - AMP_Options_Manager::update_option( Option::READER_THEME, 'child-of-core' ); - - $themes = ( new ReaderThemes() )->get_themes(); - - $available_theme_slugs = wp_list_pluck( $themes, 'slug' ); - $this->assertContains( 'child-of-core', $available_theme_slugs ); - $this->assertNotContains( 'custom', $available_theme_slugs ); - $this->assertNotContains( 'with-legacy', $available_theme_slugs ); - } - - /** - * Test that themes API success does not result in a WP_Error. - * - * @covers ::get_themes - * @covers ::get_default_reader_themes - */ - public function test_themes_api_success() { - $this->reader_themes->get_themes(); - - $this->assertNull( $this->reader_themes->get_themes_api_error() ); - } - - /** - * Test that a themes API failure results in a WP_Error. - * - * @covers ::get_themes - * @covers ::get_default_reader_themes - */ - public function test_themes_api_failure() { - add_filter( 'themes_api_result', '__return_null' ); - - $this->reader_themes->get_themes(); - - $error = $this->reader_themes->get_themes_api_error(); - $this->assertWPError( $error ); - $this->assertEquals( - 'The request for reader themes from WordPress.org resulted in an invalid response. Check your Site Health to confirm that your site can communicate with WordPress.org. Otherwise, please try again later or contact your host.', - $error->get_error_message() - ); - - remove_filter( 'themes_api_result', '__return_null' ); - } - - /** - * Test that a themes API response with an empty themes array results in a WP_Error. - * - * @covers ::get_themes - * @covers ::get_default_reader_themes - */ - public function test_themes_api_empty_array() { - $filter_cb = static function() { - return (object) [ 'themes' => [] ]; - }; - add_filter( 'themes_api_result', $filter_cb ); - - $this->reader_themes->get_themes(); - - $error = $this->reader_themes->get_themes_api_error(); - $this->assertWPError( $this->reader_themes->get_themes_api_error() ); - $this->assertEquals( - 'The default reader themes cannot be displayed because a plugin appears to be overriding the themes response from WordPress.org.', - $error->get_error_message() - ); - } - - /** - * Test that an error is stored in state when themes_api returns an error. - * - * @covers ::get_themes - * @covers ::get_default_reader_themes - */ - public function test_themes_api_wp_error() { - $filter_cb = static function() { - return new WP_Error( - 'amp_test_error', - 'Test message' - ); - }; - add_filter( 'themes_api_result', $filter_cb ); - - $this->reader_themes->get_themes(); - - $error = $this->reader_themes->get_themes_api_error(); - $this->assertWPError( $this->reader_themes->get_themes_api_error() ); - $this->assertStringStartsWith( - 'The request for reader themes from WordPress.org resulted in an invalid response. Check your Site Health to confirm that your site can communicate with WordPress.org. Otherwise, please try again later or contact your host.', - $error->get_error_message() - ); - if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) { - $this->assertStringContainsString( 'Test message', $error->get_error_message() ); - $this->assertStringContainsString( 'amp_test_error', $error->get_error_message() ); - } - } - - /** - * Test for get_reader_theme_by_slug. - * - * @covers ::get_reader_theme_by_slug - */ - public function test_get_reader_theme_by_slug() { - $this->assertFalse( $this->reader_themes->get_reader_theme_by_slug( 'some-theme' ) ); - $this->assertArrayHasKey( 'slug', $this->reader_themes->get_reader_theme_by_slug( 'legacy' ) ); - } - - /** - * Provides test themes to test availability. - * - * @return array - */ - public function get_availability_test_themes() { - return [ - 'from_wp_future' => [ - static function () { - return ReaderThemes::STATUS_NON_INSTALLABLE; - }, - false, - [ - 'name' => 'Some Theme', - 'requires' => '99.9', - 'requires_php' => '5.2', - 'slug' => 'from_wp_future', - ], - ], - 'from_php_future' => [ - static function () { - return ReaderThemes::STATUS_NON_INSTALLABLE; - }, - false, - [ - 'name' => 'Some Theme', - 'requires' => '4.9', - 'requires_php' => '99.9', - 'slug' => 'from_php_future', - ], - ], - 'non_reader_theme' => [ - static function () { - return wp_get_theme( 'neve' )->exists() ? ReaderThemes::STATUS_INSTALLED : ReaderThemes::STATUS_INSTALLABLE; - }, - true, - [ - 'name' => 'Neve', - 'requires' => false, - 'requires_php' => '5.2', - 'slug' => 'neve', - ], - ], - 'twentytwelve_not_requiring_wp_version' => [ - static function () { - return wp_get_theme( 'twentytwelve' )->exists() ? ReaderThemes::STATUS_INSTALLED : ReaderThemes::STATUS_NON_INSTALLABLE; - }, - true, - [ - 'name' => 'Some Theme', - 'requires' => false, - 'requires_php' => '5.2', - 'slug' => 'twentytwelve', - ], - ], - 'twentytwelve_not_requiring_php_version' => [ - static function () { - return wp_get_theme( 'twentysixteen' )->exists() ? ReaderThemes::STATUS_INSTALLED : ReaderThemes::STATUS_NON_INSTALLABLE; - }, - true, - [ - 'name' => 'Some Theme', - 'requires' => '4.9', - 'requires_php' => false, - 'slug' => 'twentysixteen', - ], - ], - 'twentytwenty_active' => [ - static function () { - return ReaderThemes::STATUS_ACTIVE; - }, - true, - [ - 'name' => 'WordPress Default', - 'requires' => '4.4', - 'requires_php' => '5.2', - 'slug' => 'twentytwenty', - ], - ], - ]; - } - - /** - * Test for get_theme_availability. - * - * @covers ::get_theme_availability - * @covers ::can_install_theme - * - * @dataProvider get_availability_test_themes - * - * @param Closure $get_expected Expected. - * @param bool $can_install Can install. - * @param array $theme Theme. - */ - public function test_get_theme_availability( $get_expected, $can_install, $theme ) { - wp_set_current_user( $this->factory()->user->create( [ 'role' => 'administrator' ] ) ); - $expected = $get_expected(); - $this->assertEquals( $expected, $this->reader_themes->get_theme_availability( $theme ) ); - $this->assertEquals( $can_install, $this->reader_themes->can_install_theme( $theme ) ); - } - - /** - * Tests for can_install_theme. - * - * @covers ::can_install_theme - */ - public function test_can_install_theme() { - $core_theme = [ - 'name' => 'Twenty Twelve', - 'requires' => false, - 'requires_php' => '5.2', - 'slug' => 'twentytwelve', - ]; - - $neve_theme = [ - 'name' => 'Neve', - 'requires' => false, - 'requires_php' => '5.2', - 'slug' => 'neve', - ]; - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'author' ] ) ); - $this->assertFalse( $this->reader_themes->can_install_theme( $core_theme ) ); - $this->assertFalse( $this->reader_themes->can_install_theme( $neve_theme ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->assertTrue( $this->reader_themes->can_install_theme( $core_theme ) ); - $this->assertTrue( $this->reader_themes->can_install_theme( $neve_theme ) ); - - $core_theme['requires'] = '999.9'; - $this->assertFalse( $this->reader_themes->can_install_theme( $core_theme ) ); - - $core_theme['requires'] = false; - $core_theme['requires_php'] = '999.9'; - $this->assertFalse( $this->reader_themes->can_install_theme( $core_theme ) ); - } - - /** - * Tests for theme_data_exists. - * - * @covers ::theme_data_exists - */ - public function test_theme_data_exists() { - if ( ( new ReaderThemes() )->theme_data_exists( 'neve' ) ) { - $this->markTestSkipped( 'Neve is already installed.' ); - } - - $neve_theme = [ - 'name' => 'Neve', - 'requires' => false, - 'requires_php' => '5.2', - 'slug' => 'neve', - ]; - $append_neve_theme = static function ( $themes ) use ( $neve_theme ) { - $themes[] = $neve_theme; - return $themes; - }; - - add_filter( 'amp_reader_themes', $append_neve_theme ); - - $this->assertTrue( ( new ReaderThemes() )->theme_data_exists( 'neve' ) ); - - remove_filter( 'amp_reader_themes', $append_neve_theme ); - } - - /** @covers ::using_fallback_theme */ - public function test_using_fallback_theme() { - $reader_themes = new ReaderThemes(); - AMP_Options_Manager::update_options( - [ - Option::THEME_SUPPORT => 'reader', - Option::READER_THEME => ReaderThemes::DEFAULT_READER_THEME, - ] - ); - $this->assertFalse( $reader_themes->using_fallback_theme() ); - - AMP_Options_Manager::update_option( Option::READER_THEME, 'foobar' ); - $this->assertTrue( $reader_themes->using_fallback_theme() ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->assertFalse( $reader_themes->using_fallback_theme() ); - } -} diff --git a/tests/php/src/Admin/ReenableCssTransientCachingAjaxActionTest.php b/tests/php/src/Admin/ReenableCssTransientCachingAjaxActionTest.php deleted file mode 100644 index 1d9f633182e..00000000000 --- a/tests/php/src/Admin/ReenableCssTransientCachingAjaxActionTest.php +++ /dev/null @@ -1,204 +0,0 @@ -instance = new ReenableCssTransientCachingAjaxAction(); - } - - /** - * Tear down. - * - * @inheritdoc - */ - public function tear_down() { - global $wp_scripts; - $wp_scripts = null; - - parent::tear_down(); - } - - public function test__construct() { - $this->assertInstanceOf( ReenableCssTransientCachingAjaxAction::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - } - - /** - * Tests ReenableCssTransientCachingAjaxAction::register - * - * @covers ::register - */ - public function test_register() { - $this->instance->register(); - - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->instance, 'register_ajax_script' ] ) ); - $this->assertEquals( 10, has_action( 'wp_ajax_amp_reenable_css_transient_caching', [ $this->instance, 'reenable_css_transient_caching' ] ) ); - } - - /** @covers ::register_ajax_script */ - public function test_register_ajax_script_not_hook() { - $this->instance->register_ajax_script( 'nope' ); - $this->assertFalse( wp_script_is( 'wp-util', 'enqueued' ) ); - $this->assertFalse( wp_script_is( 'jquery', 'enqueued' ) ); - $this->assertEmpty( wp_scripts()->get_data( 'wp-util', 'after' ) ); - } - - /** @return array */ - public function get_data_to_test_register_ajax_script_yes_hook() { - return [ - 'without_site_health_plugin' => [ - 'hook_suffix' => 'site-health.php', - ], - 'with_site_health_plugin' => [ - 'hook_suffix' => 'tools_page_health-check', - ], - ]; - } - - /** - * @dataProvider get_data_to_test_register_ajax_script_yes_hook - * @covers ::register_ajax_script - * @param string $hook_suffix - */ - public function test_register_ajax_script_yes_hook( $hook_suffix ) { - $this->instance->register_ajax_script( $hook_suffix ); - $this->assertTrue( wp_script_is( 'jquery', 'enqueued' ) ); - $this->assertTrue( wp_script_is( 'wp-util', 'enqueued' ) ); - $after = wp_scripts()->get_data( 'wp-util', 'after' ); - $this->assertStringContainsString( '$( \'.health-check-body\' )', implode( "\n", $after ) ); - } - - /** @return array */ - public function get_data_to_test_reenable_css_transient_caching() { - return [ - 'no_nonce' => [ - 'initial_value' => true, - 'nonce_action' => null, - 'user' => null, - 'expected_output' => '-1', - 'final_value' => true, - ], - 'no_auth' => [ - 'initial_value' => true, - 'nonce_action' => ReenableCssTransientCachingAjaxAction::AJAX_ACTION, - 'user' => null, - 'expected_output' => '{"success":false,"data":"Unauthorized."}', - 'final_value' => true, - ], - 'bad_auth' => [ - 'initial_value' => true, - 'nonce_action' => ReenableCssTransientCachingAjaxAction::AJAX_ACTION, - 'user' => 'author', - 'expected_output' => '{"success":false,"data":"Unauthorized."}', - 'final_value' => true, - ], - 'good_auth_bad_nonce' => [ - 'initial_value' => true, - 'nonce_action' => 'other_action', - 'user' => 'administrator', - 'expected_output' => '-1', - 'final_value' => true, - ], - 'good_auth' => [ - 'initial_value' => true, - 'nonce_action' => ReenableCssTransientCachingAjaxAction::AJAX_ACTION, - 'user' => 'administrator', - 'expected_output' => '{"success":true,"data":"CSS transient caching was re-enabled."}', - 'final_value' => false, - ], - 'good_auth_no_change' => [ - 'initial_value' => false, - 'nonce_action' => ReenableCssTransientCachingAjaxAction::AJAX_ACTION, - 'user' => 'administrator', - 'expected_output' => '{"success":false,"data":"CSS transient caching could not be re-enabled."}', - 'final_value' => false, - ], - ]; - } - - /** - * @covers ::reenable_css_transient_caching - * @dataProvider get_data_to_test_reenable_css_transient_caching - * - * @param bool $initial_value - * @param string|null $nonce_action - * @param string|null $user - * @param string $expected_output - * @param bool $final_value - */ - public function test_reenable_css_transient_caching( $initial_value, $nonce_action, $user, $expected_output, $final_value ) { - AMP_Options_Manager::update_option( Option::DISABLE_CSS_TRANSIENT_CACHING, $initial_value ); - add_filter( 'wp_doing_ajax', '__return_true' ); - add_filter( - 'wp_die_ajax_handler', - static function () { - return function ( $message ) { - throw new WPDieException( $message ); - }; - } - ); - - if ( $user ) { - wp_set_current_user( self::factory()->user->create( [ 'role' => $user ] ) ); - } - if ( $nonce_action ) { - $_REQUEST['nonce'] = wp_create_nonce( $nonce_action ); - } - - ob_start(); - $exception = null; - try { - $this->instance->reenable_css_transient_caching(); - } catch ( Exception $ex ) { - $exception = $ex; - } - $output = ob_get_clean(); - $this->assertInstanceOf( WPDieException::class, $exception ); - $actual_output = $output . $exception->getMessage(); - - $this->assertEquals( $expected_output, $actual_output ); - $this->assertEquals( - $final_value, - AMP_Options_Manager::get_option( Option::DISABLE_CSS_TRANSIENT_CACHING ) - ); - } -} diff --git a/tests/php/src/Admin/SiteHealthTest.php b/tests/php/src/Admin/SiteHealthTest.php deleted file mode 100644 index 0e5a0b5434a..00000000000 --- a/tests/php/src/Admin/SiteHealthTest.php +++ /dev/null @@ -1,1182 +0,0 @@ -get_container() - ->get( 'injector' ); - - $this->instance = $injector->make( SiteHealth::class ); - - remove_theme_support( 'amp' ); - foreach ( get_post_types_by_support( 'amp' ) as $post_type ) { - remove_post_type_support( $post_type, 'amp' ); - } - delete_option( AMP_Options_Manager::OPTION_NAME ); - - $this->was_wp_using_ext_object_cache = wp_using_ext_object_cache(); - - $this->original_wp_rest_server = isset( $GLOBALS['wp_rest_server'] ) ? $GLOBALS['wp_rest_server'] : null; - $GLOBALS['wp_rest_server'] = null; - - $this->add_home_url_loopback_request_mocking(); - } - - /** - * Tears down after each test. - * - * @inheritDoc - */ - public function tear_down() { - wp_using_ext_object_cache( $this->was_wp_using_ext_object_cache ); - $GLOBALS['wp_rest_server'] = $this->original_wp_rest_server; - unset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ); - - parent::tear_down(); - } - - /** - * Test init. - * - * @covers ::register() - */ - public function test_register() { - $this->instance->register(); - $this->assertEquals( 10, has_filter( 'site_status_tests', [ $this->instance, 'add_tests' ] ) ); - $this->assertEquals( 10, has_action( 'rest_api_init', [ $this->instance, 'register_async_test_endpoints' ] ) ); - $this->assertEquals( 10, has_filter( 'debug_information', [ $this->instance, 'add_debug_information' ] ) ); - $this->assertEquals( 10, has_filter( 'site_status_test_result', [ $this->instance, 'modify_test_result' ] ) ); - $this->assertEquals( 10, has_filter( 'site_status_test_php_modules', [ $this->instance, 'add_extensions' ] ) ); - - $this->assertEquals( 10, has_action( 'admin_print_styles-site-health.php', [ $this->instance, 'add_styles' ] ) ); - $this->assertEquals( 10, has_action( 'admin_print_styles-tools_page_health-check', [ $this->instance, 'add_styles' ] ) ); - } - - /** - * @covers ::register_async_test_endpoints() - */ - public function test_register_async_test_endpoints() { - $GLOBALS['wp_rest_server'] = null; - remove_all_actions( 'rest_api_init' ); - - $this->instance->register(); - $server = rest_get_server(); - - $routes = $server->get_routes( SiteHealth::REST_API_NAMESPACE ); - - $endpoint = '/' . SiteHealth::REST_API_NAMESPACE . SiteHealth::REST_API_PAGE_CACHE_ENDPOINT; - $this->assertArrayHasKey( $endpoint, $routes ); - $this->assertCount( 1, $routes[ $endpoint ] ); - $route = $routes[ $endpoint ][0]; - - $this->assertEquals( - [ 'GET' => true ], - $route['methods'] - ); - - $this->assertEquals( - [ $this->instance, 'page_cache' ], - $route['callback'] - ); - - $this->assertIsCallable( $route['permission_callback'] ); - - $this->assertFalse( call_user_func( $route['permission_callback'] ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'author' ] ) ); - $this->assertFalse( call_user_func( $route['permission_callback'] ) ); - - // Prior to WordPress 5.2, the view_site_health_checks cap didn't exist because Site Health didn't exist. - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - if ( version_compare( get_bloginfo( 'version' ), '5.2', '>=' ) ) { - $this->assertTrue( call_user_func( $route['permission_callback'] ) ); - } else { - $this->assertFalse( call_user_func( $route['permission_callback'] ) ); - } - } - - /** - * Test add_tests. - * - * @covers ::add_tests() - */ - public function test_add_tests() { - $tests = $this->instance->add_tests( [] ); - $this->assertArrayHasKey( 'direct', $tests ); - $this->assertArrayHasKey( 'amp_persistent_object_cache', $tests['direct'] ); - - if ( version_compare( get_bloginfo( 'version' ), '5.6', '>=' ) ) { - $this->assertArrayHasKey( 'amp_page_cache', $tests['async'] ); - } elseif ( array_key_exists( 'async', $tests ) ) { - $this->assertArrayNotHasKey( 'amp_page_cache', $tests['async'] ); - } - - $this->assertArrayHasKey( 'amp_curl_multi_functions', $tests['direct'] ); - $this->assertArrayNotHasKey( 'amp_icu_version', $tests['direct'] ); - $this->assertArrayHasKey( 'amp_xdebug_extension', $tests['direct'] ); - $this->assertEquals( QueryVar::AMP, amp_get_slug() ); - $this->assertArrayNotHasKey( 'amp_slug_definition_timing', $tests['direct'] ); - - // Test that the the ICU version test is added only when site URL is an IDN. - add_filter( 'site_url', [ self::class, 'get_idn' ], 10, 4 ); - add_filter( 'amp_query_var', [ self::class, 'get_lite_query_var' ] ); - - $tests = $this->instance->add_tests( [] ); - $this->assertArrayHasKey( 'amp_icu_version', $tests['direct'] ); - $this->assertArrayHasKey( 'amp_slug_definition_timing', $tests['direct'] ); - - remove_filter( 'site_url', [ self::class, 'get_idn' ] ); - remove_filter( 'amp_query_var', [ self::class, 'get_lite_query_var' ] ); - } - - /** - * Test get_persistent_object_cache_availability. - * - * @covers ::persistent_object_cache() - * @covers ::get_persistent_object_cache_availability() - * @covers ::get_persistent_object_cache_learn_more_action() - */ - public function test_get_persistent_object_cache_availability() { - $data = [ - 'test' => 'amp_persistent_object_cache', - ]; - - wp_using_ext_object_cache( false ); - - $page_cache_status = [ - 'advanced_cache_present' => false, - 'page_caching_response_headers' => [ [], [], [] ], - 'response_timing' => [ 200, 300, 400 ], - ]; - - set_transient( SiteHealth::HAS_PAGE_CACHING_TRANSIENT_KEY, $page_cache_status ); - $output = $this->instance->persistent_object_cache(); - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'status' => 'recommended', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'orange', - ], - ] - ), - $output - ); - $this->assertStringContainsString( 'Please check with your host for what persistent caching services are available.', $output['description'] ); - $this->assertStringNotContainsString( 'Since page caching was detected', $output['description'] ); - $this->assertStringContainsString( '/persistent-object-caching/', $output['actions'] ); - - $page_cache_status = [ - 'advanced_cache_present' => true, - 'page_caching_response_headers' => [ [ 'x-cache' ], [ 'x-cache' ], [ 'x-cache' ] ], - 'response_timing' => [ 200, 300, 400 ], - ]; - - set_transient( SiteHealth::HAS_PAGE_CACHING_TRANSIENT_KEY, $page_cache_status ); - - $output = $this->instance->persistent_object_cache(); - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'status' => 'good', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'blue', - ], - ] - ), - $output - ); - $this->assertStringContainsString( 'Please check with your host for what persistent caching services are available.', $output['description'] ); - $this->assertStringContainsString( 'Since page caching was detected', $output['description'] ); - $this->assertStringContainsString( '/persistent-object-caching/', $output['actions'] ); - - wp_using_ext_object_cache( true ); - $output = $this->instance->persistent_object_cache(); - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'label' => 'Persistent object caching is enabled', - 'status' => 'good', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'green', - ], - ] - ), - $output - ); - $this->assertStringNotContainsString( 'Please check with your host for what persistent caching services are available.', $output['description'] ); - $this->assertStringNotContainsString( 'Since page caching was detected', $output['description'] ); - $this->assertStringContainsString( '/persistent-object-caching/', $output['actions'] ); - } - - /** - * @covers ::get_persistent_object_cache_availability() - */ - public function test_persistent_object_cache_with_suggestions() { - - $output = $this->instance->get_persistent_object_cache_availability(); - - $this->assertArrayHasKey( 'redis', $output ); - $this->assertIsBool( $output['redis']['available'] ); - $this->assertEquals( 'Redis', $output['redis']['name'] ); - - $this->assertArrayHasKey( 'memcached', $output ); - $this->assertIsBool( $output['memcached']['available'] ); - $this->assertEquals( 'Memcached', $output['memcached']['name'] ); - - $this->assertArrayHasKey( 'apcu', $output ); - $this->assertIsBool( $output['apcu']['available'] ); - $this->assertEquals( 'APCu', $output['apcu']['name'] ); - } - - /** - * Test slug_definition_timing. - * - * @covers ::slug_definition_timing() - */ - public function test_slug_definition_timing() { - $data = [ - 'test' => 'amp_slug_definition_timing', - ]; - - /** @var AmpSlugCustomizationWatcher $amp_slug_customization_watcher */ - $amp_slug_customization_watcher = $this->get_private_property( $this->instance, 'amp_slug_customization_watcher' ); - $this->set_private_property( $amp_slug_customization_watcher, 'is_customized_late', false ); - $this->assertFalse( $amp_slug_customization_watcher->did_customize_late() ); - - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'label' => 'The AMP slug (query var) was defined early', - 'status' => 'good', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'green', - ], - ] - ), - $this->instance->slug_definition_timing() - ); - - add_filter( 'amp_query_var', [ self::class, 'get_lite_query_var' ] ); - - /** @var AmpSlugCustomizationWatcher $amp_slug_customization_watcher */ - $amp_slug_customization_watcher = $this->get_private_property( $this->instance, 'amp_slug_customization_watcher' ); - $this->set_private_property( $amp_slug_customization_watcher, 'is_customized_late', true ); - $this->assertTrue( $amp_slug_customization_watcher->did_customize_late() ); - - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'label' => 'The AMP slug (query var) was defined late', - 'status' => 'recommended', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'orange', - ], - ] - ), - $this->instance->slug_definition_timing() - ); - } - - /** - * Test curl_multi_functions. - * - * @covers ::curl_multi_functions() - */ - public function test_curl_multi_functions() { - $this->assertAssocArraySubset( - [ - 'test' => 'amp_curl_multi_functions', - ], - $this->instance->curl_multi_functions() - ); - } - - /** - * Test icu_version. - * - * @covers ::icu_version() - */ - public function test_icu_version() { - $this->assertAssocArraySubset( - [ - 'test' => 'amp_icu_version', - ], - $this->instance->icu_version() - ); - } - - /** - * Test css_transient_caching. - * - * @covers ::css_transient_caching() - */ - public function test_css_transient_caching() { - wp_using_ext_object_cache( false ); - $data = [ - 'test' => 'amp_css_transient_caching', - ]; - - AMP_Options_Manager::update_option( Option::DISABLE_CSS_TRANSIENT_CACHING, false ); - - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'status' => 'good', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'green', - ], - ] - ), - $this->instance->css_transient_caching() - ); - - AMP_Options_Manager::update_option( Option::DISABLE_CSS_TRANSIENT_CACHING, true ); - - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'status' => 'recommended', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'orange', - ], - ] - ), - $this->instance->css_transient_caching() - ); - - wp_using_ext_object_cache( true ); - $this->assertAssocArraySubset( - array_merge( - $data, - [ - 'status' => 'good', - 'badge' => [ - 'label' => 'AMP', - 'color' => 'blue', - ], - ] - ), - $this->instance->css_transient_caching() - ); - } - - /** - * Test xdebug_extension. - * - * @covers ::xdebug_extension() - */ - public function test_xdebug_extension() { - $actual = $this->instance->xdebug_extension(); - $this->assertEquals( 'amp_xdebug_extension', $actual['test'] ); - - $this->assertStringContainsString( - esc_html( 'The Xdebug extension can cause some of the AMP plugin’s processes to time out depending on your system resources and configuration. It should not be enabled on a live site (production environment).' ), - $actual['description'] - ); - } - - /** - * Test add_debug_information. - * - * @covers ::add_debug_information() - */ - public function test_add_debug_information() { - $debug_info = $this->instance->add_debug_information( [] ); - $this->assertArrayHasKey( 'amp_wp', $debug_info ); - $this->assertArrayHasKey( 'fields', $debug_info['amp_wp'] ); - $keys = [ - 'amp_mode_enabled', - 'amp_templates_enabled', - 'amp_serve_all_templates', - 'amp_css_transient_caching_disabled', - 'amp_css_transient_caching_threshold', - 'amp_css_transient_caching_sampling_range', - 'amp_css_transient_caching_transient_count', - 'amp_slug_query_var', - 'amp_slug_defined_late', - ]; - foreach ( $keys as $key ) { - $this->assertArrayHasKey( $key, $debug_info['amp_wp']['fields'], "Expected key: $key" ); - $this->assertFalse( $debug_info['amp_wp']['fields'][ $key ]['private'], "Expected private for key: $key" ); - } - } - - /** - * Get test data for test_modify_test_result. - * - * @return array[] Test data. - */ - public function get_test_result() { - return [ - 'empty_result' => [ - [], - ], - 'good_https_status_result' => [ - [ - 'test' => 'https_status', - 'status' => 'good', - 'description' => '', - ], - ], - 'recommended_https_status_result' => [ - [ - 'test' => 'https_status', - 'status' => 'recommended', - 'description' => '', - ], - [ - 'test' => 'https_status', - 'status' => 'critical', - 'description' => '

Additionally, AMP requires HTTPS for most components to work properly, including iframes and videos.

', - ], - ], - ]; - } - - /** - * Test modify_test_result. - * - * @dataProvider get_test_result - * - * @covers ::modify_test_result() - * - * @param array $test_data Data from Site Health test. - * @param array $expected Expected modified test result. - */ - public function test_modify_test_result( $test_data, $expected = null ) { - $test_result = $this->instance->modify_test_result( $test_data ); - - if ( ! $expected ) { - $expected = $test_data; - } - - $this->assertEquals( $expected, $test_result ); - } - - /** - * Gets the test data for test_get_supported_templates(). - * - * @return array The test data. - */ - public function get_supported_templates_data() { - return [ - 'no_template_supported' => [ - [], - [], - 'standard', - 'No template supported', - ], - 'only_singular' => [ - [ 'post' ], - [ 'is_singular' ], - 'transitional', - 'post, is_singular', - ], - 'only_post' => [ - [ 'post' ], - [], - 'transitional', - 'post', - ], - 'only_post_and_author' => [ - [ 'post' ], - [ 'is_author' ], - 'transitional', - 'post, is_author', - ], - 'two_templates' => [ - [ 'post' ], - [ 'is_singular', 'is_author' ], - 'transitional', - 'post, is_singular, is_author', - ], - 'three_templates' => [ - [ 'post', 'page' ], - [ 'is_singular', 'is_author', 'is_tag' ], - 'transitional', - 'post, page, is_singular, is_author, is_tag', - ], - 'three_templates_reader_mode' => [ - [ 'post', 'page' ], - [ 'is_singular', 'is_author', 'is_tag' ], - 'reader', - 'post, page', - ], - ]; - } - - /** - * Test add_debug_information. - * - * @dataProvider get_supported_templates_data - * @covers ::get_supported_templates() - * - * @param array $supported_content_types The supported content types, like 'post'. - * @param array $supported_templates The supported templates, like 'is_author'. - * @param string $theme_support The theme support, like 'standard'. - * @param string $expected The expected string of supported templates. - */ - public function test_get_supported_templates( $supported_content_types, $supported_templates, $theme_support, $expected ) { - remove_theme_support( 'amp' ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, $supported_templates ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, $theme_support ); - AMP_Options_Manager::update_option( Option::SUPPORTED_POST_TYPES, $supported_content_types ); - - $this->assertEquals( $expected, $this->call_private_method( $this->instance, 'get_supported_templates' ) ); - } - - /** - * Gets the test data for test_get_serve_all_templates(). - * - * @return array The test data. - */ - public function get_serve_all_templates_data() { - return [ - 'reader_mode_and_option_true' => [ - 'reader', - true, - 'This option does not apply to Reader mode.', - ], - 'reader_mode_and_option_false' => [ - 'reader', - false, - 'This option does not apply to Reader mode.', - ], - 'standard_mode_and_option_true' => [ - 'standard', - true, - 'true', - ], - 'standard_mode_and_option_false' => [ - 'standard', - false, - 'false', - ], - 'transitional_mode_and_option_true' => [ - 'transitional', - false, - 'false', - ], - 'transitional_mode_and_option_false' => [ - 'transitional', - false, - 'false', - ], - ]; - } - - /** - * Test get_serve_all_templates. - * - * @dataProvider get_serve_all_templates_data - * @covers ::get_serve_all_templates() - * - * @param string $theme_support The template mode, like 'standard'. - * @param bool $do_serve_all_templates Whether the option to serve all templates is true. - * @param string $expected The expected return value. - */ - public function test_get_serve_all_templates( $theme_support, $do_serve_all_templates, $expected ) { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, $theme_support ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, $do_serve_all_templates ); - - $this->assertEquals( $expected, $this->call_private_method( $this->instance, 'get_serve_all_templates' ) ); - } - - /** - * Test add_extensions. - * - * @covers ::add_extensions() - */ - public function test_add_extensions() { - $this->assertEquals( - [ - 'json' => [ - 'extension' => 'json', - 'function' => 'json_encode', - 'required' => false, - ], - 'mbstring' => [ - 'extension' => 'mbstring', - 'required' => false, - ], - 'zip' => [ - 'extension' => 'zip', - 'required' => false, - ], - ], - $this->instance->add_extensions( [] ) - ); - - // Test that the `intl` extension is added only when site URL is an IDN. - add_filter( 'site_url', [ self::class, 'get_idn' ], 10, 4 ); - - $extensions = $this->instance->add_extensions( [] ); - $this->assertArrayHasKey( 'intl', $extensions ); - $this->assertEquals( - [ - 'extension' => 'intl', - 'function' => 'idn_to_utf8', - 'required' => false, - ], - $extensions['intl'] - ); - - remove_filter( 'site_url', [ self::class, 'get_idn' ] ); - } - - /** - * Test get_good_response_time_threshold. - * - * @covers ::get_good_response_time_threshold() - */ - public function test_get_good_response_time_threshold() { - $this->assertSame( 600, $this->instance->get_good_response_time_threshold() ); - - add_filter( - 'amp_page_cache_good_response_time_threshold', - static function () { - return 200; - } - ); - - $this->assertSame( 200, $this->instance->get_good_response_time_threshold() ); - - add_filter( - 'amp_page_cache_good_response_time_threshold', - static function () { - return '100'; - }, - 100 - ); - - $this->assertSame( 100, $this->instance->get_good_response_time_threshold() ); - } - - /** - * Data provider for $this->test_page_cache() - * - * @return array[] - */ - public function get_page_cache_data() { - $recommended_label = 'Page caching is not detected but the server response time is OK'; - $good_label = 'Page caching is detected and the server response time is good'; - $critical_label = 'Page caching is not detected and the server response time is slow'; - $error_label = 'Unable to detect the presence of page caching'; - - return [ - 'basic-auth-fail' => [ - 'responses' => [ - 'unauthorized', - ], - 'expected_status' => 'critical', - 'expected_label' => $error_label, - 'good_basic_auth' => false, - ], - 'no-cache-control' => [ - 'responses' => array_fill( 0, 3, [] ), - 'expected_status' => 'critical', - 'expected_label' => $critical_label, - 'good_basic_auth' => null, - 'delay_the_response' => true, - ], - 'no-cache' => [ - 'responses' => array_fill( 0, 3, [ 'cache-control' => 'no-cache' ] ), - 'expected_status' => 'recommended', - 'expected_label' => $recommended_label, - ], - 'no-cache-arrays' => [ - 'responses' => array_fill( 0, 3, [ 'cache-control' => [ 'no-cache', 'no-store' ] ] ), - 'expected_status' => 'recommended', - 'expected_label' => $recommended_label, - ], - 'no-cache-with-delayed-response' => [ - 'responses' => array_fill( 0, 3, [ 'cache-control' => 'no-cache' ] ), - 'expected_status' => 'critical', - 'expected_label' => $critical_label, - 'good_basic_auth' => null, - 'delay_the_response' => true, - ], - 'age' => [ - 'responses' => array_fill( - 0, - 3, - [ 'age' => '1345' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cache-control-max-age' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cache-control' => 'public; max-age=600' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'etag' => [ - 'responses' => array_fill( - 0, - 3, - [ 'etag' => '"1234567890"' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cache-control-max-age-after-2-requests' => [ - 'responses' => [ - [], - [], - [ 'cache-control' => 'public; max-age=600' ], - ], - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cache-control-with-future-expires' => [ - 'responses' => array_fill( - 0, - 3, - [ 'expires' => gmdate( 'r', time() + MINUTE_IN_SECONDS * 10 ) ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cache-control-with-past-expires' => [ - 'responses' => array_fill( - 0, - 3, - [ 'expires' => gmdate( 'r', time() - MINUTE_IN_SECONDS * 10 ) ] - ), - 'expected_status' => 'critical', - 'expected_label' => $critical_label, - 'good_basic_auth' => null, - 'delay_the_response' => true, - ], - 'cache-control-with-basic-auth' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cache-control' => 'public; max-age=600' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - 'good_basic_auth' => true, - ], - 'cf-cache-status' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cf-cache-status' => 'HIT: 1' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cf-cache-status-without-header-and-delay' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cf-cache-status' => 'MISS' ] - ), - 'expected_status' => 'recommended', - 'expected_label' => $recommended_label, - 'good_basic_auth' => null, - 'delay_the_response' => false, - ], - 'cf-cache-status-with-delay' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cf-cache-status' => 'MISS' ] - ), - 'expected_status' => 'critical', - 'expected_label' => $critical_label, - 'good_basic_auth' => null, - 'delay_the_response' => true, - ], - 'x-cache-enabled' => [ - 'responses' => array_fill( - 0, - 3, - [ 'x-cache-enabled' => 'true' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'x-cache-enabled-with-delay' => [ - 'responses' => array_fill( - 0, - 3, - [ 'x-cache-enabled' => 'false' ] - ), - 'expected_status' => 'critical', - 'expected_label' => $critical_label, - 'good_basic_auth' => null, - 'delay_the_response' => true, - ], - 'x-cache-disabled' => [ - 'responses' => array_fill( - 0, - 3, - [ 'x-cache-disabled' => 'off' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cf-apo-via' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cf-apo-via' => 'tcache' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - 'cf-edge-cache' => [ - 'responses' => array_fill( - 0, - 3, - [ 'cf-edge-cache' => 'cache' ] - ), - 'expected_status' => 'good', - 'expected_label' => $good_label, - ], - ]; - } - - /** - * @dataProvider get_page_cache_data - * @covers ::page_cache() - * @covers ::get_page_cache_headers() - * @covers ::check_for_page_caching() - */ - public function test_page_cache( $responses, $expected_status, $expected_label, $good_basic_auth = null, $delay_the_response = false ) { - - $badge_color = [ - 'critical' => 'red', - 'recommended' => 'orange', - 'good' => 'green', - ]; - - $expected_props = [ - 'badge' => [ - 'label' => 'AMP', - 'color' => $badge_color[ $expected_status ], - ], - 'test' => 'amp_page_cache', - 'status' => $expected_status, - 'label' => $expected_label, - ]; - - if ( null !== $good_basic_auth ) { - $_SERVER['PHP_AUTH_USER'] = 'admin'; - $_SERVER['PHP_AUTH_PW'] = 'password'; - } - - $is_unauthorized = false; - - $threshold = 10; - if ( $delay_the_response ) { - add_filter( - 'amp_page_cache_good_response_time_threshold', - static function () use ( $threshold ) { - return $threshold; - } - ); - } - - add_filter( - 'pre_http_request', - function ( $r, $parsed_args ) use ( &$responses, &$is_unauthorized, $good_basic_auth, $delay_the_response, $threshold ) { - - $expected_response = array_shift( $responses ); - - if ( $delay_the_response ) { - usleep( $threshold * 1000 + 1 ); - } - - if ( 'unauthorized' === $expected_response ) { - $is_unauthorized = true; - - return [ - 'response' => [ - 'code' => 401, - 'message' => 'Unauthorized', - ], - ]; - } - - if ( null !== $good_basic_auth ) { - $this->assertArrayHasKey( - 'Authorization', - $parsed_args['headers'] - ); - } - - $this->assertIsArray( $expected_response ); - - return [ - 'headers' => $expected_response, - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - }, - 20, - 2 - ); - - $actual = $this->instance->page_cache(); - $this->assertArrayHasKey( 'description', $actual ); - $this->assertArrayHasKey( 'actions', $actual ); - if ( $is_unauthorized ) { - $this->assertStringContainsString( 'Unauthorized', $actual['description'] ); - } else { - $this->assertStringNotContainsString( 'Unauthorized', $actual['description'] ); - } - - $this->assertEquals( - $expected_props, - wp_array_slice_assoc( $actual, array_keys( $expected_props ) ) - ); - } - - /** - * @covers ::get_page_cache_detail() - * @covers ::check_for_page_caching() - */ - public function test_get_page_cache_detail_with_legacy_cache_result() { - - add_filter( - 'pre_http_request', - function () { - return [ - 'headers' => [ - 'etag' => '"cool"', - ], - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - }, - 20, - 2 - ); - - set_transient( SiteHealth::HAS_PAGE_CACHING_TRANSIENT_KEY, 'no', DAY_IN_SECONDS ); - - $this->assertAssocArrayContains( - [ - 'status' => 'good', - 'advanced_cache_present' => false, - 'headers' => [ - 'etag', - ], - ], - $this->instance->get_page_cache_detail( true ) - ); - } - - /** - * @covers ::get_page_cache_detail() - * @covers ::check_for_page_caching() - */ - public function test_get_page_cache_detail() { - $callback = static function () { - return [ - 'headers' => [ - 'age' => '1234', - ], - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - }; - - add_filter( 'pre_http_request', $callback, 20 ); - - // Test 1: Assert for fresh result. (Even cached result is exist.) - $page_cache_status = [ - 'advanced_cache_present' => false, - 'page_caching_response_headers' => [ [], [], [] ], - 'response_timing' => [ 200, 300, 400 ], - ]; - set_transient( SiteHealth::HAS_PAGE_CACHING_TRANSIENT_KEY, $page_cache_status, DAY_IN_SECONDS ); - - $output = $this->instance->get_page_cache_detail( true ); - $this->assertEquals( 'recommended', $output['status'] ); - - $output = $this->instance->get_page_cache_detail(); - $this->assertEquals( 'good', $output['status'] ); - - remove_filter( 'pre_http_request', $callback, 20 ); - - // Test 2: Test for cached result. - $page_cache_status = [ - 'advanced_cache_present' => true, - 'page_caching_response_headers' => [ [ 'x-cache' ], [ 'x-cache' ], [ 'x-cache' ] ], - 'response_timing' => [ 200, 300, 400 ], - ]; - set_transient( SiteHealth::HAS_PAGE_CACHING_TRANSIENT_KEY, $page_cache_status, DAY_IN_SECONDS ); - - $output = $this->instance->get_page_cache_detail( true ); - $this->assertEquals( 'good', $output['status'] ); - - delete_transient( SiteHealth::HAS_PAGE_CACHING_TRANSIENT_KEY ); - } - - /** - * @covers ::get_page_cache_detail() - * @covers ::check_for_page_caching() - */ - public function test_get_page_cache_detail_with_error() { - $error_object = new WP_Error( 'error_code', 'Error message.' ); - - $return_error = static function () use ( $error_object ) { - return $error_object; - }; - - $return_cached_response = static function () { - return [ - 'headers' => [ - 'cache-control' => 'public; max-age=600', - ], - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - }; - - add_filter( 'pre_http_request', $return_error, 20 ); - - // Test 1: Assert for fresh result (which is then cached). - $this->assertEquals( - $error_object, - $this->instance->get_page_cache_detail() - ); - - remove_filter( 'pre_http_request', $return_error, 20 ); - add_filter( 'pre_http_request', $return_cached_response, 20 ); - - // Test 2: Test for cached result. - $this->assertEquals( - $error_object, - $this->instance->get_page_cache_detail( true ) - ); - - // Test 3: Test for non-cached result again now that no error is returned. - $output = $this->instance->get_page_cache_detail( false ); - $this->assertEquals( 'good', $output['status'] ); - $this->assertContains( 'cache-control', $output['headers'] ); - - remove_filter( 'pre_http_request', $return_cached_response, 20 ); - add_filter( 'pre_http_request', $return_error, 20 ); - - // Test 4: Test for cached result again now that no error is returned. - $output = $this->instance->get_page_cache_detail( true ); - $this->assertEquals( 'good', $output['status'] ); - $this->assertContains( 'cache-control', $output['headers'] ); - } - - /** - * Get an IDN for testing purposes. - * - * @return string - */ - public static function get_idn() { - return 'https://foo.xn--57h.bar.com'; - } - - /** - * Get an AMP query var for testing purposes. - * - * @return string - */ - public static function get_lite_query_var() { - return 'lite'; - } - - /** - * Assert that the expected is a subset of the actual superset. - * - * @param array $expected Subset. - * @param array $actual Superset. - */ - public function assertAssocArraySubset( $expected, $actual ) { - $this->assertEquals( - $expected, - wp_array_slice_assoc( $actual, array_keys( $expected ) ) - ); - } -} diff --git a/tests/php/src/Admin/SupportLinkTest.php b/tests/php/src/Admin/SupportLinkTest.php deleted file mode 100644 index 624a8de3c87..00000000000 --- a/tests/php/src/Admin/SupportLinkTest.php +++ /dev/null @@ -1,220 +0,0 @@ -markTestSkipped( 'Test requires Site Health.' ); - } - - $this->instance = new SupportLink(); - } - - /** - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - $this->assertEquals( - 'wp_loaded', - SupportLink::get_registration_action() - ); - } - - /** - * @covers ::is_needed() - */ - public function test_is_needed() { - - // Test 1: Test for users that don't have permission. - $this->assertFalse( SupportLink::is_needed() ); - - // Test 2: Test with admin user. - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - $this->assertTrue( SupportLink::is_needed() ); - } - - /** - * @covers ::register() - */ - public function test_register() { - - set_current_screen( 'index.php' ); - - $this->instance->register(); - - $this->assertEquals( 105, has_action( 'admin_bar_menu', [ $this->instance, 'admin_bar_menu' ] ) ); - - $this->assertEquals( - 10, - has_filter( - 'amp_validated_url_status_actions', - [ - $this->instance, - 'amp_validated_url_status_actions', - ] - ) - ); - - $this->assertEquals( - PHP_INT_MAX, - has_filter( - 'post_row_actions', - [ - $this->instance, - 'post_row_actions', - ] - ) - ); - - $this->assertEquals( 10, has_filter( 'plugin_row_meta', [ $this->instance, 'plugin_row_meta' ] ) ); - - set_current_screen( 'front' ); - } - - /** - * @covers ::admin_bar_menu() - */ - public function test_admin_bar_menu() { - - // Mock Admin user. - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - // Set AMP mode. - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - - require_once ABSPATH . WPINC . '/class-wp-admin-bar.php'; - $admin_bar = new \WP_Admin_Bar(); - - $this->go_to( home_url( '/' ) ); - - // AMP-first mode. - AMP_Validation_Manager::add_admin_bar_menu_items( $admin_bar ); - $this->instance->admin_bar_menu( $admin_bar ); - - $node = $admin_bar->get_node( 'amp-support' ); - - $this->assertInstanceOf( 'stdClass', $node ); - $this->assertStringContainsString( 'page=amp-support', $node->href ); - } - - /** - * @covers ::amp_validated_url_status_actions() - */ - public function test_amp_validated_url_status_actions() { - - $post = $this->factory()->post->create_and_get( - [ - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - ] - ); - - $actions = $this->instance->amp_validated_url_status_actions( [], $post ); - - $this->assertStringContainsString( - 'page=amp-support', - $actions['amp-support'] - ); - - $this->assertStringContainsString( - sprintf( 'url=%s', rawurlencode( $post->post_title ) ), - $actions['amp-support'] - ); - } - - /** - * Test post_row_actions method. - * - * @covers ::post_row_actions() - */ - public function test_post_row_actions() { - - // Test 1: With different post type. - $post = $this->factory()->post->create_and_get(); - - $actions = $this->instance->post_row_actions( [], $post ); - $this->assertEmpty( $actions ); - - // Test 2: With "amp_validated_url" post type. - $post = $this->factory()->post->create_and_get( - [ - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - ] - ); - - $actions = $this->instance->post_row_actions( [], $post ); - - $this->assertStringContainsString( - 'page=amp-support', - $actions['amp-support'] - ); - - $this->assertStringContainsString( - sprintf( 'url=%s', rawurlencode( $post->post_title ) ), - $actions['amp-support'] - ); - } - - /** - * @covers ::plugin_row_meta() - */ - public function test_plugin_row_meta() { - - // Test 1: For other than AMP plugin - $output = $this->instance->plugin_row_meta( [], 'hello-dolly.php' ); - $this->assertEmpty( $output ); - - // Test 2: For AMP plugin - $output = $this->instance->plugin_row_meta( [], 'amp/amp.php' ); - - $should_have = sprintf( - '%s', - esc_url( - add_query_arg( - [ 'page' => 'amp-support' ], - admin_url( 'admin.php' ) - ) - ), - esc_html__( 'Get support', 'amp' ) - ); - - $this->assertContains( $should_have, $output ); - - } -} diff --git a/tests/php/src/Admin/SupportScreenTest.php b/tests/php/src/Admin/SupportScreenTest.php deleted file mode 100644 index c3f76fe86cb..00000000000 --- a/tests/php/src/Admin/SupportScreenTest.php +++ /dev/null @@ -1,281 +0,0 @@ -markTestSkipped( 'Test requires Site Health.' ); - } - - global $wp_version; - $this->original_wp_version = $wp_version; - - $this->instance = $this->injector->make( SupportScreen::class ); - - $this->add_home_url_loopback_request_mocking(); - } - - /** - * Tear down. - * - * @inheritDoc - */ - public function tear_down() { - parent::tear_down(); - - global $wp_version; - $wp_version = $this->original_wp_version; - } - - /** @covers ::__construct() */ - public function test__construct() { - - $this->assertInstanceOf( Conditional::class, $this->instance ); - $this->assertInstanceOf( Delayed::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( SupportScreen::class, $this->instance ); - } - - /** - * @covers ::get_registration_action - */ - public function test_get_registration_action() { - $this->assertEquals( 'init', SupportScreen::get_registration_action() ); - } - - /** - * @covers ::check_core_version() - */ - public function test_check_core_version() { - global $wp_version; - - // This will always be true by default because set_up calls markTestSkipped if WP_Site_Health doesn't exist. - $this->assertTrue( SupportScreen::check_core_version() ); - - $wp_version = '4.9'; - $this->assertFalse( SupportScreen::check_core_version() ); - - $wp_version = '5.0'; - $this->assertFalse( SupportScreen::check_core_version() ); - - $wp_version = '5.1'; - $this->assertFalse( SupportScreen::check_core_version() ); - - $wp_version = '5.2'; - $this->assertTrue( SupportScreen::check_core_version() ); - } - - /** - * @covers ::is_needed() - * @covers ::has_cap() - */ - public function test_is_needed() { - - // Without mocking. - $this->assertFalse( SupportScreen::is_needed() ); - $this->assertFalse( SupportScreen::has_cap() ); - - // Mock the is_admin() with required user caps. - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->assertFalse( SupportScreen::is_needed() ); - $this->assertTrue( SupportScreen::has_cap() ); - - set_current_screen( $this->instance->screen_handle() ); - $this->assertTrue( SupportScreen::is_needed() ); - $this->assertTrue( SupportScreen::has_cap() ); - - // Access denied when user cannot validate. - add_filter( - 'map_meta_cap', - function ( $caps, $cap ) { - if ( AMP_Validation_Manager::VALIDATE_CAPABILITY === $cap ) { - $caps[] = 'do_not_allow'; - } - return $caps; - }, - 10, - 3 - ); - $this->assertFalse( SupportScreen::is_needed() ); - $this->assertFalse( SupportScreen::has_cap() ); - - // Reset data. - unset( $GLOBALS['current_screen'] ); - } - - /** - * @covers ::register - */ - public function test_register() { - - $this->instance->register(); - - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_assets' ] ) ); - $this->assertEquals( 9, has_action( 'admin_menu', [ $this->instance, 'add_menu_items' ] ) ); - - } - - /** - * @covers ::get_menu_slug - */ - public function test_get_menu_slug() { - - $this->assertEquals( 'amp-support', $this->instance->get_menu_slug() ); - } - - /** - * @covers ::screen_handle - */ - public function test_screen_handle() { - - $this->assertEquals( - sprintf( 'amp_page_%s', $this->instance->get_menu_slug() ), - $this->instance->screen_handle() - ); - } - - /** - * @covers ::add_menu_items - */ - public function test_add_menu_items() { - - global $submenu; - - wp_set_current_user( - self::factory()->user->create( - [ - 'role' => 'administrator', - ] - ) - ); - - $this->instance->add_menu_items(); - - $this->assertArrayHasKey( 'amp-options', $submenu ); - $this->assertContains( - [ - 'Support', - 'manage_options', - 'amp-support', - 'Support', - ], - $submenu['amp-options'] - ); - - } - - /** - * @covers ::enqueue_assets - */ - public function test_enqueue_assets() { - - $wp_scripts = wp_scripts(); - $wp_styles = wp_styles(); - - $this->instance->enqueue_assets( '' ); - - $this->assertArrayNotHasKey( SupportScreen::ASSET_HANDLE, $wp_scripts->registered ); - $this->assertArrayNotHasKey( SupportScreen::ASSET_HANDLE, $wp_styles->registered ); - - $this->instance->enqueue_assets( $this->instance->screen_handle() ); - - $this->assertArrayHasKey( SupportScreen::ASSET_HANDLE, $wp_scripts->registered ); - $this->assertArrayHasKey( SupportScreen::ASSET_HANDLE, $wp_styles->registered ); - - } - - /** - * @covers ::render_screen - */ - public function test_render_screen() { - - ob_start(); - $this->instance->render_screen(); - $content = ob_get_clean(); - - $this->assertStringContainsString( '
', $content ); - } - - /** - * @covers ::get_amp_validated_post_counts() - */ - public function test_get_amp_validated_post_counts() { - - $validated_environment = AMP_Validated_URL_Post_Type::get_validated_environment(); - - $this->factory()->post->create_and_get( - [ - 'post_title' => home_url( 'sample-page-for-amp-validation' ), - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'meta_input' => [ - AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY => $validated_environment, - ], - ] - ); - - $stale_validated_environment = $validated_environment; - $stale_validated_environment['options']['theme_support'] = 'standard'; - - $this->factory()->post->create_and_get( - [ - 'post_title' => home_url( 'sample-page-for-amp-validation-stale' ), - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'meta_input' => [ - AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY => $stale_validated_environment, - ], - ] - ); - - $this->assertEquals( - [ - 'all' => 2, - 'fresh' => 1, - 'stale' => 1, - ], - $this->instance->get_amp_validated_post_counts() - ); - } -} diff --git a/tests/php/src/Admin/UserRESTEndpointExtensionTest.php b/tests/php/src/Admin/UserRESTEndpointExtensionTest.php deleted file mode 100644 index fd02e2933c0..00000000000 --- a/tests/php/src/Admin/UserRESTEndpointExtensionTest.php +++ /dev/null @@ -1,154 +0,0 @@ -user_rest_endpoint_extension = new UserRESTEndpointExtension(); - } - - /** - * Tests UserRESTEndpointExtension::register - * - * @covers ::get_registration_action - */ - public function test_get_registration_action() { - $this->assertEquals( 'rest_api_init', UserRESTEndpointExtension::get_registration_action() ); - } - - /** - * Tests UserRESTEndpointExtension::register_rest_field - * - * @covers ::register - * @covers ::register_rest_field - */ - public function test_register_rest_field() { - global $wp_rest_additional_fields; - - $this->user_rest_endpoint_extension->register(); - - $this->assertArrayHasKey( 'amp_review_panel_dismissed_for_template_mode', $wp_rest_additional_fields['user'] ); - } - - /** - * Tests UserRESTEndpointExtension::update_review_panel_dismissed_for_template_mode - * - * @covers ::update_review_panel_dismissed_for_template_mode - */ - public function test_update_review_panel_dismissed_for_template_mode() { - $server = rest_get_server(); - $this->user_rest_endpoint_extension->register_rest_field(); - - $admin_user = self::factory()->user->create_and_get( [ 'role' => 'administrator' ] ); - $editor_user = self::factory()->user->create_and_get( [ 'role' => 'editor' ] ); - - $this->assertSame( '', $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $admin_user->ID ] ) ); - $this->assertSame( '', $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $editor_user->ID ] ) ); - - // Test that an editor can edit their own field. - wp_set_current_user( $editor_user->ID ); - $request = new WP_REST_Request( 'PUT', "/wp/v2/users/{$editor_user->ID}" ); - $request->set_body_params( [ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE => AMP_Theme_Support::STANDARD_MODE_SLUG ] ); - $response = $server->dispatch( $request ); - $this->assertEquals( 200, $response->get_status() ); - $this->assertSame( AMP_Theme_Support::STANDARD_MODE_SLUG, $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $editor_user->ID ] ) ); - - // Test that an editor cannot edit another user's field. - wp_set_current_user( $editor_user->ID ); - $request = new WP_REST_Request( 'PUT', "/wp/v2/users/{$admin_user->ID}" ); - $request->set_body_params( [ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE => AMP_Theme_Support::STANDARD_MODE_SLUG ] ); - $response = $server->dispatch( $request ); - $this->assertEquals( 403, $response->get_status() ); - $this->assertSame( '', $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $admin_user->ID ] ) ); - - // Test that admin user can edit another user's field. - wp_set_current_user( $admin_user->ID ); - $request = new WP_REST_Request( 'PUT', "/wp/v2/users/{$editor_user->ID}" ); - $request->set_body_params( [ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ] ); - $response = $server->dispatch( $request ); - $this->assertEquals( 200, $response->get_status() ); - $this->assertSame( AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $editor_user->ID ] ) ); - - // Test that admin user can edit their own field (to clear it out). - wp_set_current_user( $admin_user->ID ); - $request = new WP_REST_Request( 'PUT', "/wp/v2/users/{$admin_user->ID}" ); - $request->set_body_params( [ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE => '' ] ); - $response = $server->dispatch( $request ); - $this->assertEquals( 200, $response->get_status() ); - $this->assertSame( '', $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $admin_user->ID ] ) ); - - // Test that a user user cannot update the value to be bogus. - wp_set_current_user( $admin_user->ID ); - $request = new WP_REST_Request( 'PUT', "/wp/v2/users/{$admin_user->ID}" ); - $request->set_body_params( [ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE => 'BOGUS' ] ); - $response = $server->dispatch( $request ); - $this->assertEquals( 400, $response->get_status() ); - $this->assertSame( '', $this->user_rest_endpoint_extension->get_review_panel_dismissed_for_template_mode( [ 'id' => $admin_user->ID ] ) ); - } - - /** - * Tests UserRESTEndpointExtension::get_review_panel_dismissed_for_template_mode - * - * @covers ::get_review_panel_dismissed_for_template_mode - */ - public function test_get_review_panel_dismissed_for_template_mode() { - $server = rest_get_server(); - $this->user_rest_endpoint_extension->register_rest_field(); - - $admin_user = self::factory()->user->create_and_get( [ 'role' => 'administrator' ] ); - wp_set_current_user( $admin_user->ID ); - - // Check initial value. - $request = new WP_REST_Request( 'GET', "/wp/v2/users/{$admin_user->ID}" ); - $response = $server->dispatch( $request ); - $this->assertEquals( 200, $response->get_status() ); - $data = $response->get_data(); - $this->assertArrayHasKey( UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE, $data ); - $this->assertSame( '', $data[ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE ] ); - - // Check updated value. - $this->user_rest_endpoint_extension->update_review_panel_dismissed_for_template_mode( AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, $admin_user ); - $request = new WP_REST_Request( 'GET', "/wp/v2/users/{$admin_user->ID}" ); - $response = $server->dispatch( $request ); - $this->assertEquals( 200, $response->get_status() ); - $data = $response->get_data(); - $this->assertArrayHasKey( UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE, $data ); - $this->assertSame( AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, $data[ UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE ] ); - - // Verify the editor user cannot access another user. - $editor_user = self::factory()->user->create_and_get( [ 'role' => 'editor' ] ); - wp_set_current_user( $editor_user->ID ); - $request = new WP_REST_Request( 'GET', "/wp/v2/users/{$admin_user->ID}" ); - $response = $server->dispatch( $request ); - $this->assertEquals( 403, $response->get_status() ); - } -} diff --git a/tests/php/src/Admin/ValidationCountsTest.php b/tests/php/src/Admin/ValidationCountsTest.php deleted file mode 100644 index 21f125015af..00000000000 --- a/tests/php/src/Admin/ValidationCountsTest.php +++ /dev/null @@ -1,213 +0,0 @@ -post_type = 'post'; - - $this->instance = new ValidationCounts( new RESTPreloader() ); - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( ValidationCounts::class, $this->instance ); - $this->assertInstanceOf( Delayed::class, $this->instance ); - $this->assertInstanceOf( Conditional::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - $this->assertInstanceOf( HasRequirements::class, $this->instance ); - } - - /** - * Test ::get_registration_action(). - * - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - self::assertEquals( 'admin_enqueue_scripts', ValidationCounts::get_registration_action() ); - } - - /** @covers ::get_requirements() */ - public function test_get_requirements() { - $this->assertSame( - [ 'dependency_support', 'dev_tools.user_access' ], - ValidationCounts::get_requirements() - ); - } - - /** - * Test ::register(). - * - * @covers ::register() - */ - public function test_register() { - $this->instance->register(); - - $this->assertTrue( wp_script_is( ValidationCounts::ASSETS_HANDLE ) ); - $this->assertTrue( wp_style_is( ValidationCounts::ASSETS_HANDLE ) ); - } - - /** - * Test ::is_needed(). - * - * @covers ::is_needed() - */ - public function test_is_needed() { - $this->assertFalse( ValidationCounts::is_needed() ); - - // If dependency support is absent, then abort because is_needed will never be true. - if ( ! Services::get( 'dependency_support' )->has_support() ) { - return; - } - - $admin_user = self::factory()->user->create_and_get( [ 'role' => 'administrator' ] ); - wp_set_current_user( $admin_user->ID ); - - // Should be needed when in Transitional mode and not on a devtools screen. - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->assertTrue( ValidationCounts::is_needed() ); - - // Should not be needed when in Reader mode and not on a devtools screen. - unset( $_GET['post'], $_GET['post_type'], $_GET['taxonomy'], $_GET['action'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - $this->assertFalse( ValidationCounts::is_needed() ); - - // Should not be needed when in Reader mode, user access has not been configured and on a devtools screen. - $_GET['post_type'] = AMP_Validated_URL_Post_Type::POST_TYPE_SLUG; - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - $this->assertFalse( ValidationCounts::is_needed() ); - - // Should not be needed when in Reader mode, on a devtools screen, and dev tools is disabled for the user. - $_GET['post_type'] = AMP_Validated_URL_Post_Type::POST_TYPE_SLUG; - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - update_user_meta( $admin_user->ID, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, wp_json_encode( false ) ); - $this->assertFalse( ValidationCounts::is_needed() ); - - // Should be needed when in Reader mode, on a devtools screen, and dev tools is enabled for the user. - $_GET['post_type'] = AMP_Validated_URL_Post_Type::POST_TYPE_SLUG; - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - update_user_meta( $admin_user->ID, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, wp_json_encode( true ) ); - $this->assertTrue( ValidationCounts::is_needed() ); - - // Should be needed when not on a dev tools screen, dev tools has never been configured for the user, but is enabled through a filter. - add_filter( 'amp_dev_tools_user_default_enabled', '__return_true' ); - unset( $_GET['post'], $_GET['post_type'], $_GET['taxonomy'], $_GET['action'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - delete_user_meta( $admin_user->ID, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED ); - $this->assertTrue( ValidationCounts::is_needed() ); - } - - /** @return array */ - public function maybe_add_preload_rest_paths_data() { - return [ - 'no_type_post' => [ - 'set_up' => static function () { - set_current_screen( 'user' ); - }, - 'should_preload_path' => false, - ], - 'post_type_post' => [ - 'set_up' => static function () { - set_current_screen( 'edit' ); - get_current_screen()->post_type = 'post'; - }, - 'should_preload_path' => false, - ], - 'post_type_page' => [ - 'set_up' => static function () { - set_current_screen( 'edit' ); - get_current_screen()->post_type = 'page'; - }, - 'should_preload_path' => false, - ], - 'post_type_amp_validated_url' => [ - 'set_up' => static function () { - set_current_screen( 'edit' ); - get_current_screen()->post_type = AMP_Validated_URL_Post_Type::POST_TYPE_SLUG; - }, - 'should_preload_path' => true, - ], - 'settings_screen' => [ - 'set_up' => function () { - global $pagenow, $plugin_page, $menu; - $pagenow = 'admin.php'; - $plugin_page = 'amp-options'; - $menu = [ - [ - 2 => $plugin_page, - ], - ]; - $this->assertEquals( AMP_Options_Manager::OPTION_NAME, get_admin_page_parent() ); - }, - 'should_preload_path' => true, - ], - ]; - } - - /** - * @dataProvider maybe_add_preload_rest_paths_data - * @covers ::maybe_add_preload_rest_paths() - */ - public function test_maybe_add_preload_rest_paths( callable $set_up, $should_preload_path ) { - if ( ! function_exists( 'rest_preload_api_request' ) ) { - $this->markTestIncomplete( 'REST preload is not available so skipping.' ); - } - - $set_up(); - - $this->call_private_method( $this->instance, 'maybe_add_preload_rest_paths' ); - - $rest_preloader = $this->get_private_property( $this->instance, 'rest_preloader' ); - $paths = $this->get_private_property( $rest_preloader, 'paths' ); - - if ( $should_preload_path ) { - $this->assertContains( '/amp/v1/unreviewed-validation-counts', $paths ); - } else { - $this->assertNotContains( '/amp/v1/unreviewed-validation-counts', $paths ); - } - } -} diff --git a/tests/php/src/AmpSlugCustomizationWatcherTest.php b/tests/php/src/AmpSlugCustomizationWatcherTest.php deleted file mode 100644 index 62d39cb03d6..00000000000 --- a/tests/php/src/AmpSlugCustomizationWatcherTest.php +++ /dev/null @@ -1,82 +0,0 @@ -instance = new AmpSlugCustomizationWatcher(); - } - - public function test__construct() { - $this->assertInstanceOf( AmpSlugCustomizationWatcher::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - } - - /** @covers ::register() */ - public function test_register() { - $this->instance->register(); - $this->assertEquals( 8, has_action( 'plugins_loaded', [ $this->instance, 'determine_early_customization' ] ) ); - } - - /** @covers ::determine_early_customization() */ - public function test_determine_early_customization() { - $this->assertFalse( $this->instance->did_customize_early() ); - $this->assertFalse( $this->instance->did_customize_late() ); - - $early_slug = 'early'; - $this->add_query_var_filter( $early_slug ); - $this->assertEquals( $early_slug, amp_get_slug() ); - $this->instance->determine_early_customization(); - $this->assertFalse( has_action( 'after_setup_theme', [ $this->instance, 'determine_late_customization' ] ) ); - - $this->assertTrue( $this->instance->did_customize_early() ); - $this->assertFalse( $this->instance->did_customize_late() ); - } - - /** - * @covers ::determine_early_customization() - * @covers ::determine_late_customization() - */ - public function test_determine_late_customization() { - $this->assertFalse( $this->instance->did_customize_early() ); - $this->assertFalse( $this->instance->did_customize_late() ); - - $this->instance->determine_early_customization(); - $this->assertEquals( 4, has_action( 'after_setup_theme', [ $this->instance, 'determine_late_customization' ] ) ); - - $late_slug = 'late'; - $this->add_query_var_filter( $late_slug ); - $this->assertEquals( $late_slug, amp_get_slug() ); - - $this->instance->determine_late_customization(); - - $this->assertFalse( $this->instance->did_customize_early() ); - $this->assertTrue( $this->instance->did_customize_late() ); - } - - /** - * Add query var filter. - * - * @param string $value Query var. - */ - private function add_query_var_filter( $value ) { - remove_all_filters( 'amp_query_var' ); - add_filter( - 'amp_query_var', - static function () use ( $value ) { - return $value; - } - ); - } -} diff --git a/tests/php/src/AmpWpPluginTest.php b/tests/php/src/AmpWpPluginTest.php deleted file mode 100644 index d7c885125ff..00000000000 --- a/tests/php/src/AmpWpPluginTest.php +++ /dev/null @@ -1,33 +0,0 @@ - DummyService::class ]; - } - ); - - $plugin->register(); - - $container = $plugin->get_container(); - - $this->assertGreaterThan( 2, count( $container ) ); - $this->assertTrue( $container->has( 'injector' ) ); - $this->assertInstanceof( Injector::class, $container->get( 'injector' ) ); - $this->assertTrue( $container->has( 'plugin_registry' ) ); - $this->assertInstanceof( PluginRegistry::class, $container->get( 'plugin_registry' ) ); - $this->assertFalse( $container->has( 'filtered_service' ) ); - } -} diff --git a/tests/php/src/BackgroundTask/BackgroundTaskDeactivatorTest.php b/tests/php/src/BackgroundTask/BackgroundTaskDeactivatorTest.php deleted file mode 100644 index e7ef266e8c4..00000000000 --- a/tests/php/src/BackgroundTask/BackgroundTaskDeactivatorTest.php +++ /dev/null @@ -1,134 +0,0 @@ -test_instance = new BackgroundTaskDeactivator(); - } - - /** - * @covers ::register() - */ - public function test_register() { - $this->assertInstanceof( BackgroundTaskDeactivator::class, $this->test_instance ); - $this->assertInstanceof( Service::class, $this->test_instance ); - $this->assertInstanceof( Registerable::class, $this->test_instance ); - $this->assertInstanceof( Deactivateable::class, $this->test_instance ); - - $this->test_instance->register(); - - $plugin_file = $this->get_private_property( $this->test_instance, 'plugin_file' ); - $this->assertEquals( 'amp/amp.php', $plugin_file ); - - $this->assertEquals( 10, has_action( "network_admin_plugin_action_links_{$plugin_file}", [ $this->test_instance, 'add_warning_sign_to_network_deactivate_action' ] ) ); - $this->assertEquals( 10, has_action( 'plugin_row_meta', [ $this->test_instance, 'add_warning_to_plugin_meta' ] ) ); - } - - /** - * @covers ::add_event() - * @covers ::deactivate() - */ - public function test_deactivating_two_events() { - $original_cron = get_option( 'cron' ); - - update_option( - 'cron', - [ - time() => [ - 'event_one' => [ 'args' => [] ], - ], - time() + HOUR_IN_SECONDS => [ - 'event_two' => [ 'args' => [] ], - ], - ] - ); - - $this->assertCount( 2, _get_cron_array() ); - - $this->test_instance->add_event( 'event_one' ); - $this->test_instance->add_event( 'event_two' ); - - $this->test_instance->deactivate( false ); - $this->assertCount( 0, _get_cron_array() ); - - update_option( 'cron', $original_cron ); - } - - /** - * @covers ::add_event() - * @covers ::deactivate() - */ - public function test_deactivating_one_of_two_events() { - $original_cron = get_option( 'cron' ); - - update_option( - 'cron', - [ - time() => [ - 'event_one' => [ 'args' => [] ], - ], - time() + HOUR_IN_SECONDS => [ - 'event_two' => [ 'args' => [] ], - ], - ] - ); - - $this->assertCount( 2, _get_cron_array() ); - - $this->test_instance->add_event( 'event_one' ); - - $this->test_instance->deactivate( false ); - $this->assertCount( 1, _get_cron_array() ); - - update_option( 'cron', $original_cron ); - } - - /** - * @covers ::get_warning_icon() - * @covers ::add_warning_sign_to_network_deactivate_action() - */ - public function test_network_deactivate_warning() { - // Tested method uses multisite functions. - if ( ! function_exists( 'wp_is_large_network' ) ) { - require_once ABSPATH . WPINC . '/ms-functions.php'; - } - - add_filter( 'wp_is_large_network', '__return_true' ); - wp_register_style( 'amp-icons', 'http://site.com/file.css', [], '1' ); - - $actions = [ - 'deactivate' => '', - ]; - - $new_actions = $this->test_instance->add_warning_sign_to_network_deactivate_action( $actions ); - - $this->assertTrue( wp_style_is( 'amp-icons' ) ); - $this->assertStringContainsString( '', $new_actions['deactivate'] ); - - remove_filter( 'wp_is_large_network', '__return_true' ); - } -} diff --git a/tests/php/src/BackgroundTask/MonitorCssTransientCachingTest.php b/tests/php/src/BackgroundTask/MonitorCssTransientCachingTest.php deleted file mode 100644 index eda2cce661f..00000000000 --- a/tests/php/src/BackgroundTask/MonitorCssTransientCachingTest.php +++ /dev/null @@ -1,443 +0,0 @@ -was_wp_using_ext_object_cache = wp_using_ext_object_cache(); - wp_using_ext_object_cache( false ); - $this->original_wp_version = $GLOBALS['wp_version']; - } - - /** - * Tear down the tests by clearing the list of scheduled events. - */ - public function tear_down() { - _set_cron_array( [] ); - wp_using_ext_object_cache( $this->was_wp_using_ext_object_cache ); - $GLOBALS['wp_version'] = $this->original_wp_version; - parent::tear_down(); - } - - /** - * @covers ::register() - */ - public function test_register() { - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - $monitor->register(); - $this->assertEquals( 10, has_action( 'amp_plugin_update', [ $monitor, 'handle_plugin_update' ] ) ); - $this->assertEquals( 10, has_filter( 'amp_options_updating', [ $monitor, 'sanitize_disabled_option' ] ) ); - } - - /** - * @covers ::get_interval() - */ - public function test_get_interval() { - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - $this->assertIsString( $this->call_private_method( $monitor, 'get_interval' ) ); - } - - /** - * @covers ::get_event_name() - */ - public function test_get_event_name() { - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - $this->assertIsString( $this->call_private_method( $monitor, 'get_event_name' ) ); - } - - /** - * Test whether an event is actually scheduled when the monitor is registered. - * - * @uses \AmpProject\AmpWP\BackgroundTask\CronBasedBackgroundTask::schedule_event - * @uses \AmpProject\AmpWP\BackgroundTask\BackgroundTaskDeactivator::deactivate - */ - public function test_event_gets_scheduled_and_unscheduled() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->assertFalse( wp_next_scheduled( MonitorCssTransientCaching::EVENT_NAME ) ); - - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - $monitor->schedule_event(); - - $timestamp = wp_next_scheduled( MonitorCssTransientCaching::EVENT_NAME ); - - $this->assertNotFalse( $timestamp ); - $this->assertIsInt( $timestamp ); - $this->assertGreaterThan( 0, $timestamp ); - } - - /** - * Test whether time series are calculated and stored when the monitor is processing. - * - * @covers ::process() - */ - public function test_process_causes_time_series_to_be_stored() { - delete_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ); - - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - $monitor->process(); - - $this->assertNotFalse( get_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ) ); - } - - /** - * Test whether transient caching is disabled once it hits the threshold. - * - * @covers ::process() - * @covers ::get_time_series() - * @covers ::get_sampling_range() - * @covers ::persist_time_series() - * @covers ::calculate_average() - * @covers ::get_threshold() - * @covers ::disable_css_transient_caching() - */ - public function test_process_disables_transient_caching_once_threshold_is_reached() { - delete_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ); - AMP_Options_Manager::update_option( Option::DISABLE_CSS_TRANSIENT_CACHING, false ); - - add_filter( - 'amp_css_transient_monitoring_threshold', - static function () { - return 10; - } - ); - add_filter( - 'amp_css_transient_monitoring_sampling_range', - static function () { - return 3; - } - ); - - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - - // Moving average should be 0. - $monitor->process( new DateTime( '2000-01-01' ), 5 ); - $this->assertEquals( [ '20000101' => 5 ], get_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ) ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::DISABLE_CSS_TRANSIENT_CACHING ) ); - - // Moving average should be 5. - $monitor->process( new DateTime( '2000-01-02' ), 10 ); - $this->assertEquals( - [ - '20000101' => 5, - '20000102' => 10, - ], - get_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ) - ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::DISABLE_CSS_TRANSIENT_CACHING ) ); - - // Moving average should be 7.5. - $monitor->process( new DateTime( '2000-01-03' ), 12 ); - $this->assertEquals( - [ - '20000101' => 5, - '20000102' => 10, - '20000103' => 12, - ], - get_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ) - ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::DISABLE_CSS_TRANSIENT_CACHING ) ); - - // Moving average should be 11. - $monitor->process( new DateTime( '2000-01-04' ), 12 ); - $this->assertEquals( - [ - '20000102' => 10, - '20000103' => 12, - '20000104' => 12, - ], - get_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY ) - ); - - $expected = [ - MonitorCssTransientCaching::WP_VERSION => get_bloginfo( 'version' ), - MonitorCssTransientCaching::GUTENBERG_VERSION => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null, - ]; - - $this->assertTrue( (bool) AMP_Options_Manager::get_option( Option::DISABLE_CSS_TRANSIENT_CACHING ) ); - $this->assertEquals( $expected, AMP_Options_Manager::get_option( Option::DISABLE_CSS_TRANSIENT_CACHING ) ); - } - - /** - * @covers ::enable_css_transient_caching() - * @covers ::disable_css_transient_caching() - * @covers ::is_css_transient_caching_disabled() - */ - public function test_enable_disable_is_css_transient_caching_disabled() { - $monitor = $this->injector->make( MonitorCssTransientCaching::class ); - $this->assertFalse( $monitor->is_css_transient_caching_disabled() ); - $monitor->disable_css_transient_caching(); - $this->assertTrue( $monitor->is_css_transient_caching_disabled() ); - $monitor->enable_css_transient_caching(); - $this->assertFalse( $monitor->is_css_transient_caching_disabled() ); - } - - /** @return array */ - public function get_data_to_test_sanitize_disabled_option() { - return [ - 'true' => [ - true, - true, - ], - 'false' => [ - false, - null, - ], - 'number' => [ - 123, - null, - ], - 'bad_array' => [ - [ 1, 2, 3 ], - null, - ], - 'partial_good_array' => [ - [ - MonitorCssTransientCaching::WP_VERSION => '123-\o/', - MonitorCssTransientCaching::GUTENBERG_VERSION => '45.21` => ``). - $actual = preg_replace( '/>\s*{\s*}\s*{}<', $actual ); - $expected = preg_replace( '/>\s*{\s*}\s*{}<', $expected ); - - // Normalize boolean attributes that use their name as value. - $actual = preg_replace( '/(?<=\s)([a-zA-Z-_]+)="(?:\1|)"/i', '$1', $actual ); - $expected = preg_replace( '/(?<=\s)([a-zA-Z-_]+)="(?:\1|)"/i', '$1', $expected ); - - $normalize_attributes = static function ( $element ) { - // Extract attributes for the given element. - if ( ! preg_match( '#^(<[a-z0-9-]+)(\s[^>]+)>$#i', $element, $matches ) ) { - return $element; - } - - // Split into individual attributes. - $attributes = array_map( - 'trim', - array_filter( - preg_split( - '#(\s+[^"\'\s=]+(?:=(?:"[^"]+"|\'[^\']+\'|[^"\'\s]+))?)#', - $matches[2], - -1, - PREG_SPLIT_DELIM_CAPTURE - ) - ) - ); - - // Normalize sort order. - sort( $attributes ); - - $attribute_string = implode( ' ', $attributes ); - - if ( ! empty( $attribute_string ) ) { - $attribute_string = " {$attribute_string}"; - } - - return "{$matches[1]}{$attribute_string}>"; - }; - - // Split into an array of individual elements. - $actual = preg_split( '#(<[^>]+>|[^<>]+)#', $actual, -1, PREG_SPLIT_DELIM_CAPTURE ); - $expected = preg_split( '#(<[^>]+>|[^<>]+)#', $expected, -1, PREG_SPLIT_DELIM_CAPTURE ); - - // Normalize the attributes for each individual element. - $actual = array_map( $normalize_attributes, array_filter( $actual ) ); - $expected = array_map( $normalize_attributes, array_filter( $expected ) ); - - $this->assertEquals( $expected, $actual, $message ); - } -} diff --git a/tests/php/src/Helpers/MockPluginEnvironment.php b/tests/php/src/Helpers/MockPluginEnvironment.php deleted file mode 100644 index 4ee9b2f69eb..00000000000 --- a/tests/php/src/Helpers/MockPluginEnvironment.php +++ /dev/null @@ -1,54 +0,0 @@ - [ - 'Name' => 'AMP', - 'Version' => AMP__VERSION, - ], - self::GUTENBERG_PLUGIN_FILE => [ - 'Name' => 'Gutenberg', - 'Version' => '8.2', - ], - self::FOO_PLUGIN_FILE => [ - 'Name' => 'Foo', - 'Version' => '0.1', - ], - self::BAR_PLUGIN_FILE => [ - 'Name' => 'Bar', - 'Version' => '0.2', - ], - self::BAZ_PLUGIN_FILE => [ - 'Name' => 'Baz', - 'Version' => '0.3', - ], - ]; - - const BAD_WIDGET_PLUGIN_FILE = 'bad-widget/bad-widget.php'; - const BAD_BLOCK_PLUGIN_FILE = 'bad-block.php'; - const BAD_HOOKS_PLUGIN_FILE = 'bad-hooks.php'; - const BAD_SHORTCODE_PLUGIN_FILE = 'bad-shortcode.php'; - - const BAD_PLUGIN_FILES = [ - self::BAD_BLOCK_PLUGIN_FILE, - self::BAD_HOOKS_PLUGIN_FILE, - self::BAD_SHORTCODE_PLUGIN_FILE, - self::BAD_WIDGET_PLUGIN_FILE, - ]; - - const BAD_PLUGINS_DIR = 'tests/php/data/plugins'; -} diff --git a/tests/php/src/Helpers/PrivateAccess.php b/tests/php/src/Helpers/PrivateAccess.php deleted file mode 100644 index 4e2ed604fd7..00000000000 --- a/tests/php/src/Helpers/PrivateAccess.php +++ /dev/null @@ -1,86 +0,0 @@ -getMethod( $method_name ); - $method->setAccessible( true ); - return $method->invokeArgs( $object, $args ); - } - - /** - * Call a private static method as if it was public. - * - * @param string $class Class string to call the method of. - * @param string $method_name Name of the method to call. - * @param array $args Optional. Array of arguments to pass to the method. - * @return mixed Return value of the method call. - * @throws ReflectionException If the class could not be reflected upon. - */ - private function call_private_static_method( $class, $method_name, $args = [] ) { - $method = ( new ReflectionClass( $class ) )->getMethod( $method_name ); - $method->setAccessible( true ); - return $method->invokeArgs( null, $args ); - } - - /** - * Set a private property as if it was public. - * - * @param object|string $object Object instance or class string to set the property of. - * @param string $property_name Name of the property to set. - * @param mixed $value Value to set the property to. - * @throws ReflectionException If the object could not be reflected upon. - */ - private function set_private_property( $object, $property_name, $value ) { - $property = ( new ReflectionClass( $object ) )->getProperty( $property_name ); - $property->setAccessible( true ); - - // Note: In PHP 8, `ReflectionProperty::getValue()` now requires that an object be supplied if it's a - // non-static property. - $property->isStatic() ? $property->setValue( $value ) : $property->setValue( $object, $value ); - } - - /** - * Get a private property as if it was public. - * - * @param object|string $object Object instance or class string to get the property of. - * @param string $property_name Name of the property to get. - * @return mixed Return value of the property. - * @throws ReflectionException If the object could not be reflected upon. - */ - private function get_private_property( $object, $property_name ) { - $property = ( new ReflectionClass( $object ) )->getProperty( $property_name ); - $property->setAccessible( true ); - - // Note: In PHP 8, `ReflectionProperty::getValue()` now requires that an object be supplied if it's a - // non-static property. - return $property->isStatic() ? $property->getValue() : $property->getValue( $object ); - } -} diff --git a/tests/php/src/Helpers/StubSanitizer.php b/tests/php/src/Helpers/StubSanitizer.php deleted file mode 100644 index e49b964121c..00000000000 --- a/tests/php/src/Helpers/StubSanitizer.php +++ /dev/null @@ -1,17 +0,0 @@ -dom; - } -} diff --git a/tests/php/src/Helpers/ThemesApiRequestMocking.php b/tests/php/src/Helpers/ThemesApiRequestMocking.php deleted file mode 100644 index 19ddf93c00e..00000000000 --- a/tests/php/src/Helpers/ThemesApiRequestMocking.php +++ /dev/null @@ -1,250 +0,0 @@ - 'Twenty Twenty One', - 'slug' => 'twentytwentyone', - 'version' => '1.3', - 'preview_url' => 'https://wp-themes.com/twentytwenty', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentytwentyone/screenshot.png?ver=1.3', - 'rating' => 86, - 'num_ratings' => '37', - 'homepage' => 'https://wordpress.org/themes/twentytwentyone/', - 'description' => '...', - 'requires' => '4.7', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Twenty', - 'slug' => 'twentytwenty', - 'version' => '1.3', - 'preview_url' => 'https://wp-themes.com/twentytwenty', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentytwenty/screenshot.png?ver=1.3', - 'rating' => 86, - 'num_ratings' => '37', - 'homepage' => 'https://wordpress.org/themes/twentytwenty/', - 'description' => 'Our default theme for 2020 is designed to take full advantage of the flexibility of the block editor. Organizations and businesses have the ability to create dynamic landing pages with endless layouts using the group and column blocks. The centered content column and fine-tuned typography also makes it perfect for traditional blogs. Complete editor styles give you a good idea of what your content will look like, even before you publish. You can give your site a personal touch by changing the background colors and the accent color in the Customizer. The colors of all elements on your site are automatically calculated based on the colors you pick, ensuring a high, accessible color contrast for your visitors.', - 'requires' => '4.7', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Nineteen', - 'slug' => 'twentynineteen', - 'version' => '1.5', - 'preview_url' => 'https://wp-themes.com/twentynineteen', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentynineteen/screenshot.png?ver=1.5', - 'rating' => 72, - 'num_ratings' => '54', - 'homepage' => 'https://wordpress.org/themes/twentynineteen/', - 'description' => 'Our 2019 default theme is designed to show off the power of the block editor. It features custom styles for all the default blocks, and is built so that what you see in the editor looks like what you\'ll see on your website. Twenty Nineteen is designed to be adaptable to a wide range of websites, whether you’re running a photo blog, launching a new business, or supporting a non-profit. Featuring ample whitespace and modern sans-serif headlines paired with classic serif body text, it\'s built to be beautiful on all screen sizes.', - 'requires' => '4.9.6', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Seventeen', - 'slug' => 'twentyseventeen', - 'version' => '2.3', - 'preview_url' => 'https://wp-themes.com/twentyseventeen', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentyseventeen/screenshot.png?ver=2.3', - 'rating' => 90, - 'num_ratings' => '110', - 'homepage' => 'https://wordpress.org/themes/twentyseventeen/', - 'description' => 'Twenty Seventeen brings your site to life with header video and immersive featured images. With a focus on business sites, it features multiple sections on the front page as well as widgets, navigation and social menus, a logo, and more. Personalize its asymmetrical grid with a custom color scheme and showcase your multimedia content with post formats. Our default theme for 2017 works great in many languages, for any abilities, and on any device.', - 'requires' => '4.7', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Sixteen', - 'slug' => 'twentysixteen', - 'version' => '2.1', - 'preview_url' => 'https://wp-themes.com/twentysixteen', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentysixteen/screenshot.png?ver=2.1', - 'rating' => 82, - 'num_ratings' => '76', - 'homepage' => 'https://wordpress.org/themes/twentysixteen/', - 'description' => 'Twenty Sixteen is a modernized take on an ever-popular WordPress layout — the horizontal masthead with an optional right sidebar that works perfectly for blogs and websites. It has custom color options with beautiful default color schemes, a harmonious fluid grid using a mobile-first approach, and impeccable polish in every detail. Twenty Sixteen will make your WordPress look beautiful everywhere.', - 'requires' => '4.4', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Fifteen', - 'slug' => 'twentyfifteen', - 'version' => '2.6', - 'preview_url' => 'https://wp-themes.com/twentyfifteen', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentyfifteen/screenshot.png?ver=2.6', - 'rating' => 88, - 'num_ratings' => '48', - 'homepage' => 'https://wordpress.org/themes/twentyfifteen/', - 'description' => 'Our 2015 default theme is clean, blog-focused, and designed for clarity. Twenty Fifteen\'s simple, straightforward typography is readable on a wide variety of screen sizes, and suitable for multiple languages. We designed it using a mobile-first approach, meaning your content takes center-stage, regardless of whether your visitors arrive by smartphone, tablet, laptop, or desktop computer.', - 'requires' => false, - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Fourteen', - 'slug' => 'twentyfourteen', - 'version' => '2.8', - 'preview_url' => 'https://wp-themes.com/twentyfourteen', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentyfourteen/screenshot.png?ver=2.8', - 'rating' => 88, - 'num_ratings' => '93', - 'homepage' => 'https://wordpress.org/themes/twentyfourteen/', - 'description' => 'In 2014, our default theme lets you create a responsive magazine website with a sleek, modern design. Feature your favorite homepage content in either a grid or a slider. Use the three widget areas to customize your website, and change your content\'s layout with a full-width page template and a contributor page to show off your authors. Creating a magazine website with WordPress has never been easier.', - 'requires' => false, - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Thirteen', - 'slug' => 'twentythirteen', - 'version' => '3.0', - 'preview_url' => 'https://wp-themes.com/twentythirteen', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentythirteen/screenshot.png?ver=3.0', - 'rating' => 82, - 'num_ratings' => '62', - 'homepage' => 'https://wordpress.org/themes/twentythirteen/', - 'description' => 'The 2013 theme for WordPress takes us back to the blog, featuring a full range of post formats, each displayed beautifully in their own unique way. Design details abound, starting with a vibrant color scheme and matching header images, beautiful typography and icons, and a flexible layout that looks great on any device, big or small.', - 'requires' => '3.6', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Twelve', - 'slug' => 'twentytwelve', - 'version' => '3.1', - 'preview_url' => 'https://wp-themes.com/twentytwelve', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentytwelve/screenshot.png?ver=3.1', - 'rating' => 92, - 'num_ratings' => '155', - 'homepage' => 'https://wordpress.org/themes/twentytwelve/', - 'description' => 'The 2012 theme for WordPress is a fully responsive theme that looks great on any device. Features include a front page template with its own widgets, an optional display font, styling for post formats on both index and single views, and an optional no-sidebar page template. Make it yours with a custom menu, header image, and background.', - 'requires' => '3.5', - 'requires_php' => '5.2.4', - ], - [ - 'name' => 'Twenty Eleven', - 'slug' => 'twentyeleven', - 'version' => '3.4', - 'preview_url' => 'https://wp-themes.com/twentyeleven', - 'author' => - [ - 'user_nicename' => 'wordpressdotorg', - 'profile' => 'https://profiles.wordpress.org/wordpressdotorg', - 'avatar' => 'https://secure.gravatar.com/avatar/61ee2579b8905e62b4b4045bdc92c11a?s=96&d=monsterid&r=g', - 'display_name' => 'WordPress.org', - ], - 'screenshot_url' => '//ts.w.org/wp-content/themes/twentyeleven/screenshot.png?ver=3.4', - 'rating' => 94, - 'num_ratings' => '45', - 'homepage' => 'https://wordpress.org/themes/twentyeleven/', - 'description' => 'The 2011 theme for WordPress is sophisticated, lightweight, and adaptable. Make it yours with a custom menu, header image, and background -- then go further with available theme options for light or dark color scheme, custom link colors, and three layout choices. Twenty Eleven comes equipped with a Showcase page template that transforms your front page into a showcase to show off your best content, widget support galore (sidebar, three footer areas, and a Showcase page widget area), and a custom "Ephemera" widget to display your Aside, Link, Quote, or Status posts. Included are styles for print and for the admin editor, support for featured images (as custom header images on posts and pages and as large images on featured "sticky" posts), and special styles for six different post formats.', - 'requires' => false, - 'requires_php' => '5.2.4', - ], - ]; - - /** - * Filters the external request within themes_api while testing. - */ - public function add_reader_themes_request_filter() { - add_filter( - 'pre_http_request', - static function ( $pre, $r, $request_url ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $pre; - } - - if ( 0 !== strpos( $request_url, 'https://api.wordpress.org/themes/' ) || false === strpos( $request_url, 'wordpressdotorg' ) ) { - return $pre; - } - - return [ - 'body' => wp_json_encode( [ 'themes' => self::$api_reader_themes ] ), - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - }, - 10, - 3 - ); - } -} diff --git a/tests/php/src/Helpers/ValidationRequestMocking.php b/tests/php/src/Helpers/ValidationRequestMocking.php deleted file mode 100644 index b89386fb0c2..00000000000 --- a/tests/php/src/Helpers/ValidationRequestMocking.php +++ /dev/null @@ -1,81 +0,0 @@ - AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'posts_per_page' => 100, - 'fields' => 'ids', - ] - ); - - return array_map( - static function( $post ) { - return remove_query_arg( 'amp', AMP_Validated_URL_Post_Type::get_url_from_post( $post ) ); - }, - $query->posts - ); - } - - /** - * Add filter to mock validate responses. - */ - public function add_validate_response_mocking_filter() { - add_filter( 'pre_http_request', [ $this, 'get_validate_response' ], 10, 3 ); - } - - /** - * Construct a WP HTTP response for a validation request. - * - * @return array The response. - */ - public function get_validate_response( $r, /** @noinspection PhpUnusedParameterInspection */ $args, $url ) { - if ( false === strpos( $url, 'amp_validate' ) ) { - return $r; - } - - $mock_validation = [ - 'results' => [ - [ - 'error' => [ - 'code' => 'foo', - 'sources' => [ - [ - 'type' => 'plugin', - 'name' => 'foo', - 'file' => 'foo/foo.php', - ], - ], - ], - 'sanitized' => false, - ], - ], - 'url' => home_url( '/' ), - ]; - - return [ - 'body' => wp_json_encode( $mock_validation ), - 'response' => [ - 'code' => 200, - 'message' => 'ok', - ], - ]; - } -} diff --git a/tests/php/src/Helpers/WithBlockEditorSupport.php b/tests/php/src/Helpers/WithBlockEditorSupport.php deleted file mode 100644 index 241e5c3e303..00000000000 --- a/tests/php/src/Helpers/WithBlockEditorSupport.php +++ /dev/null @@ -1,55 +0,0 @@ - true ] ); - $GLOBALS['post'] = self::factory()->post->create( [ 'post_type' => $post_type ] ); - - $previous_user = wp_get_current_user(); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - $supported_post_types = array_merge( - AMP_Options_Manager::get_option( Option::SUPPORTED_POST_TYPES ), - [ $post_type ] - ); - AMP_Options_Manager::update_option( Option::SUPPORTED_POST_TYPES, $supported_post_types ); - - wp_set_current_user( $previous_user instanceof WP_User ? $previous_user->ID : $previous_user ); - } - } -} diff --git a/tests/php/src/Helpers/WithoutBlockPreRendering.php b/tests/php/src/Helpers/WithoutBlockPreRendering.php deleted file mode 100644 index cf4e63708b7..00000000000 --- a/tests/php/src/Helpers/WithoutBlockPreRendering.php +++ /dev/null @@ -1,60 +0,0 @@ -post->create_and_get(); - } - - return $parsed_block; - } - ); - - add_filter( - 'render_block_context', - static function( $context, $parsed_block ) { - global $post; - - // Remove the dummy post from the global scope and unset post related data from the context. - if ( isset( $parsed_block['remove_post_data'] ) ) { - $post = null; - unset( $context['postId'], $context['postType'], $parsed_block['remove_post_data'] ); - } - - return $context; - }, - 10, - 2 - ); - } -} diff --git a/tests/php/src/IconTest.php b/tests/php/src/IconTest.php deleted file mode 100644 index 419c373eda0..00000000000 --- a/tests/php/src/IconTest.php +++ /dev/null @@ -1,62 +0,0 @@ -assertInstanceOf( Icon::class, $icon ); - - $html = $icon->to_html(); - $this->assertStringStartsWith( 'assertStringEndsWith( '', $html ); - $this->assertStringContainsString( "class=\"amp-icon amp-{$type}\"", $html ); - - $html = $icon->to_html( - [ - 'id' => 'amp-admin-bar-item', - 'class' => '" onclick="alert(\"evil\")">end', - 'onmouseover' => 'alert("BAD")', - ] - ); - $this->assertStringContainsString( "class=\"" onclick="alert(\"evil\")">end amp-icon amp-{$type}\"", $html ); - $this->assertStringContainsString( 'id="amp-admin-bar-item"', $html ); - $this->assertStringNotContainsString( 'onmouseover', $html ); - $this->assertStringEndsWith( '', $html ); - } -} diff --git a/tests/php/src/Infrastructure/InjectionChainTest.php b/tests/php/src/Infrastructure/InjectionChainTest.php deleted file mode 100644 index fbb50797b04..00000000000 --- a/tests/php/src/Infrastructure/InjectionChainTest.php +++ /dev/null @@ -1,48 +0,0 @@ -assertInstanceOf( InjectionChain::class, $chain ); - } - - public function test_it_accepts_new_resolutions() { - $chain = ( new InjectionChain() ) - ->add_resolution( 'something' ); - - $this->assertTrue( $chain->has_resolution( 'something' ) ); - $this->assertFalse( $chain->has_resolution( 'something_else' ) ); - } - - public function test_it_accepts_new_chain_entries() { - $chain = ( new InjectionChain() ) - ->add_to_chain( 'something' ); - - $this->assertEquals( 'something', $chain->get_class() ); - } - - public function test_it_returns_the_last_class_in_the_chain() { - $chain = ( new InjectionChain() ) - ->add_to_chain( 'first' ) - ->add_to_chain( 'second' ) - ->add_to_chain( 'third' ); - - $this->assertEquals( 'third', $chain->get_class() ); - } - - public function test_it_retains_all_elements_in_the_chain() { - $chain = ( new InjectionChain() ) - ->add_to_chain( 'first' ) - ->add_to_chain( 'second' ) - ->add_to_chain( 'third' ); - - $this->assertEquals( [ 'third', 'second', 'first' ], $chain->get_chain() ); - } -} diff --git a/tests/php/src/Infrastructure/LazilyInstantiatedServiceTest.php b/tests/php/src/Infrastructure/LazilyInstantiatedServiceTest.php deleted file mode 100644 index 154dcc23513..00000000000 --- a/tests/php/src/Infrastructure/LazilyInstantiatedServiceTest.php +++ /dev/null @@ -1,39 +0,0 @@ -assertInstanceOf( LazilyInstantiatedService::class, $lazy_service ); - } - - public function test_it_can_return_the_actual_service_it_represents() { - $callable = function () { - return $this->createMock( Service::class ); - }; - $lazy_service = new LazilyInstantiatedService( $callable ); - - $this->assertInstanceOf( Service::class, $lazy_service->instantiate() ); - } - - public function test_it_throws_when_instantiating_an_invalid_service() { - $callable = function () { - return new stdClass(); - }; - $lazy_service = new LazilyInstantiatedService( $callable ); - - $this->expectException( InvalidService::class ); - $this->expectExceptionMessage( 'The service "stdClass" is not recognized and cannot be registered.' ); - $lazy_service->instantiate(); - } -} diff --git a/tests/php/src/Infrastructure/ServiceBasedPluginTest.php b/tests/php/src/Infrastructure/ServiceBasedPluginTest.php deleted file mode 100644 index 09f62436aab..00000000000 --- a/tests/php/src/Infrastructure/ServiceBasedPluginTest.php +++ /dev/null @@ -1,370 +0,0 @@ -createMock( ServiceBasedPlugin::class ); - - $this->assertInstanceOf( ServiceBasedPlugin::class, $plugin ); - } - - public function test_it_can_return_its_container() { - $plugin = $this->getMockBuilder( ServiceBasedPlugin::class ) - ->setMethodsExcept( [ 'get_container' ] ) - ->enableOriginalConstructor() - ->getMock(); - - $container = $plugin->get_container(); - - $this->assertInstanceOf( ServiceContainer::class, $container ); - } - - public function test_it_can_be_registered() { - $plugin = $this->getMockBuilder( ServiceBasedPlugin::class ) - ->setMethodsExcept( [ 'register' ] ) - ->getMock(); - - $plugin->expects( $this->once() )->method( 'register_services' ); - - $plugin->register(); - } - - public function test_it_always_registers_an_injector_by_default() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( ServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( [ 'register', 'register_services' ] ) - ->getMock(); - - $this->assertEquals( 0, count( $container ) ); - - $plugin->register(); - - $this->assertEquals( 1, count( $container ) ); - $this->assertTrue( $container->has( 'injector' ) ); - $this->assertInstanceof( Injector::class, $container->get( 'injector' ) ); - } - - public function test_it_registers_default_services() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethods() - ->setMethodsExcept( - [ - 'register', - 'register_services', - 'get_service_classes', - ] - ) - ->getMock(); - - $this->assertEquals( 0, count( $container ) ); - - $plugin->register(); - - $this->assertEquals( 3, count( $container ) ); - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - } - - public function test_it_allows_services_to_be_filtered() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( - [ - 'register', - 'register_services', - 'get_service_classes', - ] - ) - ->getMock(); - - add_filter( - 'services', - static function () { - return [ 'filtered_service' => DummyService::class ]; - } - ); - - $this->assertFalse( $container->has( 'filtered_service' ) ); - - $plugin->register(); - - $this->assertEquals( 2, count( $container ) ); - $this->assertTrue( $container->has( 'filtered_service' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'filtered_service' ) ); - $this->assertfalse( $container->has( 'service_a' ) ); - $this->assertfalse( $container->has( 'service_b' ) ); - } - - public function test_it_provides_default_services_for_filtering() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( - [ - 'register', - 'register_services', - 'get_service_classes', - ] - ) - ->getMock(); - - add_filter( - 'services', - static function ( $services ) { - return array_merge( - $services, - [ 'filtered_service' => DummyService::class ] - ); - } - ); - - $this->assertFalse( $container->has( 'filtered_service' ) ); - - $plugin->register(); - - $this->assertEquals( 4, count( $container ) ); - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - $this->assertTrue( $container->has( 'filtered_service' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'filtered_service' ) ); - } - - public function test_it_registers_service_with_requirements() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( - [ - 'collect_missing_requirements', - 'register', - 'register_services', - 'requirements_are_met', - 'get_container', - 'get_service_classes', - ] - ) - ->getMock(); - - $service_callback = static function ( $services ) { - return array_merge( - $services, - [ 'service_with_requirements' => DummyServiceWithRequirements::class ] - ); - }; - - add_filter( 'services', $service_callback ); - - $plugin->register(); - - $this->assertEquals( 4, count( $container ) ); - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - $this->assertTrue( $container->has( 'service_with_requirements' ) ); - $this->assertInstanceof( DummyServiceWithRequirements::class, $container->get( 'service_with_requirements' ) ); - } - - public function test_it_handles_delays_for_requirements() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( - [ - 'collect_missing_requirements', - 'register', - 'register_services', - 'requirements_are_met', - 'get_container', - 'get_service_classes', - ] - ) - ->getMock(); - - $service_callback = static function ( $services ) { - return array_merge( - $services, - [ - 'service_a' => DummyServiceWithDelay::class, - 'service_with_requirements' => DummyServiceWithRequirements::class, - ] - ); - }; - - add_filter( 'services', $service_callback ); - - $plugin->register(); - - $this->assertEquals( 2, count( $container ) ); - $this->assertFalse( $container->has( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertFalse( $container->has( 'service_with_requirements' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - - do_action( 'some_action' ); - - $this->assertEquals( 4, count( $container ) ); - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceof( DummyServiceWithDelay::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - $this->assertTrue( $container->has( 'service_with_requirements' ) ); - $this->assertInstanceof( DummyServiceWithRequirements::class, $container->get( 'service_with_requirements' ) ); - } - - public function test_it_throws_an_exception_if_unrecognized_service_is_required() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( - [ - 'register', - 'register_services', - 'get_service_classes', - ] - ) - ->getMock(); - - $service_callback = static function () { - return [ 'service_with_requirements' => DummyServiceWithRequirements::class ]; - }; - - add_filter( 'services', $service_callback ); - - $this->expectExceptionMessage( 'The service ID "service_a" is not recognized and cannot be retrieved.' ); - $plugin->register(); - } - - public function test_it_generates_identifiers_as_needed() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( ServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( [ 'register', 'register_services' ] ) - ->getMock(); - - add_filter( - 'services', - static function () { - return [ DummyService::class ]; - } - ); - - $plugin->register(); - - $this->assertEquals( 2, count( $container ) ); - $this->assertTrue( $container->has( 'dummy_service' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'dummy_service' ) ); - } - - public function test_it_skips_unknown_service_classes() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( ServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( [ 'register', 'register_services' ] ) - ->getMock(); - - add_filter( - 'services', - static function () { - return [ - 'unknown_class' => 'UnknownClass', - ]; - } - ); - - $plugin->register(); - - $this->assertEquals( 1, count( $container ) ); - $this->assertFalse( $container->has( 'dummy_service' ) ); - } - - public function test_it_falls_back_to_defaults_on_broken_filtering() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->enableOriginalConstructor() - ->setConstructorArgs( [ true, null, $container ] ) - ->setMethodsExcept( - [ - 'register', - 'register_services', - 'get_service_classes', - ] - ) - ->getMock(); - - add_filter( - 'services', - static function () { - return null; - } - ); - - $plugin->register(); - - $this->assertEquals( 3, count( $container ) ); - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - } - - public function test_it_can_have_filtering_disabled() { - $container = new SimpleServiceContainer(); - $plugin = $this->getMockBuilder( DummyServiceBasedPlugin::class ) - ->setConstructorArgs( [ false, null, $container ] ) - ->enableOriginalConstructor() - ->setMethodsExcept( - [ - 'register', - 'register_services', - 'get_service_classes', - ] - ) - ->getMock(); - - add_filter( - 'services', - static function () { - return [ 'filtered_service' => DummyService::class ]; - } - ); - - $plugin->register(); - - $this->assertEquals( 3, count( $container ) ); - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceof( DummyService::class, $container->get( 'service_b' ) ); - $this->assertFalse( $container->has( 'filtered_service' ) ); - } -} diff --git a/tests/php/src/Infrastructure/SimpleInjectorTest.php b/tests/php/src/Infrastructure/SimpleInjectorTest.php deleted file mode 100644 index faa62a50767..00000000000 --- a/tests/php/src/Infrastructure/SimpleInjectorTest.php +++ /dev/null @@ -1,188 +0,0 @@ -assertInstanceOf( SimpleInjector::class, $injector ); - } - - public function test_it_implements_the_interface() { - $injector = new SimpleInjector(); - - $this->assertInstanceOf( Injector::class, $injector ); - } - - public function test_it_can_instantiate_a_concrete_class() { - $object = ( new SimpleInjector() ) - ->make( Fixture\DummyClass::class ); - - $this->assertInstanceOf( Fixture\DummyClass::class, $object ); - } - - public function test_it_can_autowire_a_class_with_a_dependency() { - $object = ( new SimpleInjector() ) - ->make( Fixture\DummyClassWithDependency::class ); - - $this->assertInstanceOf( Fixture\DummyClassWithDependency::class, $object ); - $this->assertInstanceOf( Fixture\DummyClass::class, $object->get_dummy() ); - } - - public function test_it_can_instantiate_a_bound_interface() { - $injector = ( new SimpleInjector() ) - ->bind( - Fixture\DummyInterface::class, - Fixture\DummyClassWithDependency::class - ); - $object = $injector->make( Fixture\DummyInterface::class ); - - $this->assertInstanceOf( Fixture\DummyInterface::class, $object ); - $this->assertInstanceOf( Fixture\DummyClassWithDependency::class, $object ); - $this->assertInstanceOf( Fixture\DummyClass::class, $object->get_dummy() ); - } - - public function test_it_returns_separate_instances_by_default() { - $injector = new SimpleInjector(); - $object_a = $injector->make( Fixture\DummyClass::class ); - $object_b = $injector->make( Fixture\DummyClass::class ); - - $this->assertNotSame( $object_a, $object_b ); - } - - public function test_it_returns_same_instances_if_shared() { - $injector = ( new SimpleInjector() ) - ->share( Fixture\DummyClass::class ); - $object_a = $injector->make( Fixture\DummyClass::class ); - $object_b = $injector->make( Fixture\DummyClass::class ); - - $this->assertSame( $object_a, $object_b ); - } - - public function test_it_can_instantiate_a_class_with_named_arguments() { - $object = ( new SimpleInjector() ) - ->make( - Fixture\DummyClassWithNamedArguments::class, - [ - 'argument_a' => 42, - 'argument_b' => 'Mr Alderson', - ] - ); - - $this->assertInstanceOf( Fixture\DummyClassWithNamedArguments::class, $object ); - $this->assertEquals( 42, $object->get_argument_a() ); - $this->assertEquals( 'Mr Alderson', $object->get_argument_b() ); - } - - public function test_it_allows_for_skipping_named_arguments_with_default_values() { - $object = ( new SimpleInjector() ) - ->make( - Fixture\DummyClassWithNamedArguments::class, - [ 'argument_a' => 42 ] - ); - - $this->assertInstanceOf( Fixture\DummyClassWithNamedArguments::class, $object ); - $this->assertEquals( 42, $object->get_argument_a() ); - $this->assertEquals( 'Mr Meeseeks', $object->get_argument_b() ); - } - - public function test_it_throws_if_a_required_named_arguments_is_missing() { - $this->expectException( FailedToMakeInstance::class ); - - ( new SimpleInjector() ) - ->make( Fixture\DummyClassWithNamedArguments::class ); - } - - public function test_it_throws_if_a_circular_reference_is_detected() { - $this->expectException( FailedToMakeInstance::class ); - $this->expectExceptionCode( FailedToMakeInstance::CIRCULAR_REFERENCE ); - - ( new SimpleInjector() ) - ->bind( - Fixture\DummyClass::class, - Fixture\DummyClassWithDependency::class - ) - ->make( Fixture\DummyClassWithDependency::class ); - } - - public function test_it_can_delegate_instantiation() { - $injector = ( new SimpleInjector() ) - ->delegate( - Fixture\DummyInterface::class, - static function ( $class ) { - $object = new stdClass(); - $object->class_name = $class; - return $object; - } - ); - $object = $injector->make( Fixture\DummyInterface::class ); - - $this->assertInstanceOf( stdClass::class, $object ); - $this->assertObjectHasAttribute( 'class_name', $object ); - $this->assertEquals( Fixture\DummyInterface::class, $object->class_name ); - } - - public function test_delegation_works_across_resolution() { - $injector = ( new SimpleInjector() ) - ->bind( - Fixture\DummyInterface::class, - Fixture\DummyClassWithDependency::class - ) - ->delegate( - Fixture\DummyClassWithDependency::class, - static function ( $class ) { - $object = new stdClass(); - $object->class_name = $class; - return $object; - } - ); - $object = $injector->make( Fixture\DummyInterface::class ); - - $this->assertInstanceOf( stdClass::class, $object ); - $this->assertObjectHasAttribute( 'class_name', $object ); - $this->assertEquals( Fixture\DummyClassWithDependency::class, $object->class_name ); - } - - public function test_arguments_can_be_bound() { - $object = ( new SimpleInjector() ) - ->bind_argument( - Fixture\DummyClassWithNamedArguments::class, - 'argument_a', - 42 - ) - ->bind_argument( - SimpleInjector::GLOBAL_ARGUMENTS, - 'argument_b', - 'Mr Alderson' - ) - ->make( Fixture\DummyClassWithNamedArguments::class ); - - $this->assertInstanceOf( Fixture\DummyClassWithNamedArguments::class, $object ); - $this->assertEquals( 42, $object->get_argument_a() ); - $this->assertEquals( 'Mr Alderson', $object->get_argument_b() ); - } - - public function test_callable_arguments_are_lazily_resolved() { - $injector = new SimpleInjector(); - $injector->bind_argument( - Fixture\DummyClassWithNamedArguments::class, - 'argument_a', - static function ( $class, $parameter, $arguments ) { - return $arguments['number']; } - ); - - $object = $injector->make( Fixture\DummyClassWithNamedArguments::class, [ 'number' => 123 ] ); - - $this->assertInstanceOf( Fixture\DummyClassWithNamedArguments::class, $object ); - $this->assertEquals( 123, $object->get_argument_a() ); - } -} diff --git a/tests/php/src/Infrastructure/SimpleServiceContainerTest.php b/tests/php/src/Infrastructure/SimpleServiceContainerTest.php deleted file mode 100644 index 176bc2380e1..00000000000 --- a/tests/php/src/Infrastructure/SimpleServiceContainerTest.php +++ /dev/null @@ -1,68 +0,0 @@ -assertInstanceOf( SimpleServiceContainer::class, $container ); - } - - public function test_it_implements_the_interface() { - $injector = new SimpleServiceContainer(); - - $this->assertInstanceOf( SimpleServiceContainer::class, $injector ); - } - - public function test_it_can_be_populated_at_initialization() { - $service = $this->createMock( Service::class ); - - $container = new SimpleServiceContainer( [ 'some_service' => $service ] ); - - $this->assertInstanceOf( SimpleServiceContainer::class, $container ); - } - - public function test_it_can_check_for_service_existence() { - $service = $this->createMock( Service::class ); - $container = new SimpleServiceContainer( [ 'known_service' => $service ] ); - - $this->assertTrue( $container->has( 'known_service' ) ); - $this->assertFalse( $container->has( 'unknown_service' ) ); - } - - public function test_it_can_return_services() { - $service = $this->createMock( Service::class ); - $container = new SimpleServiceContainer( [ 'some_service' => $service ] ); - - $retrieved_service = $container->get( 'some_service' ); - - $this->assertInstanceOf( Service::class, $retrieved_service ); - } - - public function test_it_can_accept_new_services() { - $service = $this->createMock( Service::class ); - $container = new SimpleServiceContainer( [ 'service_a' => $service ] ); - - $container->put( 'service_b', $service ); - - $this->assertTrue( $container->has( 'service_a' ) ); - $this->assertInstanceOf( Service::class, $container->get( 'service_a' ) ); - $this->assertTrue( $container->has( 'service_b' ) ); - $this->assertInstanceOf( Service::class, $container->get( 'service_b' ) ); - } - - public function test_it_throws_when_retrieving_an_unknown_service() { - $container = new SimpleServiceContainer(); - - $this->expectException( InvalidService::class ); - $this->expectExceptionMessage( 'The service ID "unknown_service" is not recognized and cannot be retrieved.' ); - $container->get( 'unknown_service' ); - } -} diff --git a/tests/php/src/Instrumentation/EventTest.php b/tests/php/src/Instrumentation/EventTest.php deleted file mode 100644 index 544e2d1a458..00000000000 --- a/tests/php/src/Instrumentation/EventTest.php +++ /dev/null @@ -1,123 +0,0 @@ - 'some_value' ], 'event-4;desc="Event N°4";some_label="some_value"' ], - [ 'event-5', 'Event N°5', [ 'float_label' => 3.14 ], 'event-5;desc="Event N°5";float_label="3.1"' ], - [ - 'event-6', - 'Event N°6', - [ - 'first_label' => 'first_value', - 'second_label' => 3.14, - ], - 'event-6;desc="Event N°6";first_label="first_value";second_label="3.1"', - ], - ]; - } - - /** - * Test the header string that the event object produces. - * - * @dataProvider data_get_header_string() - * - * @covers \AmpProject\AmpWP\Instrumentation\Event::get_name() - * @covers \AmpProject\AmpWP\Instrumentation\Event::get_description() - * @covers \AmpProject\AmpWP\Instrumentation\Event::add_properties() - * @covers \AmpProject\AmpWP\Instrumentation\Event::get_header_string() - * - * @param string $name Event name. - * @param string $description Event description. - * @param array|null $properties Optional. Associative array of properties - * or null to not use additional properties. - * @param string $expected Expected header string. - */ - public function test_get_header_string( $name, $description, $properties, $expected ) { - $event = new Event( $name, $description ); - - if ( null !== $properties ) { - $event->add_properties( $properties ); - } - - $this->assertEquals( $name, $event->get_name() ); - $this->assertEquals( $description, $event->get_description() ); - $this->assertEquals( $expected, $event->get_header_string() ); - } - - public function data_add_properties_typing() { - return [ - // Type of $properties collection. - 'null type' => [ null, InvalidEventProperties::class, 'but is of type NULL' ], - 'bool type' => [ true, InvalidEventProperties::class, 'but is of type bool' ], - 'string type' => [ 'a string', InvalidEventProperties::class, 'but is of type string' ], - 'int type' => [ 42, InvalidEventProperties::class, 'but is of type int' ], - 'float type' => [ 3.14, InvalidEventProperties::class, 'but is of type double' ], - 'object type' => [ new stdClass(), InvalidEventProperties::class, 'but is of type stdClass' ], - 'key-value object type' => [ (object) [ 'key' => 'value' ], InvalidEventProperties::class, 'but is of type stdClass' ], - 'array with single value' => [ [ 'key' => 'value' ], false ], - 'array with multiple values' => [ - [ - 'key_1' => 'value_1', - 'key_2' => 'value_2', - ], - false, - ], - 'empty array' => [ [], false ], - - // Type of $properties element key. - 'no key' => [ [ 'value' ], InvalidEventProperties::class, 'but found an element key of type integer' ], - 'bool key' => [ [ true => 'value' ], InvalidEventProperties::class, 'but found an element key of type integer' ], - 'string key' => [ [ 'key' => 'value' ], false ], - 'int key' => [ [ 42 => 'value' ], InvalidEventProperties::class, 'but found an element key of type int' ], - 'float key' => [ [ 3.14 => 'value' ], InvalidEventProperties::class, 'but found an element key of type integer' ], - - // Type of $properties element value. - 'null value' => [ [ 'key' => null ], InvalidEventProperties::class, 'but found an element value of type NULL' ], - 'bool value' => [ [ 'key' => true ], false ], - 'string value' => [ [ 'key' => 'a string' ], false ], - 'int value' => [ [ 'key' => 42 ], false ], - 'float value' => [ [ 'key' => 3.14 ], false ], - 'object value' => [ [ 'key' => new stdClass() ], InvalidEventProperties::class, 'but found an element value of type stdClass' ], - 'key-value object value' => [ [ 'key' => (object) [ 'key' => 'value' ] ], InvalidEventProperties::class, 'but found an element value of type stdClass' ], - ]; - } - - /** - * Test whether add_properties() correctly asserts the typing. - * - * @dataProvider data_add_properties_typing() - * - * @param mixed $properties Properties to add to the event. - * @param string|false $exception Exception class to expect, or false if no exceptions should be thrown. - * @param string|false $message Optional. Exception message to expect, or false if it shouldn't be checked. - */ - public function test_add_properties_typing( $properties, $exception, $message = false ) { - $event = new Event( 'test' ); - - if ( $exception ) { - $this->expectException( $exception ); - if ( $message ) { - $this->expectExceptionMessage( $message ); - } - } - - $event->add_properties( $properties ); - - $this->assertEquals( $properties, $this->get_private_property( $event, 'properties' ) ); - } -} diff --git a/tests/php/src/Instrumentation/EventWithDurationTest.php b/tests/php/src/Instrumentation/EventWithDurationTest.php deleted file mode 100644 index e515702a038..00000000000 --- a/tests/php/src/Instrumentation/EventWithDurationTest.php +++ /dev/null @@ -1,57 +0,0 @@ - 'some_value' ], 0.567, 'event-4;desc="Event N°4";some_label="some_value";dur="0.6"' ], - ]; - } - - /** - * Test the header string that the event with duration object produces. - * - * @dataProvider data_get_header_string() - * - * @covers \AmpProject\AmpWP\Instrumentation\EventWithDuration::get_name() - * @covers \AmpProject\AmpWP\Instrumentation\EventWithDuration::get_description() - * @covers \AmpProject\AmpWP\Instrumentation\EventWithDuration::get_duration() - * @covers \AmpProject\AmpWP\Instrumentation\EventWithDuration::get_header_string() - * - * @param string $name Event name. - * @param string $description Event description. - * @param array|null $properties Associative array of properties - * or null to not use additional properties. - * @param float $duration Event duration. - * @param string $expected Expected header string. - */ - public function test_get_header_string( $name, $description, $properties, $duration, $expected ) { - $event = new EventWithDuration( $name, $description, $properties, $duration ); - - $this->assertEquals( $name, $event->get_name() ); - $this->assertEquals( $description, $event->get_description() ); - $this->assertEquals( $duration, $event->get_duration() ); - $this->assertEquals( $expected, $event->get_header_string() ); - } - - /** - * Test setting the duration directly. - * - * @covers \AmpProject\AmpWP\Instrumentation\EventWithDuration::set_duration() - * @covers \AmpProject\AmpWP\Instrumentation\EventWithDuration::get_header_string() - */ - public function test_set_duration() { - $event = new EventWithDuration( 'my_event' ); - $event->set_duration( 12345.67890 ); - $this->assertEquals( 12345.67890, $event->get_duration() ); - $this->assertEquals( 'my_event;dur="12345.7"', $event->get_header_string() ); - } -} diff --git a/tests/php/src/Instrumentation/ServerTimingTest.php b/tests/php/src/Instrumentation/ServerTimingTest.php deleted file mode 100644 index f8beacfbe03..00000000000 --- a/tests/php/src/Instrumentation/ServerTimingTest.php +++ /dev/null @@ -1,393 +0,0 @@ -injector->make( ServerTiming::class ); - $server_timing->register(); - $this->assertEquals( 10, has_action( 'amp_server_timing_start', [ $server_timing, 'start' ] ) ); - $this->assertEquals( 10, has_action( 'amp_server_timing_stop', [ $server_timing, 'stop' ] ) ); - $this->assertEquals( 10, has_action( 'amp_server_timing_log', [ $server_timing, 'log' ] ) ); - $this->assertEquals( 10, has_action( 'amp_server_timing_send', [ $server_timing, 'send' ] ) ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - */ - public function test_it_can_record_events_with_duration_directly() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->start( 'event-1', 'Event N°1' ); - usleep( 100 * 1000 ); // 100ms. - $server_timing->stop( 'event-1' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-1']; - - $this->assertInstanceof( EventWithDuration::class, $event ); - $this->assertEquals( 'event-1', $event->get_name() ); - $this->assertEquals( 'Event N°1', $event->get_description() ); - $this->assertGreaterThan( 0.1, $event->get_duration() ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::register() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - */ - public function test_it_can_record_events_with_duration_via_actions() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->register(); - do_action( 'amp_server_timing_start', 'event-2', 'Event N°2' ); - usleep( 100 * 1000 ); // 100ms. - do_action( 'amp_server_timing_stop', 'event-2' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-2']; - - $this->assertInstanceof( EventWithDuration::class, $event ); - $this->assertEquals( 'event-2', $event->get_name() ); - $this->assertEquals( 'Event N°2', $event->get_description() ); - $this->assertGreaterThan( 0.1, $event->get_duration() ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::log() - */ - public function test_it_can_record_events_without_duration_directly() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->log( 'event-3', 'Event N°3' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-3']; - - $this->assertInstanceof( Event::class, $event ); - $this->assertNotInstanceof( EventWithDuration::class, $event ); - $this->assertEquals( 'event-3', $event->get_name() ); - $this->assertEquals( 'Event N°3', $event->get_description() ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::register() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::log() - */ - public function test_it_can_record_events_without_duration_via_actions() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->register(); - do_action( 'amp_server_timing_log', 'event-4', 'Event N°4' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-4']; - - $this->assertInstanceof( Event::class, $event ); - $this->assertNotInstanceof( EventWithDuration::class, $event ); - $this->assertEquals( 'event-4', $event->get_name() ); - $this->assertEquals( 'Event N°4', $event->get_description() ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::log() - */ - public function test_it_can_forward_additional_properties_directly() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->start( - 'event-5', - 'Event N°5', - [ - 'prop-1' => 'val-1', - 'prop-2' => 'val-2', - ] - ); - $server_timing->stop( 'event-5' ); - $server_timing->log( - 'event-6', - 'Event N°6', - [ - 'prop-3' => 'val-3', - 'prop-4' => 'val-4', - ] - ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event_5 = $events['event-5']; - $event_6 = $events['event-6']; - - $this->assertEquals( - [ - 'prop-1' => 'val-1', - 'prop-2' => 'val-2', - ], - $this->get_private_property( $event_5, 'properties' ) - ); - $this->assertEquals( - [ - 'prop-3' => 'val-3', - 'prop-4' => 'val-4', - ], - $this->get_private_property( $event_6, 'properties' ) - ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::register() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::log() - */ - public function test_it_can_forward_additional_properties_via_actions() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->register(); - do_action( - 'amp_server_timing_start', - 'event-7', - 'Event N°7', - [ - 'prop-5' => 'val-5', - 'prop-6' => 'val-6', - ] - ); - do_action( 'amp_server_timing_stop', 'event-7' ); - do_action( - 'amp_server_timing_log', - 'event-8', - 'Event N°8', - [ - 'prop-7' => 'val-7', - 'prop-8' => 'val-8', - ] - ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event_7 = $events['event-7']; - $event_8 = $events['event-8']; - - $this->assertEquals( - [ - 'prop-5' => 'val-5', - 'prop-6' => 'val-6', - ], - $this->get_private_property( $event_7, 'properties' ) - ); - $this->assertEquals( - [ - 'prop-7' => 'val-7', - 'prop-8' => 'val-8', - ], - $this->get_private_property( $event_8, 'properties' ) - ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::register() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::get_header_string() - */ - public function test_it_can_return_a_header_string() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->register(); - do_action( - 'amp_server_timing_start', - 'event-9', - 'Event N°9', - [ - 'prop-9' => 'val-9', - 'prop-10' => 'val-10', - ] - ); - do_action( 'amp_server_timing_stop', 'event-9' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-9']; - $event->set_duration( 3.14 ); - - $this->assertStringContainsString( 'event-9;desc="Event N°9";prop-9="val-9";prop-10="val-10";dur="3.1"', $server_timing->get_header_string() ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::get_header_string() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::send() - */ - public function test_it_can_send_headers_directly() { - $server_timing = $this->injector->make( ServerTiming::class ); - - $server_timing->start( 'event-10', 'Event N°10' ); - $server_timing->stop( 'event-10' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-10']; - $event->set_duration( 12345.67890 ); - - $server_timing->send(); - - $this->assertContains( - [ - 'name' => 'Server-Timing', - 'value' => 'event-10;desc="Event N°10";dur="12345.7"', - 'replace' => true, - 'status_code' => null, - ], - AMP_HTTP::$headers_sent - ); - } - - /** - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::register() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::start() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::stop() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::get_header_string() - * @covers \AmpProject\AmpWP\Instrumentation\ServerTiming::send() - */ - public function test_it_can_send_headers_via_action() { - $server_timing = $this->injector->make( ServerTiming::class ); - $server_timing->register(); - - do_action( 'amp_server_timing_start', 'event-11', 'Event N°11' ); - do_action( 'amp_server_timing_stop', 'event-11' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $event = $events['event-11']; - $event->set_duration( 3.14 ); - - do_action( 'amp_server_timing_send' ); - - $this->assertContains( - [ - 'name' => 'Server-Timing', - 'value' => 'event-11;desc="Event N°11";dur="3.1"', - 'replace' => true, - 'status_code' => null, - ], - AMP_HTTP::$headers_sent - ); - } - - public function test_it_sends_restricted_output_by_default() { - $server_timing = $this->injector->make( ServerTiming::class ); - $this->assertFalse( - $this->get_private_property( - $server_timing, - 'verbose' - ) - ); - } - - public function test_it_sends_restricted_output_with_query_var_but_not_logged_in() { - $_GET[ QueryVar::VERBOSE_SERVER_TIMING ] = '1'; - $server_timing = $this->injector->make( ServerTiming::class ); - $this->assertFalse( - $this->get_private_property( - $server_timing, - 'verbose' - ) - ); - } - - public function test_it_sends_restricted_output_when_logged_in_but_no_query_var() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $server_timing = $this->injector->make( ServerTiming::class ); - $this->assertFalse( - $this->get_private_property( - $server_timing, - 'verbose' - ) - ); - } - - public function test_it_sends_restricted_output_with_query_var_and_logged_in() { - $_GET[ QueryVar::VERBOSE_SERVER_TIMING ] = '1'; - wp_set_current_user( self::factory()->user->create( [ 'role' => 'subscriber' ] ) ); - $server_timing = $this->injector->make( ServerTiming::class ); - $this->assertFalse( - $this->get_private_property( - $server_timing, - 'verbose' - ) - ); - } - - public function test_it_sends_verbose_output_with_query_var_and_logged_in() { - $_GET[ QueryVar::VERBOSE_SERVER_TIMING ] = '1'; - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $server_timing = $this->injector->make( ServerTiming::class ); - $this->assertTrue( - $this->get_private_property( - $server_timing, - 'verbose' - ) - ); - } - - public function test_it_restricts_output_in_non_verbose_mode() { - $server_timing = $this->injector->make( ServerTiming::class ); - - $server_timing->start( 'main-event', 'Main Event', [], false ); - $server_timing->stop( 'main-event' ); - $server_timing->start( 'verbose-event', 'Verbose Event', [], true ); - $server_timing->stop( 'verbose-event' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $main_event = $events['main-event']; - $main_event->set_duration( 1.2 ); - $this->assertNotContains( 'verbose-event', $events ); - - $server_timing->send(); - - $this->assertContains( - [ - 'name' => 'Server-Timing', - 'value' => 'main-event;desc="Main Event";dur="1.2"', - 'replace' => true, - 'status_code' => null, - ], - AMP_HTTP::$headers_sent - ); - } - - public function test_it_doesnt_restrict_output_in_verbose_mode() { - $server_timing = $this->injector->make( ServerTiming::class ); - $this->set_private_property( $server_timing, 'verbose', true ); - - $server_timing->start( 'main-event', 'Main Event', [], false ); - $server_timing->stop( 'main-event' ); - $server_timing->start( 'verbose-event', 'Verbose Event', [], true ); - $server_timing->stop( 'verbose-event' ); - - $events = $this->get_private_property( $server_timing, 'events' ); - $main_event = $events['main-event']; - $main_event->set_duration( 1.2 ); - $verbose_event = $events['verbose-event']; - $verbose_event->set_duration( 3.4 ); - - $server_timing->send(); - - $this->assertContains( - [ - 'name' => 'Server-Timing', - 'value' => 'main-event;desc="Main Event";dur="1.2",verbose-event;desc="Verbose Event";dur="3.4"', - 'replace' => true, - 'status_code' => null, - ], - AMP_HTTP::$headers_sent - ); - } -} diff --git a/tests/php/src/Instrumentation/StopWatchEventTest.php b/tests/php/src/Instrumentation/StopWatchEventTest.php deleted file mode 100644 index a07595f092b..00000000000 --- a/tests/php/src/Instrumentation/StopWatchEventTest.php +++ /dev/null @@ -1,17 +0,0 @@ -assertEquals( 0.0, $stop_watch_event->get_duration() ); - usleep( 100 * 1000 ); // 100ms - $stop_watch_event->stop(); - $this->assertGreaterThan( 0.1, $stop_watch_event->get_duration() ); - } -} diff --git a/tests/php/src/Instrumentation/StopWatchTest.php b/tests/php/src/Instrumentation/StopWatchTest.php deleted file mode 100644 index df80c34d875..00000000000 --- a/tests/php/src/Instrumentation/StopWatchTest.php +++ /dev/null @@ -1,28 +0,0 @@ -start( 'single' ); - usleep( 100 * 1000 ); // 100ms - $stop_watch_event = $stop_watch->stop( 'single' ); - $this->assertGreaterThan( 0.1, $stop_watch_event->get_duration() ); - } - - public function test_it_can_measure_multiple_events() { - $stop_watch = new StopWatch(); - $stop_watch->start( 'first' ); - $stop_watch->start( 'second' ); - $second_stop_watch_event = $stop_watch->stop( 'second' ); - usleep( 100 * 1000 ); // 100ms - $first_stop_watch_event = $stop_watch->stop( 'first' ); - $this->assertGreaterThan( 0.1, $first_stop_watch_event->get_duration() ); - $this->assertLessThan( 0.1, $second_stop_watch_event->get_duration() ); - } -} diff --git a/tests/php/src/LoadingErrorTest.php b/tests/php/src/LoadingErrorTest.php deleted file mode 100644 index d83c104f0c9..00000000000 --- a/tests/php/src/LoadingErrorTest.php +++ /dev/null @@ -1,32 +0,0 @@ -instance = $this->injector->make( LoadingError::class ); - } - - public function test_it_can_be_initialized() { - $this->assertInstanceOf( Service::class, $this->instance ); - } - - /** @covers ::render() */ - public function test_render() { - $output = get_echo( [ $this->instance, 'render' ] ); - $this->assertStringContainsString( '', $output ); - $this->assertStringContainsString( '
assertStringContainsString( '

', $output ); - $this->assertStringContainsString( '

', $output ); - } -} diff --git a/tests/php/src/MobileRedirectionTest.php b/tests/php/src/MobileRedirectionTest.php deleted file mode 100644 index 8ccd3b27717..00000000000 --- a/tests/php/src/MobileRedirectionTest.php +++ /dev/null @@ -1,714 +0,0 @@ -paired_routing = $this->injector->make( PairedRouting::class ); - $this->instance = new MobileRedirection( $this->paired_routing ); - } - - public function tear_down() { - $_COOKIE = []; - unset( $GLOBALS['wp_customize'] ); - AMP_HTTP::$purged_amp_query_vars = []; - $GLOBALS['wp_the_query'] = $GLOBALS['wp_query']; // This is missing in core. - parent::tear_down(); - } - - public function test__construct() { - $this->assertInstanceOf( MobileRedirection::class, $this->instance ); - $this->assertInstanceOf( Service::class, $this->instance ); - $this->assertInstanceOf( Registerable::class, $this->instance ); - } - - /** @covers ::register() */ - public function test_register_legacy_reader_mode() { - AMP_Options_Manager::update_options( - [ - Option::MOBILE_REDIRECT => true, - Option::THEME_SUPPORT => AMP_Theme_Support::READER_MODE_SLUG, - Option::READER_THEME => ReaderThemes::DEFAULT_READER_THEME, - ] - ); - $this->instance->register(); - $this->assertSame( 10, has_filter( 'amp_default_options', [ $this->instance, 'filter_default_options' ] ) ); - $this->assertSame( 10, has_filter( 'amp_options_updating', [ $this->instance, 'sanitize_options' ] ) ); - $this->assertSame( PHP_INT_MAX, has_action( 'template_redirect', [ $this->instance, 'redirect' ] ) ); - $this->assertSame( 0, has_filter( 'amp_to_amp_linking_enabled', '__return_true' ) ); - $this->assertSame( 10, has_filter( 'comment_post_redirect', [ $this->instance, 'filter_comment_post_redirect' ] ) ); - - $this->assertTrue( amp_is_legacy() ); - $this->assertSame( 10, has_filter( 'get_comments_link', [ $this->instance, 'add_noamp_mobile_query_var' ] ) ); - $this->assertSame( 10, has_filter( 'respond_link', [ $this->instance, 'add_noamp_mobile_query_var' ] ) ); - } - - /** @covers ::register() */ - public function test_register_transitional_mode() { - AMP_Options_Manager::update_options( - [ - Option::MOBILE_REDIRECT => true, - Option::THEME_SUPPORT => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ] - ); - $this->instance->register(); - $this->assertSame( 10, has_filter( 'amp_default_options', [ $this->instance, 'filter_default_options' ] ) ); - $this->assertSame( 10, has_filter( 'amp_options_updating', [ $this->instance, 'sanitize_options' ] ) ); - $this->assertSame( PHP_INT_MAX, has_action( 'template_redirect', [ $this->instance, 'redirect' ] ) ); - $this->assertSame( 0, has_filter( 'amp_to_amp_linking_enabled', '__return_true' ) ); - $this->assertSame( 10, has_filter( 'comment_post_redirect', [ $this->instance, 'filter_comment_post_redirect' ] ) ); - - $this->assertFalse( amp_is_legacy() ); - $this->assertFalse( has_filter( 'get_comments_link', [ $this->instance, 'add_noamp_mobile_query_var' ] ) ); - $this->assertFalse( has_filter( 'respond_link', [ $this->instance, 'add_noamp_mobile_query_var' ] ) ); - } - - /** @covers ::register() */ - public function test_register_not_enabled() { - remove_all_filters( 'amp_to_amp_linking_enabled' ); - AMP_Options_Manager::update_option( Option::MOBILE_REDIRECT, false ); - $instance = new MobileRedirection( $this->paired_routing ); - $instance->register(); - $this->assertSame( 10, has_filter( 'amp_default_options', [ $instance, 'filter_default_options' ] ) ); - $this->assertSame( 10, has_filter( 'amp_options_updating', [ $instance, 'sanitize_options' ] ) ); - $this->assert_hooks_not_added( $instance ); - } - - /** @covers ::register() */ - public function test_register_enabled_but_standard_mode() { - remove_all_filters( 'amp_to_amp_linking_enabled' ); - AMP_Options_Manager::update_options( - [ - Option::MOBILE_REDIRECT => true, - Option::THEME_SUPPORT => AMP_Theme_Support::STANDARD_MODE_SLUG, - ] - ); - $instance = new MobileRedirection( $this->paired_routing ); - $instance->register(); - $this->assertSame( 10, has_filter( 'amp_default_options', [ $instance, 'filter_default_options' ] ) ); - $this->assertSame( 10, has_filter( 'amp_options_updating', [ $instance, 'sanitize_options' ] ) ); - $this->assert_hooks_not_added( $instance ); - } - - /** - * Assert the service hooks were not added. - * - * @param MobileRedirection $instance - */ - private function assert_hooks_not_added( MobileRedirection $instance ) { - $this->assertFalse( has_action( 'template_redirect', [ $instance, 'redirect' ] ) ); - $this->assertFalse( has_filter( 'amp_to_amp_linking_enabled', '__return_true' ) ); - $this->assertFalse( has_filter( 'comment_post_redirect', [ $instance, 'filter_comment_post_redirect' ] ) ); - $this->assertFalse( has_filter( 'get_comments_link', [ $instance, 'add_noamp_mobile_query_var' ] ) ); - $this->assertFalse( has_filter( 'respond_link', [ $instance, 'add_noamp_mobile_query_var' ] ) ); - } - - /** @covers ::filter_default_options() */ - public function test_filter_default_options() { - $this->instance->register(); - $this->assertEquals( - [ - 'foo' => 'bar', - Option::MOBILE_REDIRECT => true, - ], - $this->instance->filter_default_options( [ 'foo' => 'bar' ] ) - ); - } - - /** @covers ::sanitize_options() */ - public function test_sanitize_options() { - $this->assertEquals( - [ - 'foo' => 'bar', - ], - $this->instance->sanitize_options( - [ 'foo' => 'bar' ], - [] - ) - ); - - $this->assertEquals( - [ Option::MOBILE_REDIRECT => true ], - $this->instance->sanitize_options( - [], - [ Option::MOBILE_REDIRECT => 'on' ] - ) - ); - - $this->assertEquals( - [ Option::MOBILE_REDIRECT => true ], - $this->instance->sanitize_options( - [], - [ Option::MOBILE_REDIRECT => 'true' ] - ) - ); - - $this->assertEquals( - [ Option::MOBILE_REDIRECT => false ], - $this->instance->sanitize_options( - [ Option::MOBILE_REDIRECT => true ], - [ Option::MOBILE_REDIRECT => false ] - ) - ); - - $this->assertEquals( - [ Option::MOBILE_REDIRECT => false ], - $this->instance->sanitize_options( - [ Option::MOBILE_REDIRECT => true ], - [ Option::MOBILE_REDIRECT => 'false' ] - ) - ); - } - - /** @covers ::get_current_amp_url() */ - public function test_get_current_amp_url() { - $this->go_to( add_query_arg( QueryVar::NOAMP, QueryVar::NOAMP_MOBILE, '/foo/' ) ); - $this->assertEquals( - $this->paired_routing->add_endpoint( home_url( '/foo/' ) ), - $this->instance->get_current_amp_url() - ); - } - - /** @covers ::redirect() */ - public function test_redirect_on_canonical_and_available() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->go_to( '/' ); - $this->assertTrue( amp_is_canonical() ); - $this->assertTrue( amp_is_available() ); - $this->instance->redirect(); - $this->assertFalse( has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_on_canonical_and_not_available() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, [ 'is_author' ] ); - $this->go_to( '/' ); - $this->assertTrue( amp_is_canonical() ); - $this->assertFalse( amp_is_available() ); - $this->instance->redirect(); - $this->assertFalse( has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_on_transitional_and_not_available() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, [ 'is_author' ] ); - $this->go_to( '/' ); - $this->assertFalse( amp_is_canonical() ); - $this->assertFalse( amp_is_available() ); - $this->instance->redirect(); - $this->assertFalse( has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_on_transitional_and_available_and_client_side_on_amp_endpoint() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - - $this->go_to( '/' ); - set_query_var( QueryVar::AMP, '1' ); - $this->assertFalse( amp_is_canonical() ); - $this->assertTrue( amp_is_available() ); - $this->assertTrue( amp_is_request() ); - $this->instance->redirect(); - $this->assertEquals( 10, has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - $this->assertEquals( 10, has_action( 'amp_post_template_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - - $this->assertEquals( 0, has_filter( 'amp_to_amp_linking_enabled', '__return_true' ) ); - $this->assertEquals( 100, has_filter( 'amp_to_amp_linking_element_excluded', [ $this->instance, 'filter_amp_to_amp_linking_element_excluded' ] ) ); - $this->assertEquals( 10, has_filter( 'amp_to_amp_linking_element_query_vars', [ $this->instance, 'filter_amp_to_amp_linking_element_query_vars' ] ) ); - - $this->assertEquals( 10, has_action( 'wp_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - $this->assertEquals( 10, has_action( 'amp_post_template_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_when_server_side_and_not_applicable() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - add_filter( 'amp_pre_is_mobile', '__return_false' ); - - $this->go_to( '/' ); - - $this->assertFalse( amp_is_request() ); - $this->assertFalse( $this->instance->is_mobile_request() ); - - $this->instance->redirect(); - $this->assertFalse( has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_not_amp_endpoint_with_client_side_redirection() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - - $this->go_to( '/' ); - $this->assertFalse( amp_is_request() ); - $this->assertTrue( amp_is_available() ); - $this->instance->redirect(); - $this->assertEquals( 10, has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - $this->assertEquals( 10, has_action( 'wp_head', [ $this->instance, 'add_mobile_alternative_link' ] ) ); - $this->assertEquals( 10, has_action( 'wp_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_not_amp_endpoint_with_server_side_redirection_on_mobile() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - add_filter( 'amp_pre_is_mobile', '__return_true' ); - - $this->go_to( '/' ); - $this->assertFalse( amp_is_request() ); - $this->assertTrue( amp_is_available() ); - $redirected_url = null; - add_filter( - 'wp_redirect', - static function ( $redirect_url ) use ( &$redirected_url ) { - $redirected_url = $redirect_url; - return false; - } - ); - $this->instance->redirect(); - $this->assertNotNull( $redirected_url ); - $this->assertEquals( - $this->paired_routing->add_endpoint( home_url( '/' ) ), - $redirected_url - ); - } - - /** @covers ::redirect() */ - public function test_redirect_not_amp_endpoint_with_server_side_redirection_on_mobile_when_cookie_set() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - add_filter( 'amp_pre_is_mobile', '__return_true' ); - - $this->go_to( '/' ); - $this->assertFalse( amp_is_request() ); - $this->assertTrue( amp_is_available() ); - $_COOKIE[ MobileRedirection::DISABLED_STORAGE_KEY ] = '1'; - $this->instance->redirect(); - - $this->assertEquals( 10, has_action( 'wp_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_not_amp_endpoint_with_server_side_redirection_on_mobile_when_noamp_query_var_present() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - add_filter( 'amp_pre_is_mobile', '__return_true' ); - - $this->go_to( add_query_arg( QueryVar::NOAMP, QueryVar::NOAMP_MOBILE, '/' ) ); - $_GET[ QueryVar::NOAMP ] = QueryVar::NOAMP_MOBILE; - $this->assertFalse( amp_is_request() ); - $this->assertTrue( amp_is_available() ); - - $this->assertArrayNotHasKey( MobileRedirection::DISABLED_STORAGE_KEY, $_COOKIE ); - $this->instance->redirect(); - $this->assertArrayHasKey( MobileRedirection::DISABLED_STORAGE_KEY, $_COOKIE ); - - $this->assertEquals( 10, has_action( 'wp_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - } - - /** @covers ::redirect() */ - public function test_redirect_on_transitional_and_available_and_server_side_on_amp_endpoint_with_cookie_set() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - add_filter( 'amp_pre_is_mobile', '__return_true' ); - - $this->go_to( '/' ); - set_query_var( QueryVar::AMP, '1' ); - $this->assertFalse( amp_is_canonical() ); - $this->assertTrue( amp_is_available() ); - $this->assertTrue( amp_is_request() ); - $_COOKIE[ MobileRedirection::DISABLED_STORAGE_KEY ] = '1'; - $this->instance->redirect(); - $this->assertArrayNotHasKey( MobileRedirection::DISABLED_STORAGE_KEY, $_COOKIE ); - $this->assertEquals( 10, has_action( 'wp_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - $this->assertEquals( 10, has_action( 'amp_post_template_head', [ $this->instance, 'add_mobile_version_switcher_styles' ] ) ); - - $this->assertEquals( 0, has_filter( 'amp_to_amp_linking_enabled', '__return_true' ) ); - $this->assertEquals( 100, has_filter( 'amp_to_amp_linking_element_excluded', [ $this->instance, 'filter_amp_to_amp_linking_element_excluded' ] ) ); - $this->assertEquals( 10, has_filter( 'amp_to_amp_linking_element_query_vars', [ $this->instance, 'filter_amp_to_amp_linking_element_query_vars' ] ) ); - - $this->assertEquals( 10, has_action( 'wp_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - $this->assertEquals( 10, has_action( 'amp_post_template_footer', [ $this->instance, 'add_mobile_version_switcher_link' ] ) ); - } - - /** @covers ::filter_amp_to_amp_linking_element_excluded() */ - public function test_filter_amp_to_amp_linking_element_excluded() { - $home_url_without_noamp = home_url( '/' ); - $home_url_with_noamp = add_query_arg( QueryVar::NOAMP, QueryVar::NOAMP_MOBILE, home_url( '/' ) ); - - $this->assertEquals( true, $this->instance->filter_amp_to_amp_linking_element_excluded( true, $home_url_without_noamp ) ); - $this->assertEquals( true, $this->instance->filter_amp_to_amp_linking_element_excluded( true, $home_url_with_noamp ) ); - $this->assertEquals( false, $this->instance->filter_amp_to_amp_linking_element_excluded( false, $home_url_without_noamp ) ); - $this->assertEquals( true, $this->instance->filter_amp_to_amp_linking_element_excluded( false, $home_url_with_noamp ) ); - } - - /** @covers ::filter_amp_to_amp_linking_element_query_vars() */ - public function test_filter_amp_to_amp_linking_element_query_vars() { - $this->assertEquals( - [ 'foo' => 'bar' ], - $this->instance->filter_amp_to_amp_linking_element_query_vars( [ 'foo' => 'bar' ], false ) - ); - $this->assertEquals( - [ - 'foo' => 'bar', - QueryVar::NOAMP => QueryVar::NOAMP_MOBILE, - ], - $this->instance->filter_amp_to_amp_linking_element_query_vars( [ 'foo' => 'bar' ], true ) - ); - } - - /** @covers ::is_mobile_request() */ - public function test_is_mobile_request() { - unset( $_SERVER['HTTP_USER_AGENT'] ); - $this->assertFalse( $this->instance->is_mobile_request() ); - - add_filter( 'amp_pre_is_mobile', '__return_true', 10 ); - $this->assertTrue( $this->instance->is_mobile_request() ); - - add_filter( 'amp_pre_is_mobile', '__return_false', 20 ); - $this->assertFalse( $this->instance->is_mobile_request() ); - - remove_all_filters( 'amp_pre_is_mobile' ); - - $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Mobile Safari/537.36'; - $this->assertTrue( $this->instance->is_mobile_request() ); - - $_SERVER['HTTP_USER_AGENT'] = 'Wristwatch'; - $this->assertFalse( $this->instance->is_mobile_request() ); - - add_filter( - 'amp_mobile_user_agents', - function ( $user_agents ) { - return array_merge( $user_agents, [ 'watch' ] ); - } - ); - - $this->assertTrue( $this->instance->is_mobile_request() ); - - $_SERVER['HTTP_USER_AGENT'] = 'Eyeglasses'; - $this->assertFalse( $this->instance->is_mobile_request() ); - - add_filter( - 'amp_mobile_user_agents', - function ( $user_agents ) { - return array_merge( $user_agents, [ '/eyeglass/i' ] ); - } - ); - - $this->assertTrue( $this->instance->is_mobile_request() ); - } - - /** @covers ::is_using_client_side_redirection() */ - public function test_is_using_client_side_redirection_in_customizer_preview() { - $this->assertTrue( $this->instance->is_using_client_side_redirection() ); - - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - $this->assertFalse( $this->instance->is_using_client_side_redirection() ); - - $this->assertFalse( $this->instance->is_using_client_side_redirection() ); - $this->init_customizer_preview(); - $this->assertTrue( $this->instance->is_using_client_side_redirection(), 'Expected client-side redirection to be enforced because in Customizer preview.' ); - } - - /** @covers ::is_using_client_side_redirection() */ - public function test_is_using_client_side_redirection_paired_browsing_active() { - if ( ! Services::get( 'dependency_support' )->has_support() ) { - $this->markTestSkipped( 'Paired browsing is not available in the current environment.' ); - } - - $this->assertTrue( $this->instance->is_using_client_side_redirection() ); - add_filter( 'amp_mobile_client_side_redirection', '__return_false' ); - $this->assertFalse( $this->instance->is_using_client_side_redirection() ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->register_paired_browsing_service(); - - $this->assertTrue( $this->instance->is_using_client_side_redirection(), 'Expected client-side redirection to be enforced because (possibly) in paired browsing.' ); - } - - /** @covers ::get_mobile_user_agents() */ - public function test_get_mobile_user_agents() { - $this->assertContains( 'Mobile', $this->instance->get_mobile_user_agents() ); - $this->assertNotContains( 'Watch', $this->instance->get_mobile_user_agents() ); - add_filter( - 'amp_mobile_user_agents', - function ( $user_agents ) { - return array_merge( $user_agents, [ 'Watch' ] ); - } - ); - $this->assertContains( 'Watch', $this->instance->get_mobile_user_agents() ); - } - - /** @covers ::is_redirection_disabled_via_query_param() */ - public function test_is_redirection_disabled_via_query_param() { - $this->assertFalse( $this->instance->is_redirection_disabled_via_query_param() ); - - $_GET[ QueryVar::NOAMP ] = QueryVar::NOAMP_MOBILE; - $this->assertTrue( $this->instance->is_redirection_disabled_via_query_param() ); - } - - /** @covers ::is_redirection_disabled_via_cookie() */ - public function test_is_redirection_disabled_via_cookie() { - $this->assertFalse( $this->instance->is_redirection_disabled_via_cookie() ); - $_COOKIE[ MobileRedirection::DISABLED_STORAGE_KEY ] = '1'; - $this->assertTrue( $this->instance->is_redirection_disabled_via_cookie() ); - } - - /** @covers ::set_mobile_redirection_disabled_cookie() */ - public function test_set_mobile_redirection_disabled_cookie() { - $this->assertArrayNotHasKey( MobileRedirection::DISABLED_STORAGE_KEY, $_COOKIE ); - $this->instance->set_mobile_redirection_disabled_cookie( true ); - $this->assertArrayHasKey( MobileRedirection::DISABLED_STORAGE_KEY, $_COOKIE ); - $this->instance->set_mobile_redirection_disabled_cookie( false ); - $this->assertArrayNotHasKey( MobileRedirection::DISABLED_STORAGE_KEY, $_COOKIE ); - } - - /** - * @covers ::add_mobile_redirect_script() - * @covers ::get_inline_script_tag() - * @covers ::sanitize_script_attributes() - */ - public function test_add_mobile_redirect_script() { - ob_start(); - $this->instance->add_mobile_redirect_script(); - $output = ob_get_clean(); - $this->assertStringContainsString( '

', ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ), - 'expected_level' => 2, - 'expected_required_amp_markup' => true, - ], - 'level_1_to_1' => [ - 'min_level' => 1, - 'body' => sprintf( '
', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ), - 'expected_level' => 1, - 'expected_required_amp_markup' => false, - ], - 'level_1_to_1_with_2' => [ - 'min_level' => 1, - 'body' => sprintf( '
', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE, ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ), - 'expected_level' => 1, - 'expected_required_amp_markup' => false, - ], - ]; - } - - /** - * @dataProvider get_data_to_test_finalize_document - * @covers ::get_effective_level() - * @covers ::finalize_document() - * @covers ::remove_required_amp_markup_if_not_used() - */ - public function test_finalize_document_and_get_effective_level( $min_level, $body, $expected_level, $expected_required_amp_markup ) { - $this->register_settings_and_set_user(); - AMP_Options_Manager::update_options( - [ - Sandboxing::OPTION_ENABLED => true, - Sandboxing::OPTION_LEVEL => $min_level, - ] - ); - - $dom = Document::fromHtml( - sprintf( - ' - - - - - - - - - - %s - -
- -
- - - ', - $body - ) - ); - - $actual_effective_level = $this->instance->get_effective_level( $dom ); - $this->assertEquals( $expected_level, $actual_effective_level ); - - $this->instance->finalize_document( $dom, $actual_effective_level ); - - $meta = $dom->xpath->query( '//meta[ @name = "generator" ]' )->item( 0 ); - $this->assertInstanceOf( Element::class, $meta ); - $this->assertStringEndsWith( "foo=bar; sandboxing-level={$min_level}:{$expected_level}", $meta->getAttribute( Attribute::CONTENT ) ); - - $expressions = [ - '//link[ @rel = "preconnect" and @href = "https://cdn.ampproject.org" ]', - '//style[ @amp-runtime ]', - '//script[ @src = "https://cdn.ampproject.org/v0.mjs" ]', - '//script[ @src = "https://cdn.ampproject.org/v0.js" ]', - ]; - foreach ( $expressions as $expression ) { - $this->assertEquals( $expected_required_amp_markup ? 1 : 0, $dom->xpath->query( $expression )->length, $expression ); - } - - $root_path = '//div[ @id = "wpadminbar" ]//li[ @id = "wp-admin-bar-amp" ]'; - $this->assertInstanceOf( - Element::class, - $dom->xpath->query( $root_path . '/a/span[ contains( @title, "Sandboxing level" ) ]' )->item( 0 ) - ); - $this->assertInstanceOf( - Element::class, - $dom->xpath->query( $root_path . '//li[ @id = "wp-admin-bar-amp-sandboxing-level" ]//a[ @href and contains( ., "Sandboxing level" ) ]' )->item( 0 ) - ); - } - - /** - * Register settings and set the current user. - */ - private function register_settings_and_set_user() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->instance->register(); - AMP_Options_Manager::register_settings(); - } -} diff --git a/tests/php/src/Support/SupportCliCommandTest.php b/tests/php/src/Support/SupportCliCommandTest.php deleted file mode 100644 index ddf975e05e7..00000000000 --- a/tests/php/src/Support/SupportCliCommandTest.php +++ /dev/null @@ -1,28 +0,0 @@ -assertEquals( 'amp support', SupportCliCommand::get_command_name() ); - } -} diff --git a/tests/php/src/Support/SupportDataTest.php b/tests/php/src/Support/SupportDataTest.php deleted file mode 100644 index 837bf646309..00000000000 --- a/tests/php/src/Support/SupportDataTest.php +++ /dev/null @@ -1,740 +0,0 @@ - null, - 'log_errors' => null, - ]; - - /** - * Set up. - * - * @inheritdoc - */ - public function set_up() { - - parent::set_up(); - - $this->instance = $this->injector->make( SupportData::class ); - - foreach ( array_keys( $this->previous_ini_config ) as $key ) { - $this->previous_ini_config[ $key ] = ini_get( $key ); - } - - $this->add_home_url_loopback_request_mocking(); - } - - /** - * Tear down. - * - * @inheritdoc - */ - public function tear_down() { - parent::tear_down(); - foreach ( $this->previous_ini_config as $key => $value ) { - ini_set( $key, $value ); // phpcs:ignore WordPress.PHP.IniSet.log_errors_Blacklisted, WordPress.PHP.IniSet.Risky - } - } - - /** - * @covers ::__construct() - * @covers ::parse_args() - */ - public function test_parse_args() { - - $url_post_id = $this->factory()->post->create( [] ); - $post_id = $this->factory()->post->create( [] ); - $term_id = $this->factory()->category->create( [] ); - $amp_validated_post = $this->factory()->post->create_and_get( - [ - 'post_title' => home_url( 'sample-page-for-amp-validation' ), - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - ] - ); - - $input = [ - 'urls' => [ get_permalink( $url_post_id ) ], - 'post_ids' => [ $post_id ], - 'term_ids' => [ $term_id ], - 'amp_validated_post_ids' => [ $amp_validated_post->ID ], - ]; - - $expected = array_map( - static function ( $url ) { - return AMP_Validated_URL_Post_Type::normalize_url_for_storage( $url ); - }, - [ - get_permalink( $url_post_id ), - get_term_link( $term_id ), - get_permalink( $post_id ), - $amp_validated_post->post_title, - ] - ); - - $instance = new SupportData( $input ); - - $this->assertEquals( $expected, $instance->urls ); - - } - - /** - * Create validated URL. - * - * @return array Validated URL posts. - */ - public function create_validated_url() { - - $plugin_info = SupportData::normalize_plugin_info( 'amp/amp.php' ); - - $post = $this->factory()->post->create_and_get( - [ - 'post_content' => 'Some post content', - ] - ); - - $term = $this->factory()->term->create_and_get(); - - $validated_url_post_content = wp_json_encode( - [ - [ - 'term_slug' => '1', - 'data' => [ - 'node_name' => 'script', - 'parent_name' => 'head', - 'code' => 'DISALLOWED_TAG', - 'type' => 'js_error', - 'node_attributes' => [ - 'src' => home_url( '/wp-includes/js/jquery/jquery.js?ver=__normalized__' ), - 'id' => 'jquery-core-js', - ], - 'node_type' => 1, - 'sources' => [ - [ - 'type' => 'plugin', - 'name' => $plugin_info['slug'], - 'file' => $plugin_info['slug'], - 'line' => 350, - 'function' => 'dummy_function', - 'hook' => 'wp_enqueue_scripts', - 'priority' => 10, - 'dependency_type' => 'script', - 'handle' => 'hello-script', - 'dependency_handle' => 'jquery-core', - 'text' => 'Start of the content. ' . home_url( '/additional.css' ) . ' End of the content', - ], - ], - ], - ], - ] - ); - - $validated_posts = []; - - $post_url = AMP_Validated_URL_Post_Type::normalize_url_for_storage( get_permalink( $post ) ); - $validated_posts['post'] = $this->factory()->post->create_and_get( - [ - 'post_title' => $post_url, - 'post_name' => md5( $post_url ), - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'post_content' => $validated_url_post_content, - 'meta_input' => [ - '_amp_queried_object' => [ - 'id' => $post->ID, - 'type' => 'post', - ], - AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY => AMP_Validated_URL_Post_Type::get_validated_environment(), - ], - ] - ); - - $term_url = AMP_Validated_URL_Post_Type::normalize_url_for_storage( get_term_link( $term ) ); - $validated_posts['term'] = $this->factory()->post->create_and_get( - [ - 'post_title' => $term_url, - 'post_name' => md5( $term_url ), - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'post_content' => $validated_url_post_content, - 'meta_input' => [ - '_amp_queried_object' => [ - 'id' => $term->term_id, - 'type' => 'term', - ], - AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY => AMP_Validated_URL_Post_Type::get_validated_environment(), - ], - ] - ); - - $search_url = AMP_Validated_URL_Post_Type::normalize_url_for_storage( home_url( '?s=example' ) ); - $validated_posts['search'] = $this->factory()->post->create_and_get( - [ - 'post_title' => $search_url, - 'post_name' => md5( $search_url ), - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'post_content' => $validated_url_post_content, - 'meta_input' => [ - '_amp_queried_object' => [ - 'type' => 'search', - ], - AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY => AMP_Validated_URL_Post_Type::get_validated_environment(), - ], - ] - ); - - return $validated_posts; - } - - /** - * @covers ::send_data() - * @covers ::get_data() - * @covers ::process_raw_post_errors() - */ - public function test_send_data() { - - $this->create_validated_url(); - - // Mock http request. - $support_data = []; - $expected_response = [ - 'status' => 'ok', - 'data' => [ - 'uuid' => 'ampwp-563e5de8-3129-55fb-af71-a6fbd9ef5026', - ], - ]; - - $callback_wp_remote = static function ( $preempt, $parsed_args ) use ( &$support_data, $expected_response ) { - - $support_data = $parsed_args['body']; - - return [ - 'body' => wp_json_encode( $expected_response ), - ]; - }; - - add_filter( 'pre_http_request', $callback_wp_remote, 10, 2 ); - - $instance = new SupportData( [] ); - $instance->send_data(); - - $support_data_keys = [ - 'site_url', - 'site_info', - 'plugins', - 'themes', - 'errors', - 'error_sources', - 'urls', - 'error_log', - ]; - - foreach ( $support_data_keys as $key ) { - $this->assertArrayHasKey( $key, $support_data ); - } - - $this->assertEquals( SupportData::get_home_url(), $support_data['site_url'] ); - - remove_filter( 'pre_http_request', $callback_wp_remote ); - } - - /** - * @covers ::get_data() - * @covers ::get_amp_urls() - * @covers ::process_raw_post_errors() - */ - public function test_get_data_with_specific_url() { - - $amp_validated_posts = $this->create_validated_url(); - - $search_urls = home_url( '?s=example' ); - - $instance = new SupportData( - [ - 'urls' => [ - $search_urls, - ], - ] - ); - - $output = $instance->get_data(); - - $this->assertCount( 1, $output['urls'] ); - $this->assertEquals( - AMP_Validated_URL_Post_Type::get_url_from_post( $amp_validated_posts['search'] ), - $output['urls'][0]['url'] - ); - } - - /** - * @covers ::send_data() - */ - public function test_send_data_with_error() { - $callback_wp_remote = static function ( $preempt, $parsed_args ) use ( &$support_data ) { - - $support_data = $parsed_args['body']; - - return [ - 'body' => 'some invalid string', - ]; - }; - add_filter( 'pre_http_request', $callback_wp_remote, 10, 2 ); - - $instance = new SupportData( [] ); - $response = $instance->send_data(); - - $this->assertInstanceOf( WP_Error::class, $response ); - - remove_filter( 'pre_http_request', $callback_wp_remote ); - } - - /** - * Test get_error_log method. - * - * @covers ::get_error_log() - */ - public function test_get_error_log() { - - $instance = new SupportData( [] ); - $output = $instance->get_error_log(); - - $this->assertArrayHasKey( 'log_errors', $output ); - $this->assertArrayHasKey( 'contents', $output ); - - $log_path = $this->temp_filename(); - $this->assertTrue( is_writable( $log_path ) ); - - ini_set( 'log_errors', 1 ); // phpcs:ignore WordPress.PHP.IniSet.log_errors_Blacklisted, WordPress.PHP.IniSet.Risky - ini_set( 'error_log', $log_path ); // phpcs:ignore WordPress.PHP.IniSet.log_errors_Blacklisted, WordPress.PHP.IniSet.Risky - - $input_content = ''; - $expected_content = ''; - - for ( $i = 1; $i <= 300; $i ++ ) { - $input_content .= "Line: $i\n"; - } - - for ( $i = 101; $i <= 300; $i ++ ) { - $expected_content .= "Line: $i\n"; - } - $expected_content = trim( $expected_content, "\n" ); - - file_put_contents( $log_path, $input_content ); - $output = $instance->get_error_log(); - - $this->assertEquals( $expected_content, $output['contents'] ); - } - - /** - * @covers ::get_site_info() - */ - public function test_get_site_info() { - - $site_info = $this->instance->get_site_info(); - - $site_info_keys = [ - 'site_url', - 'site_title', - 'php_version', - 'mysql_version', - 'wp_version', - 'wp_language', - 'wp_https_status', - 'wp_multisite', - 'wp_active_theme', - 'object_cache_status', - 'libxml_version', - 'is_defined_curl_multi', - 'loopback_requests', - 'amp_mode', - 'amp_version', - 'amp_plugin_configured', - 'amp_all_templates_supported', - 'amp_supported_post_types', - 'amp_supported_templates', - 'amp_mobile_redirect', - 'amp_reader_theme', - ]; - - foreach ( $site_info_keys as $key ) { - $this->assertArrayHasKey( $key, $site_info ); - } - } - - /** - * @covers ::get_plugin_info() - * @covers ::normalize_plugin_info() - */ - public function test_get_plugin_info() { - - $original_active_plugins = get_option( 'active_plugins' ); - $original_active_plugins = ( ! empty( $original_active_plugins ) && is_array( $original_active_plugins ) ) ? $original_active_plugins : []; - - // Mock the data - update_option( 'active_plugins', [ 'amp/amp.php' ] ); - - $plugin_info = $this->instance->get_plugin_info(); - $this->assertTrue( count( $plugin_info ) >= 1 ); - $plugin_info = array_filter( - $plugin_info, - static function ( $plugin ) { - return 'amp' === $plugin['slug']; - } - ); - - $expected_plugin_info = SupportData::normalize_plugin_info( 'amp/amp.php' ); - - $this->assertEquals( 'AMP', $plugin_info[0]['name'] ); - $this->assertEquals( 'amp', $plugin_info[0]['slug'] ); - - $plugin_keys = [ - 'name', - 'slug', - 'plugin_url', - 'version', - 'author', - 'author_url', - 'requires_wp', - 'requires_php', - 'is_active', - 'is_network_active', - 'is_suppressed', - ]; - - foreach ( $plugin_keys as $key ) { - $this->assertArrayHasKey( $key, $plugin_info[0] ); - $this->assertEquals( $expected_plugin_info[ $key ], $plugin_info[0][ $key ] ); - } - - // Restore data. - update_option( 'active_plugins', $original_active_plugins ); - } - - /** - * @covers ::get_theme_info() - * @covers ::normalize_theme_info() - */ - public function test_get_theme_info() { - - $theme_info = $this->instance->get_theme_info(); - if ( ! isset( $theme_info[0] ) ) { - $this->markTestSkipped( 'No active theme.' ); - } - - $active_theme = SupportData::normalize_theme_info( wp_get_theme() ); - - $theme_keys = [ - 'name', - 'slug', - 'version', - 'status', - 'tags', - 'text_domain', - 'requires_wp', - 'requires_php', - 'theme_url', - 'author', - 'author_url', - 'is_active', - 'parent_theme', - ]; - - foreach ( $theme_keys as $key ) { - $this->assertArrayHasKey( $key, $theme_info[0] ); - $this->assertEquals( $active_theme[ $key ], $theme_info[0][ $key ] ); - } - - } - - /** - * Data provider for $this->test_normalize_error_data() - * - * @return array - */ - public function normalize_error_data_provider() { - - return [ - 'empty' => [ - 'input' => [], - 'expected' => [], - ], - 'normalize' => [ - 'input' => [ - 'node_name' => 'script', - 'parent_name' => 'head', - 'code' => 'DISALLOWED_TAG', - 'type' => 'js_error', - 'node_attributes' => [ - 'src' => home_url( '/wp-includes/js/jquery/jquery.js?ver=__normalized__' ), - 'id' => 'jquery-core-js', - ], - 'node_type' => 1, - 'sources' => [ 'some data' ], - ], - 'expected' => [ - 'node_name' => 'script', - 'parent_name' => 'head', - 'code' => 'DISALLOWED_TAG', - 'node_attributes' => [ - 'src' => '/wp-includes/js/jquery/jquery.js?ver=__normalized__', - 'id' => 'jquery-core-js', - ], - 'node_type' => 1, - 'text' => '', - 'type' => 'js_error', - 'error_slug' => 'dc023279738b7ab0fd76fd6a6e004320039cba2f2eee04b30a5f3843262c2d0b', - ], - ], - ]; - } - - /** - * @dataProvider normalize_error_data_provider - * @covers ::normalize_error() - * @covers ::remove_domain() - * @covers ::generate_hash() - */ - public function test_normalize_error( $input, $expected ) { - - $this->assertEquals( $expected, SupportData::normalize_error( $input ) ); - } - - /** - * Data provider for $this->test_normalize_error_source() - * - * @return array - */ - public function normalize_error_source_data_provider() { - - $plugin_info = SupportData::normalize_plugin_info( 'amp/amp.php' ); - - $themes = wp_get_themes(); - $theme_info = array_pop( $themes ); - $theme_info = SupportData::normalize_theme_info( $theme_info ); - - $data = [ - 'empty' => [ - 'input' => [], - 'expected' => [], - ], - 'core' => [ - 'input' => [ - 'type' => 'core', - 'name' => 'wp-includes', - 'file' => 'script-loader.php', - 'line' => 2021, - 'function' => 'wp_enqueue_scripts', - 'hook' => 'wp_head', - 'priority' => 1, - 'dependency_type' => 'script', - 'handle' => 'jquery-blockui', - 'dependency_handle' => 'jquery-core', - ], - 'expected' => [], - ], - 'plugin' => [ - 'input' => [ - 'type' => 'plugin', - 'name' => $plugin_info['slug'], - 'file' => $plugin_info['slug'], - 'line' => 350, - 'function' => 'dummy_function', - 'hook' => 'wp_enqueue_scripts', - 'priority' => 10, - 'dependency_type' => 'script', - 'handle' => 'hello-script', - 'dependency_handle' => 'jquery-core', - 'text' => 'Start of the content. ' . home_url( '/additional.css' ) . ' End of the content', - ], - 'expected' => [ - 'dependency_handle' => 'jquery-core', - 'dependency_type' => 'script', - 'file' => $plugin_info['slug'], - 'function' => 'dummy_function', - 'handle' => 'hello-script', - 'hook' => 'wp_enqueue_scripts', - 'line' => 350, - 'name' => $plugin_info['slug'], - 'priority' => 10, - 'text' => 'Start of the content. /additional.css End of the content', - 'type' => 'plugin', - 'version' => $plugin_info['version'], - ], - ], - 'theme' => [ - 'input' => [ - 'type' => 'theme', - 'name' => $theme_info['slug'], - 'file' => 'inc/template-functions.php', - 'line' => 403, - 'function' => 'theme_post_content', - 'hook' => 'theme_loop_post', - 'priority' => 30, - ], - 'expected' => [ - 'file' => 'inc/template-functions.php', - 'function' => 'theme_post_content', - 'hook' => 'theme_loop_post', - 'line' => 403, - 'name' => $theme_info['slug'], - 'priority' => 30, - 'type' => 'theme', - 'version' => $theme_info['version'], - ], - ], - ]; - - foreach ( [ 'plugin', 'theme' ] as $key ) { - $data[ $key ]['expected']['error_source_slug'] = SupportData::generate_hash( $data[ $key ]['expected'] ); - ksort( $data[ $key ]['expected'] ); - } - - return $data; - } - - /** - * @dataProvider normalize_error_source_data_provider - * @covers ::normalize_error_source() - * @covers ::generate_hash() - */ - public function test_normalize_error_source( $input, $expected ) { - - $this->assertEquals( $expected, SupportData::normalize_error_source( $input ) ); - } - - /** - * Test get_amp_urls method. - * - * @covers ::get_amp_urls() - * @covers ::get_stylesheet_info() - * @covers ::process_raw_post_errors() - */ - public function test_get_amp_urls() { - - $this->create_validated_url(); - $data = $this->instance->get_amp_urls(); - - $this->assertCount( 1, $data['errors'] ); - $this->assertCount( 1, $data['error_sources'] ); - $this->assertCount( 3, $data['urls'] ); - - $keys = [ - 'url', - 'object_type', - 'object_subtype', - 'css_size_before', - 'css_size_after', - 'css_size_excluded', - 'css_budget_percentage', - 'errors', - ]; - - foreach ( $keys as $key ) { - $this->assertArrayHasKey( $key, $data['urls'][0] ); - } - } - - /** - * @covers ::get_home_url() - */ - public function test_get_home_url() { - - $home_url = home_url(); - $home_url = strtolower( trim( $home_url ) ); - $http_protocol = wp_parse_url( $home_url, PHP_URL_SCHEME ); - $home_url = str_replace( "$http_protocol://", '', $home_url ); - $home_url = untrailingslashit( $home_url ); - - $this->assertEquals( $home_url, SupportData::get_home_url() ); - } - - /** - * @covers ::remove_domain() - */ - public function test_remove_domain() { - - // Test 1: With string. - $input = home_url( '/sample-page/' ); - $expected = '/sample-page/'; - - $this->assertEquals( $expected, SupportData::remove_domain( $input ) ); - - // Test 2: With array and object. - $input_object = new stdClass(); - $input_object->key_1 = 'value_1'; - $input_object->key_2 = 'value_2'; - $input_object->key_3 = home_url( '/example-page/' ); - $input_object->key_4 = [ - 'value 1', - home_url( '/sample-page/' ), - home_url( '/sample-page-2/' ), - ]; - $input_array = (object) $input_object; - - $expected = [ - 'key_1' => 'value_1', - 'key_2' => 'value_2', - 'key_3' => '/example-page/', - 'key_4' => [ - 'value 1', - '/sample-page/', - '/sample-page-2/', - ], - ]; - - $this->assertEquals( $expected, SupportData::remove_domain( $input_object ) ); - $this->assertEquals( $expected, SupportData::remove_domain( $input_array ) ); - } - - /** - * @covers ::generate_hash() - */ - public function test_generate_hash() { - - $this->assertEmpty( SupportData::generate_hash( '' ) ); - - $input_data = new stdClass(); - $input_data->key_1 = 'value_1'; - $input_data->key_2 = 'value_2'; - $input_data->key_3 = 'value_3'; - - $expected_data = (array) $input_data; - - ksort( $expected_data ); - - $expected = hash( 'sha256', wp_json_encode( $expected_data ) ); - - $this->assertEquals( $expected, SupportData::generate_hash( $input_data ) ); - - $this->assertEquals( $expected, SupportData::generate_hash( (array) $input_data ) ); - } -} diff --git a/tests/php/src/Support/SupportRESTControllerTest.php b/tests/php/src/Support/SupportRESTControllerTest.php deleted file mode 100644 index f4da8bb5ff9..00000000000 --- a/tests/php/src/Support/SupportRESTControllerTest.php +++ /dev/null @@ -1,186 +0,0 @@ -instance = $this->injector->make( SupportRESTController::class ); - } - - /** - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - - $this->assertEquals( - 'rest_api_init', - SupportRESTController::get_registration_action() - ); - } - - /** - * @covers ::register() - */ - public function test_register() { - - do_action( 'rest_api_init' ); - - $rest_server = rest_get_server(); - - $namespaces = $this->get_private_property( $rest_server, 'namespaces' ); - - $this->assertContains( - 'amp/v1', - $rest_server->get_namespaces() - ); - - $this->assertContains( - '/amp/v1/send-diagnostic', - array_keys( $namespaces['amp/v1'] ) - ); - } - - /** - * @covers ::permission_callback() - */ - public function test_permission_callback() { - - $this->assertFalse( $this->instance->permission_callback() ); - - // Mock User. - wp_set_current_user( - self::factory()->user->create( - [ - 'role' => 'administrator', - ] - ) - ); - - $this->assertTrue( $this->instance->permission_callback() ); - } - - /** - * Data provider for $this->test_callback() - * - * @return array[] - */ - public function callback_data_provider() { - - return [ - 'fail' => [ - 'request_response' => [ - 'status' => 'fail', - 'data' => [ - 'message' => 'Fail to generate UUID', - ], - ], - 'expected' => new \WP_Error( - 'fail_to_send_data', - 'Failed to send support request. Please try again later.', - [ 'status' => 500 ] - ), - ], - 'success' => [ - 'request_response' => [ - 'status' => 'ok', - 'data' => [ - 'uuid' => 'ampwp-563e5de8-3129-55fb-af71-a6fbd9ef5026', - ], - ], - 'expected' => [ - 'success' => true, - 'data' => [ - 'uuid' => 'ampwp-563e5de8-3129-55fb-af71-a6fbd9ef5026', - ], - ], - ], - ]; - } - - /** - * @dataProvider callback_data_provider - * - * @param array $request_response Value to mock for response for API. - * @param array|WP_Error $expected Expected AJAX response. - * - * @covers ::callback() - */ - public function test_callback( $request_response, $expected ) { - - // Mock User. - wp_set_current_user( - self::factory()->user->create( - [ - 'role' => 'administrator', - ] - ) - ); - - $this->perform_test_on_callback_with( $request_response, $expected ); - } - - /** - * To perform test on $this->ajax_callback(). - * - * @param array $request_response Value to mock for response for API. - * @param array|WP_Error $expected Expected AJAX response. - * - * @return void - */ - private function perform_test_on_callback_with( $request_response, $expected ) { - - $callback_wp_remote = static function () use ( $request_response ) { - - return [ - 'body' => wp_json_encode( $request_response ), - ]; - }; - - add_filter( 'pre_http_request', $callback_wp_remote ); - - $request = new WP_REST_Request( 'POST', $this->instance->namespace . '/send-diagnostic', [] ); - $response = $this->instance->callback( $request ); - - if ( ! is_wp_error( $response ) ) { - $response = $response->get_data(); - } - - $this->assertEquals( $expected, $response ); - - remove_filter( 'pre_http_request', $callback_wp_remote ); - } -} diff --git a/tests/php/src/TestCase.php b/tests/php/src/TestCase.php deleted file mode 100644 index d4e275292e1..00000000000 --- a/tests/php/src/TestCase.php +++ /dev/null @@ -1,74 +0,0 @@ -original_wp_theme_features = $_wp_theme_features; - - // This was needed with the upgrade of yoast/wp-test-utils from 0.2.2 to 1.0.0. - $wp_the_query = $wp_query; - } - - /** - * Tear down. - * - * @inheritDoc - */ - public function tear_down() { - parent::tear_down(); - - global $_wp_theme_features; - $_wp_theme_features = $this->original_wp_theme_features; - } - - /** - * Assert that one associative array contains another. - * - * @param array $expected_subset Expected subset associative array. - * @param array $actual_superset Actual superset associative array. - */ - public function assertAssocArrayContains( $expected_subset, $actual_superset ) { - $this->assertArrayNotHasKey( 0, $expected_subset, 'Expected $expected_subset to be associative array.' ); - $this->assertArrayNotHasKey( 0, $actual_superset, 'Expected $actual_superset to be associative array.' ); - - foreach ( $expected_subset as $expected_key => $expected_value ) { - $this->assertArrayHasKey( $expected_key, $actual_superset ); - $this->assertEquals( $expected_value, $actual_superset[ $expected_key ] ); - } - } - - /** - * Assert that one indexed array contains another. - * - * @param array $expected_subset Expected subset indexed array. - * @param array $actual_superset Actual superset indexed array. - */ - public function assertIndexedArrayContains( $expected_subset, $actual_superset ) { - $this->assertArrayHasKey( 0, $expected_subset, 'Expected $expected_subset to be indexed array.' ); - $this->assertArrayHasKey( 0, $actual_superset, 'Expected $actual_superset to be indexed array.' ); - - foreach ( $expected_subset as $expected_value ) { - $this->assertContains( $expected_value, $actual_superset ); - } - } -} diff --git a/tests/php/src/ValidatedUrlStylesheetDataGarbageCollectionTest.php b/tests/php/src/ValidatedUrlStylesheetDataGarbageCollectionTest.php deleted file mode 100644 index 3ffa0fdd0e6..00000000000 --- a/tests/php/src/ValidatedUrlStylesheetDataGarbageCollectionTest.php +++ /dev/null @@ -1,74 +0,0 @@ -user->create( [ 'role' => 'administrator' ] ) ); - $this->assertFalse( wp_next_scheduled( ValidatedUrlStylesheetDataGarbageCollection::EVENT_NAME ) ); - - $monitor = new ValidatedUrlStylesheetDataGarbageCollection( new BackgroundTaskDeactivator() ); - $monitor->schedule_event(); - - $timestamp = wp_next_scheduled( ValidatedUrlStylesheetDataGarbageCollection::EVENT_NAME ); - - $this->assertNotFalse( $timestamp ); - $this->assertIsInt( $timestamp ); - $this->assertGreaterThan( 0, $timestamp ); - } - - /** - * Test whether stylesheet data is deleted when the garbage collection is processing. - * - * @covers ::process() - */ - public function test_event_can_be_processed() { - $monitor = new ValidatedUrlStylesheetDataGarbageCollection( new BackgroundTaskDeactivator() ); - - // Insert four weeks of validated URLs. - $post_ids = []; - for ( $days_ago = 1; $days_ago <= 28; $days_ago++ ) { - $post_date = gmdate( 'Y-m-d H:i:s', strtotime( "$days_ago days ago" ) + 2 ); - $post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [], - home_url( "/days-ago-$days_ago/" ), - [ 'stylesheets' => [ '/*...*/' ] ] - ); - wp_update_post( - [ - 'ID' => $post_id, - 'post_date_gmt' => $post_date, - 'post_date' => $post_date, - ] - ); - $post_ids[ $days_ago ] = $post_id; - } - - $monitor->process(); - - foreach ( $post_ids as $days_ago => $post_id ) { - if ( $days_ago > 7 ) { - $this->assertEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ), "Expected $days_ago days ago to be empty." ); - } else { - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ), "Expected $days_ago days ago to not be empty." ); - } - } - } -} diff --git a/tests/php/src/Validation/ScannableURLProviderTest.php b/tests/php/src/Validation/ScannableURLProviderTest.php deleted file mode 100644 index 94f3183068e..00000000000 --- a/tests/php/src/Validation/ScannableURLProviderTest.php +++ /dev/null @@ -1,530 +0,0 @@ -scannable_url_provider = new ScannableURLProvider( [], 20 ); - $this->add_validate_response_mocking_filter(); - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( ScannableURLProvider::class, $this->scannable_url_provider ); - } - - /** - * Test retrieval of urls. - * - * @covers ::get_urls() - * @covers ::get_supportable_templates() - * @covers ::is_template_supported() - * @covers ::get_posts_by_type() - */ - public function test_count_urls_to_validate_in_standard_mode() { - $user = self::factory()->user->create(); - self::factory()->post->create( [ 'post_author' => $user ] ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $number_original_urls = 6; - - $this->assertCount( $number_original_urls, $this->scannable_url_provider->get_urls() ); - - $this->scannable_url_provider = new ScannableURLProvider( [], 100 ); - - $category = self::factory()->term->create( [ 'taxonomy' => 'category' ] ); - $number_new_posts = 50; - $post_ids = []; - for ( $i = 0; $i < $number_new_posts; $i++ ) { - $post_ids[] = self::factory()->post->create( - [ - 'tax_input' => [ 'category' => $category ], - ] - ); - } - - $expected_url_count = $number_new_posts + $number_original_urls; - $this->assertCount( $expected_url_count, $this->scannable_url_provider->get_urls() ); - - $this->scannable_url_provider = new ScannableURLProvider( [], 100 ); - - $number_of_new_terms = 20; - $expected_url_count += $number_of_new_terms; - $taxonomy = 'category'; - $terms_for_current_taxonomy = []; - for ( $i = 0; $i < $number_of_new_terms; $i++ ) { - $terms_for_current_taxonomy[] = self::factory()->term->create( - [ - 'taxonomy' => $taxonomy, - ] - ); - } - - // Terms need to be associated with a post in order to be returned in get_terms(). - $result = wp_set_post_terms( - $post_ids[0], - $terms_for_current_taxonomy, - $taxonomy - ); - $this->assertFalse( is_wp_error( $result ) ); - - $this->assertCount( $expected_url_count, $this->scannable_url_provider->get_urls() ); - } - - /** - * Test retrieval of urls in legacy Reader mode. - * - * @covers ::get_urls() - * @covers ::get_supportable_templates() - * @covers ::is_template_supported() - * @covers ::get_posts_by_type() - */ - public function test_count_urls_to_validate_in_legacy_reader_mode() { - $this->scannable_url_provider->set_limit_per_type( 1 ); - - $user_id = self::factory()->user->create(); - $term_id = self::factory()->term->create( [ 'taxonomy' => 'category' ] ); - $post_id = self::factory()->post->create( - [ - 'post_type' => 'post', - 'post_author' => $user_id, - 'tax_input' => [ 'category' => $term_id ], - ] - ); - $page1_id = self::factory()->post->create( [ 'post_type' => 'page' ] ); - $page2_id = self::factory()->post->create( [ 'post_type' => 'page' ] ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::READER_THEME, ReaderThemes::DEFAULT_READER_THEME ); - $this->assertTrue( amp_is_legacy() ); - - // Test showing latest posts on front. - update_option( 'show_on_front', 'posts' ); - $this->assertEqualSets( - [ - get_permalink( $post_id ), - get_permalink( $page2_id ), - ], - wp_list_pluck( $this->scannable_url_provider->get_urls(), 'url' ) - ); - $this->assertEqualSets( - [ 'is_singular' ], - array_keys( - array_filter( - $this->scannable_url_provider->get_supportable_templates(), - static function ( $supportable_template ) { - return ! empty( $supportable_template['supported'] ); - } - ) - ) - ); - - // Test when there is a page_on_front and a page_on_front, but these pages do not have AMP enabled. - update_option( 'show_on_front', 'page' ); - update_option( 'page_on_front', $page1_id ); - update_option( 'page_for_posts', $page2_id ); - $this->assertFalse( amp_is_post_supported( $page1_id ) ); - $this->assertFalse( amp_is_post_supported( $page2_id ) ); - - $this->assertEqualSets( - [ - get_permalink( $post_id ), - ], - wp_list_pluck( $this->scannable_url_provider->get_urls(), 'url' ) - ); - $this->assertEqualSets( - [ 'is_singular' ], - array_keys( - array_filter( - $this->scannable_url_provider->get_supportable_templates(), - static function ( $supportable_template ) { - return ! empty( $supportable_template['supported'] ); - } - ) - ) - ); - - // Enable AMP for both page_on_front and page_on_front. - update_post_meta( $page1_id, AMP_Post_Meta_Box::STATUS_POST_META_KEY, AMP_Post_Meta_Box::ENABLED_STATUS ); - update_post_meta( $page2_id, AMP_Post_Meta_Box::STATUS_POST_META_KEY, AMP_Post_Meta_Box::ENABLED_STATUS ); - $this->assertTrue( amp_is_post_supported( $page1_id ) ); - $this->assertTrue( amp_is_post_supported( $page2_id ) ); - $this->assertEqualSets( - array_unique( - [ - get_permalink( $post_id ), - get_permalink( $page1_id ), - get_permalink( $page2_id ), - home_url( '/' ), // Same as $page1_id since page_on_front. - ] - ), - wp_list_pluck( $this->scannable_url_provider->get_urls(), 'url' ) - ); - $this->assertEqualSets( - [ 'is_singular', 'is_home', 'is_front_page' ], - array_keys( - array_filter( - $this->scannable_url_provider->get_supportable_templates(), - static function ( $supportable_template ) { - return ! empty( $supportable_template['supported'] ); - } - ) - ) - ); - } - - /** - * Test get_posts_that_support_amp. - * - * @covers ::get_posts_that_support_amp() - */ - public function test_get_posts_that_support_amp() { - $number_of_posts = 20; - $ids = []; - for ( $i = 0; $i < $number_of_posts; $i++ ) { - $ids[] = self::factory()->post->create(); - } - - // This should count all of the newly-created posts as supporting AMP. - $this->assertEquals( $ids, $this->call_private_method( $this->scannable_url_provider, 'get_posts_that_support_amp', [ $ids ] ) ); - - // Simulate 'Enable AMP' being unchecked in the post editor, in which case get_url_count() should not count it. - $first_id = $ids[0]; - update_post_meta( - $first_id, - AMP_Post_Meta_Box::STATUS_POST_META_KEY, - AMP_Post_Meta_Box::DISABLED_STATUS - ); - $this->assertEquals( [], $this->call_private_method( $this->scannable_url_provider, 'get_posts_that_support_amp', [ [ $first_id ] ] ) ); - - update_post_meta( - $first_id, - AMP_Post_Meta_Box::STATUS_POST_META_KEY, - AMP_Post_Meta_Box::ENABLED_STATUS - ); - - $this->scannable_url_provider = new ScannableURLProvider( [], 20 ); - - // In AMP-first, the IDs should include all of the newly-created posts. - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->assertEquals( $ids, $this->call_private_method( $this->scannable_url_provider, 'get_posts_that_support_amp', [ $ids ] ) ); - - // In Transitional Mode, the IDs should also include all of the newly-created posts. - add_theme_support( - AMP_Theme_Support::SLUG, - [ - AMP_Theme_Support::PAIRED_FLAG => true, - ] - ); - $this->assertEquals( $ids, $this->call_private_method( $this->scannable_url_provider, 'get_posts_that_support_amp', [ $ids ] ) ); - } - - /** - * Test get_author_page_urls. - * - * @covers ::get_author_page_urls() - */ - public function test_get_author_page_urls() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - - self::factory()->user->create(); - $users = get_users(); - $first_author = $users[0]; - $first_author_url = get_author_posts_url( $first_author->ID, $first_author->user_nicename ); - $second_author = $users[1]; - $second_author_url = get_author_posts_url( $second_author->ID, $second_author->user_nicename ); - - $actual_urls = $this->call_private_method( $this->scannable_url_provider, 'get_author_page_urls', [ 0, 1 ] ); - $this->assertCount( 0, $actual_urls ); - - self::factory()->post->create( [ 'post_author' => $first_author->ID ] ); - self::factory()->post->create( [ 'post_author' => $second_author->ID ] ); - $actual_urls = $this->call_private_method( $this->scannable_url_provider, 'get_author_page_urls', [ 0, 1 ] ); - - // Passing 0 as the offset argument should get the first author. - $this->assertEquals( [ $first_author_url ], $actual_urls ); - - $actual_urls = $this->call_private_method( $this->scannable_url_provider, 'get_author_page_urls', [ 1, 1 ] ); - - // Passing 1 as the offset argument should get the second author. - $this->assertEquals( [ $second_author_url ], $actual_urls ); - - // If $include_conditionals is set and does not have is_author, this should not return a URL. - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_category' ], 20 ); - $this->assertEquals( [], $this->call_private_method( $this->scannable_url_provider, 'get_author_page_urls', [ 1, 0 ] ) ); - - // If $include_conditionals is set and has is_author, this should return URLs. - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_author' ], 20 ); - $this->assertEquals( - [ $first_author_url, $second_author_url ], - $this->call_private_method( $this->scannable_url_provider, 'get_author_page_urls', [ 2, 0 ] ) - ); - } - - /** - * Test does_taxonomy_support_amp. - * - * @covers ::does_taxonomy_support_amp() - */ - public function test_does_taxonomy_support_amp() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - - $custom_taxonomy = 'foo_custom_taxonomy'; - register_taxonomy( $custom_taxonomy, 'post' ); - $taxonomies_to_test = [ $custom_taxonomy, 'category', 'post_tag' ]; - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, [ 'is_category', 'is_tag', sprintf( 'is_tax[%s]', $custom_taxonomy ) ] ); - - // When these templates are not unchecked in the 'AMP Settings' UI, these should be supported. - foreach ( $taxonomies_to_test as $taxonomy ) { - $this->assertTrue( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ $taxonomy ] ) ); - } - - // When the user has not checked the boxes for 'Categories' and 'Tags,' this should be false. - $this->scannable_url_provider = new ScannableURLProvider( [], 20 ); - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, [ 'is_author' ] ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - foreach ( $taxonomies_to_test as $taxonomy ) { - $this->assertFalse( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ $taxonomy ] ) ); - } - - $this->scannable_url_provider = new ScannableURLProvider( [], 20 ); - - // When the user has checked the Option::ALL_TEMPLATES_SUPPORTED box, this should always be true. - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, true ); - foreach ( $taxonomies_to_test as $taxonomy ) { - $this->assertTrue( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ $taxonomy ] ) ); - } - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - - /* - * If the user passed allowed conditionals to the WP-CLI command like wp amp validate-site --include=is_category,is_tag - * these should be supported taxonomies. - */ - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, true ); - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_category', 'is_tag' ], 20 ); - $this->assertTrue( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ 'category' ] ) ); - $this->assertTrue( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ 'tag' ] ) ); - $this->assertFalse( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ 'author' ] ) ); - $this->assertFalse( $this->call_private_method( $this->scannable_url_provider, 'does_taxonomy_support_amp', [ 'search' ] ) ); - } - - /** - * Test is_template_supported. - * - * @covers ::is_template_supported() - */ - public function test_is_template_supported() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - - $author_conditional = 'is_author'; - $search_conditional = 'is_search'; - - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, [ $author_conditional ] ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - $this->scannable_url_provider = new ScannableURLProvider( [], 20 ); - $this->assertTrue( $this->call_private_method( $this->scannable_url_provider, 'is_template_supported', [ $author_conditional ] ) ); - $this->assertFalse( $this->call_private_method( $this->scannable_url_provider, 'is_template_supported', [ $search_conditional ] ) ); - - AMP_Options_Manager::update_option( Option::SUPPORTED_TEMPLATES, [ $search_conditional ] ); - $this->scannable_url_provider = new ScannableURLProvider( [], 20 ); - $this->assertTrue( $this->call_private_method( $this->scannable_url_provider, 'is_template_supported', [ $search_conditional ] ) ); - $this->assertFalse( $this->call_private_method( $this->scannable_url_provider, 'is_template_supported', [ $author_conditional ] ) ); - } - - /** - * Test get_posts_by_type. - * - * @covers ::get_posts_by_type() - */ - public function test_get_posts_by_type() { - $number_posts_each_post_type = 20; - $post_types = get_post_types( [ 'public' => true ], 'names' ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, true ); - AMP_Options_Manager::update_option( Option::SUPPORTED_POST_TYPES, $post_types ); - - foreach ( $post_types as $post_type ) { - // Start the expected posts with the existing post(s). - $query = new WP_Query( - [ - 'fields' => 'ids', - 'post_type' => $post_type, - ] - ); - $expected_posts = $query->posts; - - for ( $i = 0; $i < $number_posts_each_post_type; $i++ ) { - array_unshift( - $expected_posts, - self::factory()->post->create( - [ - 'post_type' => $post_type, - ] - ) - ); - } - - $actual_posts = $this->call_private_method( $this->scannable_url_provider, 'get_posts_by_type', [ $post_type ] ); - $this->assertEquals( $expected_posts, array_values( $actual_posts ) ); - - // Test with the $offset and $number arguments. - $offset = 0; - $actual_posts = $this->call_private_method( $this->scannable_url_provider, 'get_posts_by_type', [ $post_type, $offset, $number_posts_each_post_type ] ); - $this->assertEquals( array_slice( $expected_posts, $offset, $number_posts_each_post_type ), $actual_posts ); - } - } - - /** - * Test get_taxonomy_links. - * - * @covers ::get_taxonomy_links() - */ - public function test_get_taxonomy_links() { - $number_links_each_taxonomy = 20; - $taxonomies = get_taxonomies( - [ - 'public' => true, - ] - ); - - foreach ( $taxonomies as $taxonomy ) { - // Begin the expected links with the term links that already exist. - $expected_links = array_map( 'get_term_link', get_terms( [ 'taxonomy' => $taxonomy ] ) ); - $terms_for_current_taxonomy = []; - for ( $i = 0; $i < $number_links_each_taxonomy; $i++ ) { - $terms_for_current_taxonomy[] = self::factory()->term->create( - [ - 'taxonomy' => $taxonomy, - ] - ); - } - - // Terms need to be associated with a post in order to be returned in get_terms(). - $result = wp_set_post_terms( - self::factory()->post->create(), - $terms_for_current_taxonomy, - $taxonomy - ); - $this->assertFalse( is_wp_error( $result ) ); - - $expected_links = array_merge( - $expected_links, - array_map( 'get_term_link', $terms_for_current_taxonomy ) - ); - $number_of_links = 100; - $actual_links = $this->call_private_method( $this->scannable_url_provider, 'get_taxonomy_links', [ $taxonomy, 0, $number_of_links ] ); - - // The get_terms() call in get_taxonomy_links() returns an array with a first index of 1, so correct for that with array_values(). - $this->assertEquals( $expected_links, array_values( $actual_links ) ); - $this->assertLessThan( $number_of_links, count( $actual_links ) ); - - $number_of_links = 5; - $offset = 10; - $actual_links_using_offset = $this->call_private_method( $this->scannable_url_provider, 'get_taxonomy_links', [ $taxonomy, $offset, $number_of_links ] ); - $this->assertEquals( array_slice( $expected_links, $offset, $number_of_links ), array_values( $actual_links_using_offset ) ); - $this->assertEquals( $number_of_links, count( $actual_links_using_offset ) ); - } - } - - /** - * Test get_search_page. - * - * @covers ::get_search_page() - */ - public function test_get_search_page() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - - // Normally, this should return a string, unless the user has opted out of the search template. - $this->assertTrue( is_string( $this->call_private_method( $this->scannable_url_provider, 'get_search_page' ) ) ); - - // If $include_conditionals is set and does not have is_search, this should not return a URL. - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_author' ], 20 ); - $this->assertEquals( null, $this->call_private_method( $this->scannable_url_provider, 'get_search_page' ) ); - - // If $include_conditionals has is_search, this should return a URL. - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_search' ], 20 ); - $this->assertTrue( is_string( $this->call_private_method( $this->scannable_url_provider, 'get_search_page' ) ) ); - } - - /** - * Test get_date_page. - * - * @covers ::get_date_page() - */ - public function test_get_date_page() { - $this->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' ); - - $post = self::factory()->post->create(); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->scannable_url_provider = new ScannableURLProvider( [], 20 ); - - $year = get_the_date( 'Y', $post ); - - // Normally, this should return the date page, unless the user has opted out of that template. - $url = $this->call_private_method( $this->scannable_url_provider, 'get_date_page' ); - $this->assertIsString( $url ); - $this->assertStringContainsString( get_year_link( $year ), $url ); - - // If $include_conditionals is set and does not have is_date, this should not return a URL. - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_search' ], 20 ); - $this->assertEquals( null, $this->call_private_method( $this->scannable_url_provider, 'get_date_page' ) ); - - // If $include_conditionals has is_date, this should return a URL. - $this->scannable_url_provider = new ScannableURLProvider( [ 'is_date' ], 20 ); - $this->assertStringContainsString( get_year_link( $year ), $this->call_private_method( $this->scannable_url_provider, 'get_date_page' ) ); - - // If all posts are deleted, then nothing should be returned. - $query = new WP_Query( - [ - 'post_type' => 'post', - 'posts_per_page' => -1, - 'fields' => 'ids', - ] - ); - foreach ( $query->get_posts() as $deleted_post ) { - wp_delete_post( $deleted_post ); - } - $this->assertNull( $this->call_private_method( $this->scannable_url_provider, 'get_date_page' ) ); - - // Same goes if there is only one post and it lacks a year. - $timeless_post = self::factory()->post->create(); - global $wpdb; - $wpdb->update( - $wpdb->posts, - [ - 'post_date' => '0000-00-00 00:00:00', - 'post_date_gmt' => '0000-00-00 00:00:00', - ], - [ 'ID' => $timeless_post ] - ); - clean_post_cache( $timeless_post ); - $this->assertNull( $this->call_private_method( $this->scannable_url_provider, 'get_date_page' ) ); - } -} diff --git a/tests/php/src/Validation/ScannableURLsRestControllerTest.php b/tests/php/src/Validation/ScannableURLsRestControllerTest.php deleted file mode 100644 index b591eb3cc99..00000000000 --- a/tests/php/src/Validation/ScannableURLsRestControllerTest.php +++ /dev/null @@ -1,195 +0,0 @@ -controller = $this->injector->make( ScannableURLsRestController::class ); - $this->add_validate_response_mocking_filter(); - } - - /** @covers ::get_registration_action() */ - public function test_get_registration_action() { - $this->assertEquals( 'rest_api_init', ScannableURLsRestController::get_registration_action() ); - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( Delayed::class, $this->controller ); - $this->assertInstanceOf( ScannableURLsRestController::class, $this->controller ); - $this->assertInstanceOf( WP_REST_Controller::class, $this->controller ); - } - - /** @covers ::register() */ - public function test_register() { - $this->controller->register(); - - $this->assertContains( '/amp/v1/scannable-urls', array_keys( rest_get_server()->get_routes() ) ); - } - - /** @covers ::get_items_permissions_check() */ - public function test_get_items_permissions_check() { - $this->assertWPError( $this->controller->get_items_permissions_check( new WP_REST_Request( 'GET', '/amp/v1/scannable-urls/' ) ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->assertTrue( $this->controller->get_items_permissions_check( new WP_REST_Request( 'GET', '/amp/v1/scannable-urls/' ) ) ); - } - - /** - * @covers ::get_items() - * @covers ::prepare_item_for_response() - * @covers ::get_item_schema() - */ - public function test_get_items() { - $this->assertTrue( amp_is_legacy() ); - $post_id = self::factory()->post->create( [ 'post_type' => 'post' ] ); - $page_id = self::factory()->post->create( [ 'post_type' => 'page' ] ); - AMP_Validation_Manager::validate_url_and_store( get_permalink( $post_id ) ); - - $this->controller->register(); - $item_schema = $this->controller->get_item_schema(); - - $request = new WP_REST_Request( 'GET', '/amp/v1/scannable-urls' ); - - wp_set_current_user( 0 ); - $response = rest_get_server()->dispatch( $request ); - $this->assertTrue( $response->is_error() ); - $error = $response->as_error(); - $this->assertEquals( 'amp_rest_cannot_validate_urls', $error->get_error_code() ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'subscriber' ] ) ); - $response = rest_get_server()->dispatch( $request ); - $this->assertTrue( $response->is_error() ); - $error = $response->as_error(); - $this->assertEquals( 'amp_rest_cannot_validate_urls', $error->get_error_code() ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $response = rest_get_server()->dispatch( $request ); - $this->assertFalse( $response->is_error() ); - $scannable_urls = $response->get_data(); - $this->assertCount( 2, $scannable_urls, 'Expected there to be only two URLs since in legacy Reader mode.' ); - - foreach ( $scannable_urls as $scannable_url_entry ) { - $this->assertEqualSets( - array_keys( $item_schema['properties'] ), - array_keys( $scannable_url_entry ) - ); - - $this->assertContains( - $scannable_url_entry['url'], - [ get_permalink( $post_id ), get_permalink( $page_id ) ] - ); - $this->assertContains( - $scannable_url_entry['amp_url'], - [ amp_get_permalink( $post_id ), amp_get_permalink( $page_id ) ] - ); - - if ( get_permalink( $post_id ) === $scannable_url_entry['url'] ) { - $this->assertIsArray( $scannable_url_entry['validated_url_post'] ); - - $this->assertEqualSets( - [ 'id', 'edit_link' ], - array_keys( $scannable_url_entry['validated_url_post'] ) - ); - $validated_url_post = get_post( $scannable_url_entry['validated_url_post']['id'] ); - $this->assertInstanceOf( WP_Post::class, $validated_url_post ); - $this->assertEquals( - get_edit_post_link( $validated_url_post, 'raw' ), - $scannable_url_entry['validated_url_post']['edit_link'] - ); - - $this->assertIsArray( $scannable_url_entry['validation_errors'] ); - $this->assertCount( 1, $scannable_url_entry['validation_errors'] ); - - $this->assertFalse( $scannable_url_entry['stale'] ); - } else { - $this->assertNull( $scannable_url_entry['validated_url_post'] ); - $this->assertNull( $scannable_url_entry['validation_errors'] ); - $this->assertNull( $scannable_url_entry['stale'] ); - } - } - - // Test `force_standard_mode` query parameter. - AMP_Options_Manager::update_options( - [ - Option::ALL_TEMPLATES_SUPPORTED => false, - Option::SUPPORTED_TEMPLATES => [ 'is_singular' ], - ] - ); - $request_with_forced_standard_mode = new WP_REST_Request( 'GET', '/amp/v1/scannable-urls' ); - $request_with_forced_standard_mode->set_param( ScannableURLsRestController::FORCE_STANDARD_MODE, 'true' ); - $response_with_forced_standard_mode = rest_get_server()->dispatch( $request_with_forced_standard_mode ); - - $this->assertFalse( $response_with_forced_standard_mode->is_error() ); - $scannable_urls_in_standard_mode = $response_with_forced_standard_mode->get_data(); - $this->assertGreaterThan( 2, count( $scannable_urls_in_standard_mode ), 'Expected more than two URLs since in Standard mode.' ); - } - - /** - * Tests ScannableURLsRestController::get_item_schema. - * - * @covers ::get_item_schema() - */ - public function test_get_item_schema() { - $schema = $this->controller->get_item_schema(); - - $this->assertEquals( - [ - '$schema', - 'title', - 'type', - 'properties', - ], - array_keys( $schema ) - ); - - $this->assertEqualSets( - [ - 'url', - 'amp_url', - 'type', - 'label', - 'validated_url_post', - 'validation_errors', - 'stale', - ], - array_keys( $schema['properties'] ) - ); - } -} diff --git a/tests/php/src/Validation/URLValidationCronTest.php b/tests/php/src/Validation/URLValidationCronTest.php deleted file mode 100644 index 0a70abecc2c..00000000000 --- a/tests/php/src/Validation/URLValidationCronTest.php +++ /dev/null @@ -1,219 +0,0 @@ -test_instance = $this->injector->make( URLValidationCron::class ); - add_filter( - 'pre_http_request', - function ( $pre ) { - $this->request_count++; - return $pre; - } - ); - - $this->add_validate_response_mocking_filter(); - } - - /** - * @covers ::register() - * @covers ::get_event_name() - */ - public function test_register() { - $this->assertInstanceof( CronBasedBackgroundTask::class, $this->test_instance ); - $this->assertInstanceof( URLValidationCron::class, $this->test_instance ); - $this->assertInstanceof( Service::class, $this->test_instance ); - $this->assertInstanceof( Registerable::class, $this->test_instance ); - - $this->test_instance->register(); - - $this->assertEquals( 10, has_action( 'admin_init', [ $this->test_instance, 'schedule_event' ] ) ); - $this->assertEquals( 10, has_action( URLValidationCron::BACKGROUND_TASK_NAME, [ $this->test_instance, 'process' ] ) ); - } - - /** @covers ::schedule_event() */ - public function test_schedule_event_with_no_user() { - $event_name = $this->call_private_method( $this->test_instance, 'get_event_name' ); - - // No logged-in user. - $this->test_instance->schedule_event(); - - $this->assertFalse( wp_next_scheduled( $event_name ) ); - } - - /** @covers ::schedule_event() */ - public function test_schedule_event_with_user_without_permission() { - $event_name = $this->call_private_method( $this->test_instance, 'get_event_name' ); - - $this->assertFalse( wp_next_scheduled( $event_name ) ); - - wp_set_current_user( $this->factory()->user->create( [ 'role' => 'subscriber' ] ) ); - - $this->test_instance->schedule_event(); - - $this->assertTrue( is_numeric( wp_next_scheduled( $event_name ) ) ); - } - - /** @covers ::schedule_event() */ - public function test_schedule_event_with_user_with_permission() { - $event_name = $this->call_private_method( $this->test_instance, 'get_event_name' ); - - wp_set_current_user( $this->factory()->user->create( [ 'role' => 'administrator' ] ) ); - - $this->test_instance->schedule_event(); - - $this->assertNotFalse( wp_next_scheduled( $event_name ) ); - } - - /** @covers ::schedule_event() */ - public function test_schedule_event_with_different_recurrence() { - wp_set_current_user( $this->factory()->user->create( [ 'role' => 'administrator' ] ) ); - $event_name = $this->call_private_method( $this->test_instance, 'get_event_name' ); - $args = []; - $old_interval = 'daily'; - $interval = $this->call_private_method( $this->test_instance, 'get_interval' ); - - $this->assertFalse( wp_next_scheduled( $event_name, $args ) ); - - $count_events = static function ( $hook ) { - $count = 0; - foreach ( _get_cron_array() as $cron ) { - if ( isset( $cron[ $hook ] ) ) { - $count += count( $cron[ $hook ] ); - } - } - return $count; - }; - $this->assertEquals( 0, $count_events( $event_name ) ); - - // First schedule with an old interval. - $this->assertNotEquals( $old_interval, $interval ); - $old_time = time() + HOUR_IN_SECONDS; - $success = wp_schedule_event( $old_time, $old_interval, $event_name, $args ); - if ( version_compare( get_bloginfo( 'version' ), '5.1', '>=' ) ) { - $this->assertTrue( $success ); - } - $this->assertEquals( $old_time, wp_next_scheduled( $event_name, $args ) ); - $this->assertEquals( 1, $count_events( $event_name ) ); - - // Now try scheduling with the new interval. - $this->test_instance->schedule_event(); - $event = $this->test_instance->get_scheduled_event( $event_name, $args ); - $this->assertIsObject( $event ); - - $this->assertEquals( 1, $count_events( $event_name ) ); - $this->assertNotEquals( $old_time, $event->timestamp, 'Expected old event to no longer be scheduled at the old time.' ); - $this->assertLessThanOrEqual( time(), $event->timestamp ); - $this->assertEquals( $interval, $event->schedule, 'Expected event to have the new interval.' ); - } - - /** - * Test validate_urls. - * - * @covers ::process() - * @covers ::dequeue() - */ - public function test_process_and_dequeue() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - - /** @var ScannableURLProvider $scannable_url_provider */ - $scannable_url_provider = $this->get_private_property( $this->test_instance, 'scannable_url_provider' ); - - self::factory()->post->create(); - $initial_urls = wp_list_pluck( $scannable_url_provider->get_urls(), 'url' ); - $initial_url_count = count( $initial_urls ); - $this->assertGreaterThan( 0, $initial_url_count ); - - update_option( URLValidationCron::OPTION_KEY, '' ); - - // Verify that processing will enqueue URLs (if none are queued) and process one. - for ( $i = 1; $i <= $initial_url_count; $i++ ) { - $this->test_instance->process(); - $this->assertEquals( $i, $this->request_count ); - $data = get_option( URLValidationCron::OPTION_KEY ); - $this->assertArrayHasKey( 'urls', $data ); - $this->assertArrayHasKey( 'timestamp', $data ); - $this->assertLessThanOrEqual( time(), $data['timestamp'] ); - $this->assertEquals( - array_slice( $initial_urls, $i ), - $data['urls'] - ); - } - - // Ensure no URLs are queued or processed if timestamp is less than a week. - $data = get_option( URLValidationCron::OPTION_KEY ); - $this->assertCount( 0, $data['urls'] ); - $before_request_count = $this->request_count; - $this->test_instance->process(); - $this->assertEquals( $before_request_count, $this->request_count ); - $data = get_option( URLValidationCron::OPTION_KEY ); - $this->assertCount( 0, $data['urls'] ); - - // Now test that after a week has transpired, the next set of URLs are re-queued and one is processed. - $data['timestamp'] = time() - WEEK_IN_SECONDS - MINUTE_IN_SECONDS; - update_option( URLValidationCron::OPTION_KEY, $data ); - $this->test_instance->process(); - $this->assertEquals( $before_request_count + 1, $this->request_count ); - $data = get_option( URLValidationCron::OPTION_KEY ); - $this->assertCount( $initial_url_count - 1, $data['urls'] ); - - $this->test_instance->process(); - $this->assertEquals( $before_request_count + 2, $this->request_count ); - $data = get_option( URLValidationCron::OPTION_KEY ); - $this->assertCount( $initial_url_count - 2, $data['urls'] ); - - // Now test once the validated environment has changed, that the URLs are re-queued. - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $this->test_instance->process(); - $data = get_option( URLValidationCron::OPTION_KEY ); - $this->assertCount( $initial_url_count - 1, $data['urls'] ); - } - - /** @covers ::get_event_name() */ - public function test_get_event_name() { - $this->assertEquals( - URLValidationCron::BACKGROUND_TASK_NAME, - $this->call_private_method( $this->test_instance, 'get_event_name' ) - ); - } - - /** @covers ::get_interval() */ - public function test_get_interval() { - $this->assertEquals( - URLValidationCron::DEFAULT_INTERVAL_HOURLY, - $this->call_private_method( $this->test_instance, 'get_interval' ) - ); - } -} diff --git a/tests/php/src/Validation/URLValidationProviderTest.php b/tests/php/src/Validation/URLValidationProviderTest.php deleted file mode 100644 index d8d6621fb43..00000000000 --- a/tests/php/src/Validation/URLValidationProviderTest.php +++ /dev/null @@ -1,66 +0,0 @@ -url_validation_provider = new URLValidationProvider(); - $this->add_validate_response_mocking_filter(); - } - - /** - * Test get_url_validation. - * - * @covers ::get_url_validation() - * @covers ::get_total_errors() - * @covers ::get_unaccepted_errors() - * @covers ::update_state_from_validity() - */ - public function test_get_url_validation() { - $single_post_permalink = get_permalink( self::factory()->post->create() ); - $this->url_validation_provider->get_url_validation( $single_post_permalink, 'post' ); - $this->assertContains( $single_post_permalink, $this->get_validated_urls() ); - - $number_of_posts = 30; - $post_permalinks = []; - - for ( $i = 0; $i < $number_of_posts; $i++ ) { - $permalink = get_permalink( self::factory()->post->create() ); - $post_permalinks[] = $permalink; - $validity = $this->url_validation_provider->get_url_validation( $permalink, 'post' ); - $this->assertIsArray( $validity ); - } - - // All of the posts created should be present in the validated URLs. - $this->assertEmpty( array_diff( $post_permalinks, $this->get_validated_urls() ) ); - - $this->assertEquals( 31, $this->url_validation_provider->get_total_errors() ); - $this->assertEmpty( $this->url_validation_provider->get_unaccepted_errors() ); - $this->assertEquals( 31, $this->url_validation_provider->get_number_validated() ); - - $this->assertEquals( - [ 'post' ], - array_keys( $this->url_validation_provider->get_validity_by_type() ) - ); - } -} diff --git a/tests/php/src/Validation/URLValidationRESTControllerTest.php b/tests/php/src/Validation/URLValidationRESTControllerTest.php deleted file mode 100644 index 14d099a4924..00000000000 --- a/tests/php/src/Validation/URLValidationRESTControllerTest.php +++ /dev/null @@ -1,268 +0,0 @@ -user_access = $this->injector->make( UserAccess::class ); - $this->controller = $this->injector->make( URLValidationRESTController::class ); - $this->add_validate_response_mocking_filter(); - } - - /** @covers ::get_registration_action() */ - public function test_get_registration_action() { - $this->assertEquals( 'rest_api_init', URLValidationRESTController::get_registration_action() ); - } - - /** @covers ::__construct() */ - public function test__construct() { - $this->assertInstanceOf( URLValidationRESTController::class, $this->controller ); - $this->assertInstanceOf( WP_REST_Controller::class, $this->controller ); - } - - /** @covers ::register() */ - public function test_register() { - $this->controller->register(); - - $this->assertContains( '/amp/v1/validate-post-url', array_keys( rest_get_server()->get_routes() ) ); - } - - /** @covers ::create_item_permissions_check() */ - public function test_create_item_permissions_check() { - $this->assertWPError( $this->controller->create_item_permissions_check( new WP_REST_Request( 'POST', '/amp/v1/validate-post-url/' ) ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'author' ] ) ); - $this->assertWPError( $this->controller->create_item_permissions_check( new WP_REST_Request( 'POST', '/amp/v1/validate-post-url/' ) ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->user_access->set_user_enabled( wp_get_current_user(), true ); - $value = $this->controller->create_item_permissions_check( new WP_REST_Request( 'POST', '/amp/v1/validate-post-url/' ) ); - if ( ( new DependencySupport() )->has_support() ) { - $this->assertTrue( $value ); - } else { - $this->assertWPError( $value ); - } - } - - /** @covers ::is_valid_preview_nonce() */ - public function test_is_valid_preview_nonce() { - $user_id = self::factory()->user->create( [ 'role' => 'author' ] ); - $post_id = self::factory()->post->create( [ 'post_author' => $user_id ] ); - wp_set_current_user( $user_id ); - - $this->assertFalse( $this->controller->is_valid_preview_nonce( 'bad', 1 ) ); - $this->assertFalse( $this->controller->is_valid_preview_nonce( 'bad', $post_id ) ); - $this->assertFalse( $this->controller->is_valid_preview_nonce( wp_create_nonce( 'post_preview_' . ( $post_id + 1 ) ), $post_id ) ); - $this->assertTrue( $this->controller->is_valid_preview_nonce( wp_create_nonce( 'post_preview_' . $post_id ), $post_id ) ); - } - - /** @return array */ - public function get_data_for_test_validate_post_url() { - return [ - 'not_int' => [ - [ 'id' => 'foo' ], - null, - 'administrator', - 'rest_invalid_param', - ], - - 'too_small' => [ - [ 'id' => - 1 ], - null, - 'administrator', - 'rest_invalid_param', - ], - - 'empty_post' => [ - [ 'id' => 0 ], - null, - 'administrator', - 'rest_invalid_param', - ], - - 'revision_id' => [ - [ 'id' => '{{id}}' ], - 'revision', - 'administrator', - 'rest_invalid_param', - ], - - 'as_author' => [ - [ 'id' => '{{id}}' ], - 'post', - 'author', - 'amp_rest_no_dev_tools', - ], - - 'bad_preview1' => [ - [ - 'id' => '{{id}}', - 'preview_nonce' => 'bad!!', - ], - 'post', - 'administrator', - ( new DependencySupport() )->has_support() - ? ( version_compare( get_bloginfo( 'version' ), '5.2', '<' ) ? 'amp_post_preview_denied' : 'rest_invalid_param' ) - : 'amp_rest_no_dev_tools', - ], - - 'bad_preview2' => [ - [ - 'id' => '{{id}}', - 'preview_nonce' => wp_create_nonce( 'bad' ), - ], - 'post', - 'administrator', - ( new DependencySupport() )->has_support() ? 'amp_post_preview_denied' : 'amp_rest_no_dev_tools', - ], - - 'post_id' => [ - [ 'id' => '{{id}}' ], - 'post', - 'administrator', - true, - ], - - 'good_preview' => [ - [ - 'id' => '{{id}}', - 'preview_nonce' => '{{preview_nonce}}', - ], - 'post', - 'administrator', - true, - ], - ]; - } - - /** - * @dataProvider get_data_for_test_validate_post_url() - * @covers ::validate_post_url() - * @covers ::validate_post_id_param() - * @param array $params Params (template). - * @param string|null $post_type Post type. - * @param string $user_role User role. - * @param true|string $expected_validity Expected validity. - */ - public function test_validate_post_url( $params, $post_type, $user_role, $expected_validity ) { - add_filter( 'amp_dev_tools_user_default_enabled', '__return_true' ); - $user_id = self::factory()->user->create( [ 'role' => $user_role ] ); - - wp_set_current_user( $user_id ); - - if ( isset( $params['id'] ) && '{{id}}' === $params['id'] && $post_type ) { - $params['id'] = self::factory()->post->create( compact( 'post_type' ) ); - } - - if ( isset( $params['id'], $params['preview_nonce'] ) && '{{preview_nonce}}' === $params['preview_nonce'] ) { - $params['preview_nonce'] = wp_create_nonce( 'post_preview_' . $params['id'] ); - } - - $this->controller->register(); - $request = new WP_REST_Request( 'POST', '/amp/v1/validate-post-url' ); - $request->set_body_params( $params ); - $response = rest_get_server()->dispatch( $request ); - - if ( ! ( new DependencySupport() )->has_support() && true === $expected_validity ) { - $this->assertTrue( $response->is_error() ); - $error = $response->as_error(); - $this->assertEquals( 'amp_rest_no_dev_tools', $error->get_error_code() ); - } elseif ( true === $expected_validity ) { - $this->assertFalse( $response->is_error() ); - $data = $response->get_data(); - - $this->assertEquals( - [ - 'results', - 'review_link', - 'support_link', - ], - array_keys( $data ) - ); - - $this->assertNotEmpty( $data['review_link'] ); - $this->assertEquals( 1, count( $data['results'] ) ); - foreach ( $data['results'] as $result ) { - $this->assertArrayHasKey( 'error', $result ); - $this->assertArrayHasKey( 'sources', $result['error'] ); - $this->assertArrayHasKey( 'status', $result ); - $this->assertArrayHasKey( 'term_id', $result ); - $this->assertArrayHasKey( 'title', $result ); - } - } else { - $this->assertTrue( $response->is_error() ); - $error = $response->as_error(); - $this->assertEquals( $expected_validity, $error->get_error_code() ); - } - } - - /** - * Tests URLValidationRESTController::get_item_schema. - * - * @covers ::get_item_schema() - */ - public function test_get_item_schema() { - $schema = $this->controller->get_item_schema(); - - $this->assertEquals( - [ - '$schema', - 'title', - 'type', - 'properties', - ], - array_keys( $schema ) - ); - - $this->assertEquals( - [ - 'results', - 'review_link', - 'support_link', - ], - array_keys( $schema['properties'] ) - ); - } -} diff --git a/tests/php/src/Validation/ValidationCountsRestControllerTest.php b/tests/php/src/Validation/ValidationCountsRestControllerTest.php deleted file mode 100644 index d934fd6f00d..00000000000 --- a/tests/php/src/Validation/ValidationCountsRestControllerTest.php +++ /dev/null @@ -1,177 +0,0 @@ -controller = $this->injector->make( ValidationCountsRestController::class ); - } - - /** - * Test ::get_registration_action(). - * - * @covers ::get_registration_action() - */ - public function test_get_registration_action() { - self::assertEquals( 'rest_api_init', ValidationCountsRestController::get_registration_action() ); - } - - /** - * Test ::get_items_permissions_check(). - * - * @covers ::get_items_permissions_check() - */ - public function test_get_items_permissions_check() { - $admin_user = self::factory()->user->create_and_get( [ 'role' => 'administrator' ] ); - - $this->assertWPError( $this->controller->get_items_permissions_check( new WP_REST_Request( 'GET', '/amp/v1/unreviewed-validation-counts' ) ) ); - - wp_set_current_user( $admin_user->ID ); - $this->assertWPError( $this->controller->get_items_permissions_check( new WP_REST_Request( 'GET', '/amp/v1/unreviewed-validation-counts' ) ) ); - - update_user_meta( $admin_user->ID, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, wp_json_encode( true ) ); - $value = $this->controller->get_items_permissions_check( new WP_REST_Request( 'GET', '/amp/v1/unreviewed-validation-counts' ) ); - if ( ( new DependencySupport() )->has_support() ) { - $this->assertTrue( $value ); - } else { - $this->assertWPError( $value ); - } - } - - /** - * Test ::get_items(). - * - * @covers ::get_items() - * @covers AMP_Validated_URL_Post_Type::get_validation_error_urls_count() - */ - public function test_get_items() { - $admin_user = self::factory()->user->create_and_get( [ 'role' => 'administrator' ] ); - wp_set_current_user( $admin_user->ID ); - update_user_meta( $admin_user->ID, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, wp_json_encode( true ) ); - - $request = new WP_REST_Request( 'GET', '/amp/v1/unreviewed-validation-counts' ); - - $response = rest_get_server()->dispatch( $request ); - - if ( ! ( new DependencySupport() )->has_support() ) { - $this->assertWPError( $response->as_error() ); - return; - } - - $this->assertEquals( - [ - 'validated_urls' => 0, - 'errors' => 0, - ], - $response->get_data() - ); - - add_filter( - 'amp_validation_error_sanitized', - function ( $removed, $data ) { - if ( 'reviewed' === $data['code'] ) { - $removed = true; - } - return $removed; - }, - 10, - 2 - ); - - // One URL with one unreviewed error. - AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ - 'code' => 'foobar', - ], - ], - get_permalink( self::factory()->post->create() ) - ); - $response = rest_get_server()->dispatch( $request ); - $this->assertEquals( - [ - 'validated_urls' => 1, - 'errors' => 1, - ], - $response->get_data() - ); - - // Two URLs one with an unreviewed error, and another with an unreviewed error and a reviewed one. - AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ - 'code' => 'foobar', - ], - [ - 'code' => 'reviewed', - ], - ], - get_permalink( self::factory()->post->create() ) - ); - $response = rest_get_server()->dispatch( $request ); - $this->assertEquals( - [ - 'validated_urls' => 2, - 'errors' => 1, - ], - $response->get_data() - ); - - // Three URLs one with an unreviewed error, another with an unreviewed error and a reviewed one, and another with only reviewed (no change from previous). - AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ - 'code' => 'reviewed', - ], - ], - get_permalink( self::factory()->post->create() ) - ); - $response = rest_get_server()->dispatch( $request ); - $this->assertEquals( - [ - 'validated_urls' => 2, - 'errors' => 1, - ], - $response->get_data() - ); - } - - /** - * Test ::get_item_schema(). - * - * @covers ::get_item_schema() - */ - public function test_get_item_schema() { - self::assertEquals( [ 'validation_urls', 'errors' ], array_keys( $this->controller->get_item_schema()['properties'] ) ); - } -} diff --git a/tests/php/src/ValidationExemptionTest.php b/tests/php/src/ValidationExemptionTest.php deleted file mode 100644 index 0531fd9e2b8..00000000000 --- a/tests/php/src/ValidationExemptionTest.php +++ /dev/null @@ -1,178 +0,0 @@ - [ - '//script', - '', - '', - ], - 'attribute' => [ - '//img/@onload', - '', - '', - ], - 'both' => [ - '//script | //script/@onload | //script/@src', - '', - '', - ], - ]; - } - - /** - * @dataProvider get_data_to_test_px_verified_node - * - * @covers ::is_px_verified_for_node() - * @covers ::mark_node_as_px_verified() - * @covers ::is_document_with_px_verified_nodes() - * @covers ::is_document_containing_attributes() - * @covers ::check_for_attribute_token_list_membership() - */ - public function test_px_verified_node( $xpath, $input, $expected ) { - $dom = Document::fromHtml( "$input" ); - $nodes = $dom->xpath->query( $xpath ); - $this->assertFalse( ValidationExemption::is_document_with_px_verified_nodes( $dom ) ); - foreach ( $nodes as $node ) { - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $node ) ); - } - foreach ( $nodes as $node ) { - $this->assertTrue( ValidationExemption::mark_node_as_px_verified( $node ) ); - } - foreach ( $nodes as $node ) { - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $node ) ); - } - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $dom->body ) ); - $this->assertTrue( ValidationExemption::is_document_with_px_verified_nodes( $dom ) ); - - $this->assertSimilarMarkup( - $expected, - preg_replace( ':]*>:', '', $dom->saveHTML( $dom->body ) ) - ); - } - - /** - * @covers ::is_px_verified_for_node() - * @covers ::mark_node_as_px_verified() - * @covers ::is_document_with_px_verified_nodes() - * @covers ::is_document_containing_attributes() - */ - public function test_px_verified_node_for_non_element_nor_attribute() { - $dom = Document::fromHtml( '' ); - - $node = $dom->xpath->query( '//processing-instruction()' )->item( 0 ); - $this->assertInstanceOf( DOMProcessingInstruction::class, $node ); - - // Ensure that PI is a no-op. - $this->assertFalse( ValidationExemption::is_document_with_px_verified_nodes( $dom ) ); - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $node ) ); - $this->assertFalse( ValidationExemption::mark_node_as_px_verified( $node ) ); - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $node ) ); - $this->assertFalse( ValidationExemption::is_document_with_px_verified_nodes( $dom ) ); - } - - /** - * @covers ::mark_node_as_px_verified() - * @covers ::mark_node_with_exemption_attribute() - */ - public function test_mark_node_as_px_verified_for_bad_nodes() { - $dom = Document::fromHtml( '' ); - $comment_node = $dom->createComment( 'test' ); - $this->assertFalse( ValidationExemption::mark_node_as_px_verified( $comment_node ) ); - } - - /** @return array */ - public function get_data_to_test_amp_unvalidated_node() { - return [ - 'element' => [ - '//script', - '', - '', - ], - 'attribute' => [ - '//img/@onload', - '', - '', - ], - 'both' => [ - '//script | //script/@onload | //script/@src', - '', - '', - ], - ]; - } - - /** - * @dataProvider get_data_to_test_amp_unvalidated_node - * - * @covers ::is_amp_unvalidated_for_node() - * @covers ::mark_node_as_amp_unvalidated() - * @covers ::is_document_with_amp_unvalidated_nodes() - * @covers ::is_document_containing_attributes() - * @covers ::check_for_attribute_token_list_membership() - */ - public function test_amp_unvalidated_node( $xpath, $input, $expected ) { - $dom = Document::fromHtml( "$input" ); - $nodes = $dom->xpath->query( $xpath ); - $this->assertFalse( ValidationExemption::is_document_with_amp_unvalidated_nodes( $dom ) ); - foreach ( $nodes as $node ) { - $this->assertFalse( ValidationExemption::is_amp_unvalidated_for_node( $node ) ); - } - foreach ( $nodes as $node ) { - $this->assertTrue( ValidationExemption::mark_node_as_amp_unvalidated( $node ) ); - } - foreach ( $nodes as $node ) { - $this->assertTrue( ValidationExemption::is_amp_unvalidated_for_node( $node ) ); - } - $this->assertFalse( ValidationExemption::is_amp_unvalidated_for_node( $dom->body ) ); - $this->assertTrue( ValidationExemption::is_document_with_amp_unvalidated_nodes( $dom ) ); - - $this->assertSimilarMarkup( - $expected, - preg_replace( ':]*>:', '', $dom->saveHTML( $dom->body ) ) - ); - } - - /** - * @covers ::is_amp_unvalidated_for_node() - * @covers ::mark_node_as_amp_unvalidated() - * @covers ::is_document_with_amp_unvalidated_nodes() - * @covers ::is_document_containing_attributes() - */ - public function test_amp_unvalidated_node_for_non_element_nor_attribute() { - $dom = Document::fromHtml( '' ); - - $node = $dom->xpath->query( '//processing-instruction()' )->item( 0 ); - $this->assertInstanceOf( DOMProcessingInstruction::class, $node ); - - // Ensure that PI is a no-op. - $this->assertFalse( ValidationExemption::is_document_with_amp_unvalidated_nodes( $dom ) ); - $this->assertFalse( ValidationExemption::is_amp_unvalidated_for_node( $node ) ); - $this->assertFalse( ValidationExemption::mark_node_as_amp_unvalidated( $node ) ); - $this->assertFalse( ValidationExemption::is_amp_unvalidated_for_node( $node ) ); - $this->assertFalse( ValidationExemption::is_document_with_amp_unvalidated_nodes( $dom ) ); - } - - /** - * @covers ::mark_node_as_amp_unvalidated() - * @covers ::mark_node_with_exemption_attribute() - */ - public function test_mark_node_as_amp_unvalidated_for_bad_nodes() { - $dom = Document::fromHtml( '' ); - $comment_node = $dom->createComment( 'test' ); - $this->assertFalse( ValidationExemption::mark_node_as_amp_unvalidated( $comment_node ) ); - } -} diff --git a/tests/php/static-analysis-stubs/gutenberg.php b/tests/php/static-analysis-stubs/gutenberg.php deleted file mode 100644 index 136190c1b9a..00000000000 --- a/tests/php/static-analysis-stubs/gutenberg.php +++ /dev/null @@ -1,10 +0,0 @@ - $instance pairs. - * Each component must implement `WP_Service_Worker_Component`. - * Default empty array. - */ - public function __construct( $components = array() ) { - } - /** - * Initialize the class. - */ - public function init() { - } - - /** - * Get caching routes registry. - * - * @since 0.6 - * - * @return WP_Service_Worker_Caching_Routes Registry. - */ - public function caching_routes() { - } - - /** - * Get precaching routes registry. - * - * @since 0.6 - * - * @return WP_Service_Worker_Precaching_Routes Registry. - */ - public function precaching_routes() { - } - - /** - * Registers a service worker script. - * - * @since 0.2 - * - * @param string $handle Handle of the script. - * @param array $args { - * Additional script arguments. - * - * @type string|callable $src Required. URL to the source in the WordPress install, or a callback that - * returns the JS to include in the service worker. - * @type array $deps An array of registered item handles this item depends on. Default empty array. - * } - */ - public function register( $handle, $args = array() ) { - } - /** - * Gets all registered service worker scripts. - * - * @since 0.2 - * - * @return array List of registered scripts. - */ - public function get_all() { - } - /** - * Process one registered script. - * - * @param string $handle Handle. - * @param bool $group Group. Unused. - * @return void - */ - public function do_item( $handle, $group = false ) { - } - /** - * Get validated path to file. - * - * @param string $url Relative path. - * @return string|WP_Error - */ - public function get_validated_file_path( $url ) { - } -} -/** - * Class representing a registry for caching routes. - * - * @since 0.2 - */ -class WP_Service_Worker_Caching_Routes -{ - /** - * Stale while revalidate caching strategy. - * - * @since 0.2 - * @var string - */ - const STRATEGY_STALE_WHILE_REVALIDATE = 'StaleWhileRevalidate'; - /** - * Cache first caching strategy. - * - * @since 0.2 - * @var string - */ - const STRATEGY_CACHE_FIRST = 'CacheFirst'; - /** - * Network first caching strategy. - * - * @since 0.2 - * @var string - */ - const STRATEGY_NETWORK_FIRST = 'NetworkFirst'; - /** - * Cache only caching strategy. - * - * @since 0.2 - * @var string - */ - const STRATEGY_CACHE_ONLY = 'CacheOnly'; - /** - * Network only caching strategy. - * - * @since 0.2 - * @var string - */ - const STRATEGY_NETWORK_ONLY = 'NetworkOnly'; - - /** - * Registers a route. - * - * @since 0.2 - * - * @param string $route Route regular expression, without delimiters. - * @param string|array $strategy Strategy, can be WP_Service_Worker_Caching_Routes::STRATEGY_STALE_WHILE_REVALIDATE, - * WP_Service_Worker_Caching_Routes::STRATEGY_CACHE_FIRST, WP_Service_Worker_Caching_Routes::STRATEGY_NETWORK_FIRST, - * WP_Service_Worker_Caching_Routes::STRATEGY_CACHE_ONLY, WP_Service_Worker_Caching_Routes::STRATEGY_NETWORK_ONLY. - * Deprecated usage: supplying strategy args as an array. - * @param array $args { - * Additional caching strategy route arguments. - * - * @type string $cache_name Name to use for the cache. - * @type array $expiration Expiration plugin configuration. See . - * @type array $broadcast_update Broadcast update plugin configuration. See . - * @type array $cacheable_response Cacheable response plugin configuration. See . - * @type array $background_sync Background sync plugin configuration. See . - * @type array $plugins Deprecated. Array of plugins with configuration. The key of each plugin in the array must match the plugin's name. - * This is deprecated in favor of defining the plugins in the top-level. - * See . - * @return bool Whether the registration was successful. - * } - */ - public function register( $route, $strategy, $args = array() ) - { - } - /** - * Gets all registered routes. - * - * @return array List of registered routes. - * @since 0.2 - * - */ - public function get_all() - { - return $this->routes; - } - /** - * Prepare caching strategy args for export to JS. - * - * @param array $strategy_args Strategy args. - * @return string JS IIFE which returns object for passing to registerRoute. - * @since 0.2 - * - */ - public static function prepare_strategy_args_for_js_export($strategy_args) - { - } -} -/** - * Interface for classes that host a registry. - * - * @since 0.2 - */ -interface WP_Service_Worker_Registry_Aware { - /** - * Gets the registry. - * - * @return WP_Service_Worker_Registry Registry instance. - */ - public function get_registry(); -} -/** - * Class used to register service workers. - * - * @since 0.1 - * - * @see WP_Dependencies - */ -class WP_Service_Workers -{ - /** - * Param for service workers. - * - * @var string - */ - const QUERY_VAR = 'wp_service_worker'; - /** - * Scope for front. - * - * @var int - */ - const SCOPE_FRONT = 1; - /** - * Scope for admin. - * - * @var int - */ - const SCOPE_ADMIN = 2; - /** - * Scope for both front and admin. - * - * @var int - */ - const SCOPE_ALL = 3; - /** - * Constructor. - * - * Instantiates the service worker scripts registry. - */ - public function __construct() - { - } - /** - * Gets the service worker scripts registry. - * - * @return WP_Service_Worker_Scripts Scripts registry instance. - */ - public function get_registry() - { - } - /** - * Get the current scope for the service worker request. - * - * @todo We don't really need this. A simple call to is_admin() is all that is required. - * @return int Scope. Either SCOPE_FRONT or SCOPE_ADMIN. - */ - public function get_current_scope() - { - } - /** - * Get service worker logic for scope. - * - * @see wp_service_worker_loaded() - */ - public function serve_request() - { - } -} -/** - * Get service worker URL by scope. - * - * @since 0.1 - * - * @param int $scope Scope for which service worker to output. Can be WP_Service_Workers::SCOPE_FRONT (default) or WP_Service_Workers::SCOPE_ADMIN. - * @return string Service Worker URL. - */ -function wp_get_service_worker_url( $scope = WP_Service_Workers::SCOPE_FRONT ) {} diff --git a/tests/php/static-analysis-stubs/twentyseventeen.php b/tests/php/static-analysis-stubs/twentyseventeen.php deleted file mode 100644 index c1d02192855..00000000000 --- a/tests/php/static-analysis-stubs/twentyseventeen.php +++ /dev/null @@ -1,15 +0,0 @@ - 'foo', - * 'value' => 'bar', - * ) - * ); - * ``` - * - * Render `$items` as an ASCII table: - * - * ``` - * WP_CLI\Utils\format_items( 'table', $items, array( 'key', 'value' ) ); - * - * # +-----+-------+ - * # | key | value | - * # +-----+-------+ - * # | foo | bar | - * # +-----+-------+ - * ``` - * - * Or render `$items` as YAML: - * - * ``` - * WP_CLI\Utils\format_items( 'yaml', $items, array( 'key', 'value' ) ); - * - * # --- - * # - - * # key: foo - * # value: bar - * ``` - * - * @access public - * @category Output - * - * @param string $format Format to use: 'table', 'json', 'csv', 'yaml', 'ids', 'count'. - * @param array $items An array of items to output. - * @param array|string $fields Named fields for each item of data. Can be array or comma-separated list. - * @return null - */ - function format_items($format, $items, $fields) - { - } - /** - * Create a progress bar to display percent completion of a given operation. - * - * Progress bar is written to STDOUT, and disabled when command is piped. Progress - * advances with `$progress->tick()`, and completes with `$progress->finish()`. - * Process bar also indicates elapsed time and expected total time. - * - * ``` - * # `wp user generate` ticks progress bar each time a new user is created. - * # - * # $ wp user generate --count=500 - * # Generating users 22 % [=======> ] 0:05 / 0:23 - * - * $progress = \WP_CLI\Utils\make_progress_bar( 'Generating users', $count ); - * for ( $i = 0; $i < $count; $i++ ) { - * // uses wp_insert_user() to insert the user - * $progress->tick(); - * } - * $progress->finish(); - * ``` - * - * @access public - * @category Output - * - * @param string $message Text to display before the progress bar. - * @param integer $count Total number of ticks to be performed. - * @param int $interval Optional. The interval in milliseconds between updates. Default 100. - * @return \cli\progress\Bar|\WP_CLI\NoOp - */ - function make_progress_bar($message, $count, $interval = 100) - { - } - - /** - * Return the flag value or, if it's not set, the $default value. - * - * Because flags can be negated (e.g. --no-quiet to negate --quiet), this - * function provides a safer alternative to using - * `isset( $assoc_args['quiet'] )` or similar. - * - * @access public - * @category Input - * - * @param array $assoc_args Arguments array. - * @param string $flag Flag to get the value. - * @param mixed $default Default value for the flag. Default: NULL. - * @return mixed - */ - function get_flag_value( $assoc_args, $flag, $default = null ) - { - } -} diff --git a/tests/php/test-amp-analytics-options.php b/tests/php/test-amp-analytics-options.php deleted file mode 100644 index 2d138c9c57e..00000000000 --- a/tests/php/test-amp-analytics-options.php +++ /dev/null @@ -1,311 +0,0 @@ -user->create( [ 'role' => 'administrator' ] ) ); - } - - private $vendor = 'googleanalytics'; - - private $config_one = '{ - "requests": { - "event": "https://example.com/..." - }, - "triggers": { - "trackPageview": { - "on": "visible", - "request": "event", - "visibilitySpec": { - "selector": "#cat-image-id", - "visiblePercentageMin": 20, - "totalTimeMin": 500, - "continuousTimeMin": 200 - }, - "vars": { - "eventId": "catview" - } - } - } - }'; - - private $config_two = '{ - "requests": { - "event": "https://example.com/..." - }, - "triggers": { - "trackAnchorClicks": { - "on": "click", - "selector": "a", - "request": "event", - "vars": { - "eventId": "clickOnAnyAnchor" - } - } - } - }'; - - private function get_options() { - return AMP_Options_Manager::get_option( Option::ANALYTICS, [] ); - } - - private function render_post() { - $user_id = self::factory()->user->create(); - $post_id = self::factory()->post->create( - [ - 'post_author' => $user_id, - ] - ); - - return get_echo( 'amp_render_post', [ $post_id ] ); - } - - /** - * Insert one analytics entry. - * - * @param string $type Entry type (vendor). - * @param string $config Entry config (JSON). - */ - private function insert_one_option( $type, $config ) { - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - 'abcdefghijkl' => compact( 'type', 'config' ), - ] - ); - } - - /** - * Inserts two analytics entries. - * - * @param string $type Entry type (vendor). - * @param string $config Entry config (JSON). - */ - private function insert_two_options( $type, $config ) { - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - 'abcdefghijkl' => compact( 'type', 'config' ), - 'mnopqrstuvwx' => [ - 'type' => $type, - 'config' => '{"good": "good"}', - ], - ] - ); - } - - /** - * Test that nothing is added if no analytics option defined in the DB - */ - public function test_no_options() { - $options = $this->get_options(); - $this->assertEmpty( $options ); - } - - /** - * Test that exactly one analytics component is inserted into the DB - */ - public function test_one_option_inserted() { - $this->insert_one_option( - $this->vendor, - $this->config_one - ); - $options = $this->get_options(); - - $this->assertCount( 1, $options ); - } - - /** - * Test that two analytics components are inserted into the DB - */ - public function test_two_options_inserted() { - - $this->insert_two_options( - $this->vendor, - $this->config_one - ); - - $options = $this->get_options(); - - $this->assertCount( 2, $options ); - } - - /** - * Test that exactly one analytics component is added to the page. - * - * @covers ::amp_print_analytics() - */ - public function test_one_analytics_component_added() { - - /* Insert analytics option */ - $this->insert_one_option( - $this->vendor, - $this->config_one - ); - - ob_start(); - amp_print_analytics( [] ); - $amp_rendered = ob_get_clean(); - - $libxml_previous_state = libxml_use_internal_errors( true ); - - $dom = new Document(); - $dom->loadHTML( $amp_rendered ); - - $components = $dom->getElementsByTagName( 'amp-analytics' ); - - libxml_clear_errors(); - libxml_use_internal_errors( $libxml_previous_state ); - - // One amp-analytics component should be in the page - $this->assertEquals( 1, $components->length ); - } - - /** - * Test that two analytics components are added to the page. - * - * @covers ::amp_print_analytics() - */ - public function test_two_analytics_components_added() { - - $this->insert_two_options( - $this->vendor, - $this->config_one - ); - - ob_start(); - amp_print_analytics( [] ); - $amp_rendered = ob_get_clean(); - - $libxml_previous_state = libxml_use_internal_errors( true ); - - $dom = new Document(); - $dom->loadHTML( $amp_rendered ); - $components = $dom->getElementsByTagName( 'amp-analytics' ); - - libxml_clear_errors(); - libxml_use_internal_errors( $libxml_previous_state ); - - // Two amp-analytics components should be in the page - $this->assertEquals( 2, $components->length ); - } - - /** - * Test amp_get_analytics() - * - * @covers ::amp_get_analytics() - */ - public function test_amp_get_analytics() { - $this->insert_one_option( - $this->vendor, - $this->config_one - ); - - $analytics = amp_get_analytics(); - $this->assertCount( 1, $analytics ); - - $key = key( $analytics ); - $this->assertArrayHasKey( 'type', $analytics[ $key ] ); - $this->assertEquals( 'googleanalytics', $analytics[ $key ]['type'] ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - add_filter( - 'amp_analytics_entries', - static function( $analytics ) use ( $key ) { - $analytics[ $key ]['type'] = 'test'; - $analytics[ $key ]['attributes']['data-include'] = '_till_responded'; - $analytics[ $key ]['attributes']['data-block-on-consent'] = 'credentials'; - return $analytics; - } - ); - $analytics = amp_get_analytics(); - $this->assertEquals( 'test', $analytics[ $key ]['type'] ); - $this->assertEquals( '_till_responded', $analytics[ $key ]['attributes']['data-include'] ); - $this->assertEquals( 'credentials', $analytics[ $key ]['attributes']['data-block-on-consent'] ); - } - - /** - * Test amp_print_analytics() - * - * @covers ::amp_print_analytics() - */ - public function test_amp_print_analytics() { - $this->insert_one_option( - $this->vendor, - $this->config_one - ); - - $analytics = amp_get_analytics(); - - $key = key( $analytics ); - - $trigger_count = 0; - - $entries_test = function ( $entries ) use ( $analytics, &$trigger_count ) { - $this->assertEquals( $analytics, $entries ); - $trigger_count++; - }; - - add_action( - 'amp_print_analytics', - $entries_test - ); - - $output = get_echo( 'amp_print_analytics', [ $analytics ] ); - - $this->assertEquals( 1, $trigger_count ); - - $this->assertStringStartsWith( 'assertStringContainsString( 'type="googleanalytics"> - - - -

The following should have a green outline.

- - - - - -
-

Section 1

-
Content in section 1.
-
-
-

Section 2

-
Content in section 2.
-
- -
-

Section 3

-
Content in section 3.
-
-
- - - - - - ', - 'expected' => ' - - - - - - -

The following should have a green outline.

- - -
-

Section 1

-
Content in section 1.
-
-
-

Section 2

-
Content in section 2.
-
- -
-

Section 3

-
Content in section 3.
-
-
- - - - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [], - 'expect_prefer_bento' => true, - ], - - 'non-amp-bento-component' => [ - 'source' => ' - - - - - - - - - - - -

News flash!!!

-
- - - - - ', - 'expected' => ' - - - - - - - - - - - - -

News flash!!!

-
- - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [], - 'expect_prefer_bento' => true, - ], - - 'both-amp-and-bento-components' => [ - 'source' => ' - - - - - - - - - - - - - - - - - - - - - Saturday 11 April 2017 00.37 - - - - - - - - - -
- -
- -

News flash!!!

-
- - - ', - 'expected' => ' - - - - - - - - - - - - Saturday 11 April 2017 00.37 - - - - - - - - - -
- -
- - -

News flash!!!

-
- - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [], - 'expect_prefer_bento' => true, - ], - - 'bento-components-hidden-initially' => [ - 'source' => ' - - - - - - - - - - - - - - - - - - Lightboxed content - - - - - - ', - 'expected' => ' - - - - - - - - - - - - - Lightboxed content - - - - - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [], - 'expect_prefer_bento' => true, - ], - - 'no-bento-components' => [ - 'source' => ' - - - - - - - - - - - - - - - - - Hello World!! - - - ', - 'expected' => ' - - - - - - - Hello World!! - - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - 'expect_prefer_bento' => false, - ], - - 'bento-mathml' => [ - 'source' => ' - - - - - - - - - -

The Quadratic Formula

- - -

Inline formula

-

- This is an example of a formula, - - placed inline in the middle of a block of text. -

- - - ', - 'expected' => ' - - - - - - -

The Quadratic Formula

- - -

Inline formula

-

- This is an example of a formula, - - placed inline in the middle of a block of text. -

- - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [], - 'expect_prefer_bento' => true, - ], - - 'bento-no-layout-available' => [ - 'source' => ' - - - - - - - - - - - - - - -
-
-
-
- - - ', - // Note: It's somewhat unexpected that the styles are still in the document since the element was removed. - // But this is because the tree shaking happened before the tag-and-attribute sanitizer ran, so at the - // time of tree shaking the bento-base-carousel element was still in the document. - 'expected' => ' - - - - - - - - ', - 'sanitizer_args' => [], - 'expected_error_codes' => [ - AMP_Tag_And_Attribute_Sanitizer::MISSING_LAYOUT_ATTRIBUTES, - ], - 'expect_prefer_bento' => true, - ], - ]; - } - - /** - * Test that noscript elements get replaced with their children. - * - * @dataProvider get_sanitizer_data - * @param string $source Source. - * @param string $expected Expected. - * @param array $sanitizer_args Sanitizer args. - * @param array $expected_error_codes Expected error codes. - * @param bool $expect_prefer_bento Whether expecting prefer_bento to be set. - * @covers ::init() - * @covers ::sanitize() - * @covers ::has_light_shadow_dom() - * @covers ::get_selector_conversion_mapping() - * @covers ::adapt_layout_styles() - * @covers ::get_bento_component_name_from_url() - * @covers \AMP_Base_Sanitizer::set_layout() - */ - public function test_sanitize( $source, $expected = null, $sanitizer_args = [], $expected_error_codes = [], $expect_prefer_bento = false ) { - if ( null === $expected ) { - $expected = $source; - } - $dom = Document::fromHtml( $source, Options::DEFAULTS ); - - $validation_error_callback_arg = isset( $sanitizer_args['validation_error_callback'] ) ? $sanitizer_args['validation_error_callback'] : null; - - $actual_error_codes = []; - - $sanitizer_args['validation_error_callback'] = static function ( $error ) use ( &$actual_error_codes, $validation_error_callback_arg ) { - $actual_error_codes[] = $error['code']; - - if ( $validation_error_callback_arg ) { - return $validation_error_callback_arg(); - } else { - return true; - } - }; - - $sanitizer_args['use_document_element'] = true; - - $bento_sanitizer = new AMP_Bento_Sanitizer( - $dom, - $sanitizer_args - ); - - $tag_and_attribute_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( - $dom, - array_merge( - $sanitizer_args, - [ - 'prefer_bento' => false, // Overridden by AMP_Base_Sanitizer. - ] - ) - ); - - $sanitizers = [ - AMP_Bento_Sanitizer::class => $bento_sanitizer, - AMP_Script_Sanitizer::class => new AMP_Script_Sanitizer( - $dom, - $sanitizer_args - ), - AMP_Style_Sanitizer::class => new AMP_Style_Sanitizer( - $dom, - $sanitizer_args - ), - AMP_Tag_And_Attribute_Sanitizer::class => $tag_and_attribute_sanitizer, - ]; - - foreach ( $sanitizers as $sanitizer ) { - $sanitizer->init( $sanitizers ); - } - - $this->assertFalse( $tag_and_attribute_sanitizer->get_arg( 'prefer_bento' ) ); - - foreach ( $sanitizers as $sanitizer ) { - $sanitizer->sanitize(); - } - - $content = $dom->saveHTML( $dom->documentElement ); - $this->assertSimilarMarkup( $expected, $content ); - - $this->assertSame( $expected_error_codes, $actual_error_codes ); - $this->assertSame( $expect_prefer_bento, $tag_and_attribute_sanitizer->get_arg( 'prefer_bento' ) ); - } -} diff --git a/tests/php/test-amp-block-uniqid-sanitizer.php b/tests/php/test-amp-block-uniqid-sanitizer.php deleted file mode 100644 index c54e5a2ebc3..00000000000 --- a/tests/php/test-amp-block-uniqid-sanitizer.php +++ /dev/null @@ -1,101 +0,0 @@ - [ - 'content' => - ' -
This is a super cool class name: wp-duotone-0123456789abc!
- - - ', - 'expected' => - ' -
This is a super cool class name: wp-duotone-0123456789abc!
- - - ', - ], - 'transform_legacy_duotone_class_name' => [ - 'content' => - ' -
This is a super cool class name: wp-duotone-filter-622b62d997e58!
- - - ', - 'expected' => - ' -
This is a super cool class name: wp-duotone-filter-622b62d997e58!
- - - ', - ], - 'transform_container_class_name' => [ - 'content' => '
This is a super cool class name: wp-container-0123456789abc!
', - 'expected' => '
This is a super cool class name: wp-container-0123456789abc!
', - ], - 'transform_elements_class_name' => [ - 'content' => - ' - - - ', - 'expected' => - ' - - - ', - ], - 'ignore_class_names_without_hash' => [ - 'content' => '
This is a super cool class name: wp-duotone-0123456789abc!
', - 'expected' => '
This is a super cool class name: wp-duotone-0123456789abc!
', - ], - 'ignore_already_transformed_class_names' => [ - 'content' => '
This is a super cool class name: wp-duotone-0123456789abc!
', - 'expected' => '
This is a super cool class name: wp-duotone-0123456789abc!
', - ], - ]; - } - - /** - * @covers ::transform_class_names_in_content() - * @covers ::transform_class_names_in_inline_styles() - * @covers ::get_class_name_regexp_pattern() - * @covers ::unique_id() - * - * @dataProvider get_block_data - * - * @param string $content - * @param string $expected - */ - public function test_sanitize( $content, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $content ); - $sanitizer = new AMP_Block_Uniqid_Sanitizer( $dom ); - - $sanitizer->sanitize(); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - // Normalize auto-incrementing ID to allow tests to be run in isolation. - $content = preg_replace( '/-\d+\b/', '-1', $content ); - - $this->assertEqualMarkup( $expected, $content ); - } -} diff --git a/tests/php/test-amp-carousel.php b/tests/php/test-amp-carousel.php deleted file mode 100644 index a4a7753e699..00000000000 --- a/tests/php/test-amp-carousel.php +++ /dev/null @@ -1,172 +0,0 @@ -', - $src, - $width, - $height - ) - ); - - $image = $dom->body->firstChild; - - $caption_element = AMP_DOM_Utils::create_node( $dom, 'a', [ 'href' => 'example.org' ] ); - $caption_element->appendChild( new DOMText( 'Example caption' ) ); - - return [ - 'image_without_caption' => [ - ( new ElementList() )->add( $image, null ), - $dom, - '
', - ], - 'image_with_html_caption' => [ - ( new ElementList() )->add( $image, $caption_element ), - $dom, - '
', - ], - ]; - } - - /** - * Test getting the amp-carousel. - * - * @dataProvider get_carousel_data - * @covers \AmpProject\AmpWP\Component\Carousel::get_dom_element() - * - * @param ElementList $slides An array of arrays, with images and their captions (if any). - * @param Document $dom The representation of the DOM. - * @param string $expected The expected return value of the tested function. - */ - public function test_get_dom_element( $slides, $dom, $expected ) { - $amp_carousel = new Carousel( $dom, $slides ); - $actual_amp_carousel = $amp_carousel->get_dom_element(); - - // Prevent an error in get_content_from_dom_node(). - $dom->body->appendChild( $actual_amp_carousel ); - - $this->assertEquals( - $expected, - $dom->saveHTML( $actual_amp_carousel ) - ); - } - - /** - * Gets the testing data for test_get_dimensions. - * - * @return array[] An associative array, including the ElementList and the expected return value. - */ - public function get_data_carousel_dimensions() { - $dom = new Document(); - $narrow_image_width = '300'; - $narrow_image_height = '600'; - $narrow_image = AMP_DOM_Utils::create_node( - $dom, - 'amp-img', - [ - 'width' => $narrow_image_width, - 'height' => $narrow_image_height, - ] - ); - - $wide_image_width = 1400; - $wide_image_height = 1000; - $wide_image = AMP_DOM_Utils::create_node( - $dom, - 'amp-img', - [ - 'width' => $wide_image_width, - 'height' => $wide_image_height, - ] - ); - - $image_with_0_height = AMP_DOM_Utils::create_node( - $dom, - 'amp-img', - [ - 'width' => 1000, - 'height' => 0, - ] - ); - - return [ - 'empty_dom_element_list_as_argument' => [ - ( new ElementList() ), - [ Carousel::FALLBACK_WIDTH, Carousel::FALLBACK_HEIGHT ], - ], - 'element_no_width_or_height' => [ - ( new ElementList() )->add( AMP_DOM_Utils::create_node( $dom, 'div', [] ) ), - [ Carousel::FALLBACK_WIDTH, Carousel::FALLBACK_HEIGHT ], - ], - 'single_small_image_passed_as_argument' => [ - ( new ElementList() )->add( $narrow_image ), - [ $narrow_image_width, $narrow_image_height ], - ], - 'single_large_image_passed_as_argument' => [ - ( new ElementList() )->add( $wide_image ), - [ $wide_image_width, $wide_image_height ], - ], - 'image_with_0_height_should_not_affect_ratio' => [ - ( new ElementList() )->add( $image_with_0_height )->add( $wide_image, null ), - [ $wide_image_width, $wide_image_height ], - ], - 'two_images' => [ - ( new ElementList() )->add( $narrow_image )->add( $wide_image, null ), - [ $wide_image_width, $wide_image_height ], - ], - 'two_images_order_changed' => [ - ( new ElementList() )->add( $wide_image )->add( $narrow_image, null ), - [ $wide_image_width, $wide_image_height ], - ], - ]; - } - - /** - * Test get_dimensions. - * - * @dataProvider get_data_carousel_dimensions - * @covers \AmpProject\AmpWP\Component\Carousel::get_dimensions() - * - * @param ElementList $slides The slides to get the dimensions from. - * @param array $expected The expected return value of the tested function. - * @throws ReflectionException If invoking the method reflection fails. - */ - public function test_get_dimensions( $slides, $expected ) { - $carousel = new Carousel( new Document(), $slides ); - - $this->assertEquals( - $expected, - $this->call_private_method( $carousel, 'get_dimensions' ) - ); - } -} diff --git a/tests/php/test-amp-crowdsignal-embed-handler.php b/tests/php/test-amp-crowdsignal-embed-handler.php deleted file mode 100644 index 078d5884c30..00000000000 --- a/tests/php/test-amp-crowdsignal-embed-handler.php +++ /dev/null @@ -1,124 +0,0 @@ - 'rich', - 'version' => '1.0', - 'provider_name' => 'Crowdsignal', - 'provider_url' => 'https://crowdsignal.com', - 'title' => 'Which design do you prefer?', - 'html' => '', // phpcs:ignore - ]; - - $poll_response['html'] = $this->adapt_iframe_title( $poll_response['html'] ); - - $survey_response = [ - 'type' => 'rich', - 'version' => '1.0', - 'provider_name' => 'Crowdsignal', - 'provider_url' => 'https://crowdsignal.com', - 'html' => "
\n", - ]; - - $data = [ - 'poll.fm' => [ - 'https://poll.fm/7012505', - '

', - $poll_response, - ], - - 'polldaddy_poll' => [ - 'https://polldaddy.com/poll/7012505/', - '

', - $poll_response, - ], - ]; - - /* - * There is a bug with WordPress's oEmbed handling for Crowdsignal surveys. - * See . - */ - if ( version_compare( get_bloginfo( 'version' ), '5.2.0', '>=' ) ) { - $data['survey.fm'] = [ - 'https://rydk.survey.fm/test-survey', - '

View Survey

', - $survey_response, - ]; - } - - return $data; - } - - /** - * Test conversion. - * - * @dataProvider get_conversion_data - * - * @param string $url Source. - * @param string $expected Expected. - * @param string $oembed_response oEmbed response. - */ - public function test_conversion( $url, $expected, $oembed_response ) { - add_filter( - 'pre_http_request', - static function ( $pre, $r, $request_url ) use ( $oembed_response ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $pre; - } - - if ( ! preg_match( '/crowdsignal|polldaddy/', $request_url ) ) { - return $pre; - } - - return [ - 'body' => wp_json_encode( $oembed_response ), - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - }, - 10, - 3 - ); - - $embed = new AMP_Crowdsignal_Embed_Handler(); - $embed->register_embed(); - $filtered_content = apply_filters( 'the_content', $url ); - - $expected = $this->adapt_iframe_title( $expected ); - - $this->assertEquals( trim( $expected ), trim( $filtered_content ) ); - } - - private function adapt_iframe_title( $html ) { - // Prior to 5.1, there was no 'title' attribute on an iframe. - if ( version_compare( get_bloginfo( 'version' ), '5.1', '<' ) ) { - $html = preg_replace( '/( [ - '

Hello world.

', - '

Hello world.

' . PHP_EOL, - ], - - 'url_simple' => [ - 'https://www.dailymotion.com/video/x5awwth' . PHP_EOL, - '

' . PHP_EOL, - ], - - 'url_with_title' => [ - 'http://www.dailymotion.com/video/x5awwth_snatched-official-trailer-2-hd_shortfilms' . PHP_EOL, - '

' . PHP_EOL, - ], - ]; - } - - /** - * @dataProvider get_conversion_data - */ - public function test__conversion( $source, $expected ) { - $embed = new AMP_DailyMotion_Embed_Handler(); - $embed->register_embed(); - $filtered_content = apply_filters( 'the_content', $source ); - - $this->assertEquals( $expected, $filtered_content ); - } - - public function get_scripts_data() { - return [ - 'not_converted' => [ - '

Hello World.

', - [], - ], - 'converted' => [ - 'https://www.dailymotion.com/video/x5awwth' . PHP_EOL, - [ 'amp-dailymotion' => true ], - ], - ]; - } - - /** - * @dataProvider get_scripts_data - */ - public function test__get_scripts( $source, $expected ) { - $embed = new AMP_DailyMotion_Embed_Handler(); - $embed->register_embed(); - $source = apply_filters( 'the_content', $source ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( AMP_DOM_Utils::get_dom_from_content( $source ) ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-amp-dev-mode-sanitizer.php b/tests/php/test-amp-dev-mode-sanitizer.php deleted file mode 100644 index 18bbb425d4f..00000000000 --- a/tests/php/test-amp-dev-mode-sanitizer.php +++ /dev/null @@ -1,56 +0,0 @@ -All good.

- -
-
  • Blank!
  • -
    - - ' - ); - - $sanitizer = new AMP_Dev_Mode_Sanitizer( - $dom, - [ - 'element_xpaths' => [ - '//*[ @id = "greet" ]', - '//*[ @id = "wpadminbar" ]', - '//*[ @id = "wpadminbar" ]//*', - '//style[ @id = "admin-bar-inline-css" ]', - ], - ] - ); - $sanitizer->sanitize(); - - // Assert dev mode is set correctly on elements. - $this->assertFalse( $dom->hasInitialAmpDevMode() ); - $this->assertTrue( $dom->documentElement->hasAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE ) ); - $this->assertTrue( $dom->getElementById( 'greet' )->hasAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE ) ); - $this->assertTrue( $dom->getElementById( 'wpadminbar' )->hasAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE ) ); - $this->assertTrue( $dom->getElementById( 'wp-admin-bar-img' )->hasAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE ) ); - $this->assertTrue( $dom->getElementById( 'admin-bar-inline-css' )->hasAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE ) ); - $this->assertFalse( $dom->getElementById( 'no-dev-mode-needed' )->hasAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE ) ); - } -} diff --git a/tests/php/test-amp-facebook-embed-handler.php b/tests/php/test-amp-facebook-embed-handler.php deleted file mode 100644 index c34b9c883b6..00000000000 --- a/tests/php/test-amp-facebook-embed-handler.php +++ /dev/null @@ -1,235 +0,0 @@ - [ - '

    Hello World.

    ', - [], - ], - 'converted' => [ - 'https://www.facebook.com/zuck/posts/10102593740125791' . PHP_EOL, - [ 'amp-facebook' => true ], - ], - ]; - } - - /** - * Test get_scripts(). - * - * @dataProvider get_scripts_data - * @param string $source Source. - * @param array $expected Expected scripts. - */ - public function test__get_scripts( $source, $expected ) { - $embed = new AMP_Facebook_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } - - /** - * Data for test__raw_embed_sanitizer. - * - * @return array - */ - public function get_raw_embed_dataset() { - $overflow_button = ''; - - return [ - 'no_embed_blockquote' => [ - '

    Hello world.

    ', - '

    Hello world.

    ', - ], - - 'div_without_facebook_embed' => [ - '
    lorem ipsum
    ', - '
    lorem ipsum
    ', - ], - - 'simple_url_https' => [ - 'https://www.facebook.com/zuck/posts/10102593740125791' . PHP_EOL, - '' . $overflow_button . '' . PHP_EOL, - ], - - 'notes_url' => [ - 'https://www.facebook.com/notes/facebook-engineering/under-the-hood-the-javascript-sdk-truly-asynchronous-loading/10151176218703920/' . PHP_EOL, - '' . $overflow_button . '' . PHP_EOL, - ], - - 'photo_url' => [ - 'https://www.facebook.com/photo.php?fbid=10102533316889441&set=a.529237706231.2034669.4&type=3&theater' . PHP_EOL, - '' . $overflow_button . '' . PHP_EOL, - ], - - 'video_url' => [ - 'https://www.facebook.com/zuck/videos/10102509264909801/' . PHP_EOL, - '' . $overflow_button . '' . PHP_EOL, - ], - - 'post_embed' => [ - '
    ', - '' . $overflow_button . '', - ], - - 'post_with_fallbacks' => [ - ' -
    -
    -
    - ', - ' - - ' . $overflow_button . ' -
    -
    - ', - ], - - 'video_embed' => [ - '
    ', - '' . $overflow_button . '', - ], - - 'page_embed' => [ - ' -
    -
    -
    -
    -
    - ', - ' - - ' . $overflow_button . ' -
    -
    -
    -
    - ', - ], - - 'like' => [ - ' -
    - ', - '' . $overflow_button . ' - ', - ], - - 'comments' => [ - ' -
    - ', - '' . $overflow_button . '', - ], - - 'comments_full_width' => [ - ' -
    - ', - '' . $overflow_button . '', - ], - - 'comments_full_width_2' => [ - ' -
    - ', - '' . $overflow_button . '', - ], - - 'comment_embed' => [ - ' -
    - ', - '' . $overflow_button . '', - ], - - 'remove_fb_root' => [ - '
    ' . str_repeat( '', 5 ), // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - '', - ], - - 'remove_multiple_fb_root' => [ - str_repeat( '
    ', 5 ) . str_repeat( '', 5 ), // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - '', - ], - - 'remove_empty_p_tag' => [ - '

    ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - '', - ], - - 'keep_p_tag_if_it_has_children' => [ - '

    ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - '

    ', - ], - ]; - } - - /** - * Test raw_embed_sanitizer. - * - * @param string $source Content. - * @param string $expected Expected content. - * @dataProvider get_raw_embed_dataset - * @covers AMP_Facebook_Embed_Handler::sanitize_raw_embeds() - */ - public function test__raw_embed_sanitizer( $source, $expected ) { - $embed = new AMP_Facebook_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $layout_sanitizer = new AMP_Layout_Sanitizer( $dom ); - $layout_sanitizer->sanitize(); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - // Normalize blockquote contents to account for editing of published posts or variability of localized datetime strings. - $content = preg_replace( '#().+?()#s', '$1$2', $content ); - - $this->assertEqualMarkup( $expected, $content ); - } -} diff --git a/tests/php/test-amp-form-sanitizer.php b/tests/php/test-amp-form-sanitizer.php deleted file mode 100644 index cccd329f9b4..00000000000 --- a/tests/php/test-amp-form-sanitizer.php +++ /dev/null @@ -1,303 +0,0 @@ -go_to( '/current-page/' ); - } - - /** - * Tear down. - */ - public function tear_down() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - parent::tear_down(); - } - - /** - * Data strings for testing converter. - * - * @return array - */ - public function get_data() { - $form_templates = ' -
    -
    -
    - '; - - return [ - 'no_form' => [ - '

    Lorem Ipsum Demet Delorit.

    ', - null, // Same. - ], - 'form_with_get_method_http_action_and_no_target' => [ - '
    ', - '
    ', - ], - 'form_with_get_method_and_action_xhr' => [ - '
    ', - '
    ', - ], - 'form_with_http_action_and_port' => [ - '
    ', - '
    ', - ], - 'form_with_http_action_and_user' => [ - '
    ', - '
    ', - ], - 'form_with_http_action_and_user_pass' => [ - '
    ', - '
    ', - ], - 'form_with_implicit_method_http_action_and_no_action_or_target' => [ - '
    ', - sprintf( '
    ', preg_replace( '#^https?:#', '', home_url( '/current-page/' ) ) ), - ], - 'form_with_empty_method_http_action_and_no_action_or_target' => [ - '
    ', - '
    ', - ], - 'form_with_post_method_http_action_and_no_target' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_exiting_mustache_templates_left_intact' => [ - ' -
    -
    -
    -
    -
    - ', - ' -
    -
    -
    -
    -
    - ', - ], - 'form_with_exiting_mustache_plain_text_scripts_left_intact' => [ - ' -
    -
    -
    -
    -
    - ', - ' -
    -
    -
    -
    -
    - ', - ], - 'form_with_not_all_templates_templates_supplied' => [ - ' -
    -
    -
    - ', - ' -
    -
    -
    -
    -
    - ', - ], - 'form_with_post_method_http_action_and_blank_target' => [ - '
    ', - '
    ', - ], - 'form_with_post_method_http_action_and_self_target' => [ - '
    ', - '
    ', - ], - 'form_with_post_method_https_action_and_custom_target' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'jetpack_contact_form' => [ - '
    hello

    ', - '
    hello

    ' . $form_templates . '
    ', - ], - 'form_with_upload' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_password' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_relative_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_relative_path_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_another_relative_path_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_relative_query_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_multiple_relative_queries_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_relative_fragment_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_relative_query_and_fragment_action_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - ], - 'form_with_pathless_url' => [ - '
    ', - '
    ' . $form_templates . '
    ', - [ - 'native_post_forms_allowed' => 'never', // This is the default. - ], - ], - 'test_with_dev_mode' => [ - '
    ', - null, // No change. - [ - 'add_dev_mode' => true, - ], - ], - 'native_form_with_post_action' => [ - '
    ', - sprintf( '
    ', ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ), - [ - 'native_post_forms_allowed' => 'always', - ], - [], - ], - 'native_form_with_post_action-xhr' => [ - '
    ', - '', - [ - 'native_post_forms_allowed' => 'always', - ], - [ AMP_Form_Sanitizer::POST_FORM_HAS_ACTION_XHR_WHEN_NATIVE_USED ], - ], - 'comment_form_conditionally_not_native' => [ - sprintf( '
    ', site_url( '/wp-comments-post.php', 'https' ) ), - sprintf( '
    %s
    ', site_url( '/wp-comments-post.php?_wp_amp_action_xhr_converted=1', 'https' ), $form_templates ), - [ - 'native_post_forms_allowed' => 'conditionally', - ], - [], - ], - 'comment_form_conditionally_yes_native' => [ - sprintf( '
    ', site_url( '/wp-comments-post.php', 'https' ) ), - sprintf( - ' -
    -
    - ', - ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE, - site_url( '/wp-comments-post.php', 'https' ) - ), - [ - 'native_post_forms_allowed' => 'conditionally', - ], - [], - ], - ]; - } - - /** - * Test html conversion. - * - * @param string $source The source HTML. - * @param string|null $expected The expected HTML after conversion. Null means same as $source. - * @param array $args Args. - * @param array $expected_errors Expected errors. - * @dataProvider get_data - */ - public function test_converter( $source, $expected = null, $args = [], $expected_errors = [] ) { - if ( is_null( $expected ) ) { - $expected = $source; - } - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - if ( ! empty( $args['add_dev_mode'] ) ) { - $dom->documentElement->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - } - - $actual_errors = []; - $args['validation_error_callback'] = static function( $error ) use ( &$actual_errors ) { - $actual_errors[] = $error; - return true; - }; - - $sanitizer = new AMP_Form_Sanitizer( $dom, $args ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - // Normalize the contents of the templates. - foreach ( $dom->xpath->query( MustacheScriptTemplates::XPATH_MUSTACHE_TEMPLATE_ELEMENTS_QUERY, $dom->body ) as $template ) { - while ( $template->firstChild ) { - $template->removeChild( $template->firstChild ); - } - $template->appendChild( $dom->createTextNode( '...' ) ); - } - - $this->assertSimilarMarkup( $expected, AMP_DOM_Utils::get_content_from_dom( $dom ) ); - $this->assertEquals( wp_list_pluck( $actual_errors, 'code' ), $expected_errors ); - } - - /** - * Test scripts. - */ - public function test_scripts() { - $source = '
    '; - $expected = [ 'amp-form' => true ]; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = $validating_sanitizer->get_scripts(); - - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-amp-gallery-embed-handler.php b/tests/php/test-amp-gallery-embed-handler.php deleted file mode 100644 index 458c332b588..00000000000 --- a/tests/php/test-amp-gallery-embed-handler.php +++ /dev/null @@ -1,325 +0,0 @@ -register_core_themes(); - } - - /** - * Tear down. - */ - public function tear_down() { - if ( did_action( 'add_attachment' ) ) { - $this->remove_added_uploads(); - } - - $this->restore_theme_directories(); - - parent::tear_down(); - } - - /** - * Mock caption text. - * - * @var string - */ - const CAPTION_TEXT = 'Example caption'; - - /** - * Replacements. - * - * @var array Associative array of string replacements to process. - */ - private $replacements = []; - - /** - * Get conversion data. - * - * @return array[] - */ - public function get_conversion_data() { - $amp_carousel_caption = ''; - $loading_attribute = version_compare( get_bloginfo( 'version' ), '5.5-alpha', '>' ) ? 'loading="lazy"' : ''; - - return [ - 'shortcode_with_invalid_id' => [ - '[gallery ids=1]', - '', - ], - 'shortcode_with_valid_ids_in_legacy_mode' => [ - '[gallery ids={{id1}},{{id2}},{{id3}}]', - ' - -
    Alt text' . $amp_carousel_caption . '
    -
    Alt text
    -
    Alt text
    -
    ', - true, - ], - 'shortcode_with_valid_ids' => [ - '[gallery ids={{id1}},{{id2}},{{id3}}]', - ' - ', - ], - 'shortcode_with_carousel' => [ - '[gallery amp-lightbox=false amp-carousel=true ids={{id1}},{{id2}},{{id3}}]', - ' - -
    Alt text' . $amp_carousel_caption . '
    -
    Alt text
    -
    Alt text
    -
    ', - ], - 'shortcode_with_carousel_linking_to_file' => [ - '[gallery amp-lightbox=false amp-carousel=true link="file" ids={{id1}},{{id2}},{{id3}}]', - ' - -
    Alt text' . $amp_carousel_caption . '
    -
    Alt text
    -
    Alt text
    -
    ', - ], - 'shortcode_with_lightbox' => [ - '[gallery amp-lightbox=true amp-carousel=false ids={{id1}},{{id2}},{{id3}}]', - ' - ', - ], - 'shortcode_with_lightbox_linking_to_file' => [ - '[gallery amp-lightbox=true amp-carousel=false link="file" ids={{id1}},{{id2}},{{id3}}]', - ' - ', - ], - 'shortcode_with_lightbox_and_carousel' => [ - '[gallery amp-lightbox=true amp-carousel=true ids={{id1}},{{id2}},{{id3}}]', - ' - ' . - '
    Alt text' . $amp_carousel_caption . '
    ' . - '
    Alt text
    ' . - '
    Alt text
    ' . - '
    ', - ], - 'shortcode_with_lightbox_and_carousel_linking_to_file' => [ - '[gallery amp-lightbox=true amp-carousel=true link="file" ids={{id1}},{{id2}},{{id3}}]', - ' - ' . - '
    Alt text' . $amp_carousel_caption . '
    ' . - '
    Alt text
    ' . - '
    Alt text
    ' . - '
    ', - ], - 'shortcode_with_no_attributes' => [ - '[gallery]', - // Note the same three attachments will be used here because when the gallery shortcode lacks an ids attribute, it uses unattached photos. - ' - ', - ], - ]; - } - - /** - * Test conversion. - * - * @dataProvider get_conversion_data - * @param string $source Source. - * @param string $expected Expected. - * @param bool $use_legacy_mode Whether to use legacy Reader mode. - */ - public function test__conversion( $source, $expected, $use_legacy_mode = false ) { - $source_files = [ - AMP__DIR__ . '/tests/e2e/assets/small-image-100-100.jpg', - DIR_TESTDATA . '/images/canola.jpg', - DIR_TESTDATA . '/images/gradient-square.jpg', - ]; - - if ( $use_legacy_mode ) { - AMP_Options_Manager::update_option( Option::READER_THEME, ReaderThemes::DEFAULT_READER_THEME ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - } else { - AMP_Options_Manager::update_option( Option::READER_THEME, 'twentyseventeen' ); - } - - // When we generate new attachments, we neither control the IDs being - // generated, which we need for the gallery shortcode, nor the actual - // filenames, which will have an index appended because of filename - // collisions. So we write the tests in a way that they don't rely on - // this, and str-replace the dynamic portions into the expected and - // actual output after the fact. - $ids = []; - $files = []; - $file_urls = []; - - foreach ( $source_files as $index => $source_file ) { - $ids[ $index ] = self::factory()->attachment - ->create_upload_object( $source_file, 0 ); - - $files[ $index ] = rtrim( - wp_get_attachment_url( $ids[ $index ] ), - '.jpg' - ); - - $file_urls[ $index ] = get_attachment_link( $ids[ $index ] ); - - update_post_meta( - $ids[ $index ], - '_wp_attachment_image_alt', - 'Alt text' - ); - - // Add a caption to the first image. - if ( 0 === $index ) { - wp_update_post( - [ - 'ID' => $ids[ $index ], - 'post_excerpt' => self::CAPTION_TEXT, - ] - ); - } - } - - $this->initialize_replacements( $ids, $files, $file_urls ); - - $embed = new AMP_Gallery_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( - 'the_content', - $this->normalize( $source ) - ); - - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - // Normalize auto-incrementing ID. - $content = preg_replace( '/\bgallery-\d+/', 'gallery-1', $content ); - - $this->assertEquals( - $this->normalize( $expected ), - $this->normalize( $content ) - ); - } - - /** - * Initialize the associative array of replacements to perform. - * - * @param array $ids Array of attachment post IDs. - * @param array $files Array of file URLs. - * @param array $file_urls Array of file permalink URLs. - */ - private function initialize_replacements( $ids, $files, $file_urls ) { - $this->replacements = [ - '{{id1}}' => $ids[0], - '{{id2}}' => $ids[1], - '{{id3}}' => $ids[2], - '{{file1}}' => $files[0], - '{{file2}}' => $files[1], - '{{file3}}' => $files[2], - '{{file_url1}}' => $file_urls[0], - '{{file_url2}}' => $file_urls[1], - '{{file_url3}}' => $file_urls[2], - "\n" => '', // Make tests ignore new lines. - '> <' => '><', // Remove left-over space between elements. - ]; - } - - /** - * Normalize a piece of content by replacing placeholders with the related - * dynamic parts. - * - * @param string|array $content Content to normalize. - * @return string|array Normalized content. - */ - private function normalize( $content ) { - // We start by turning multiple whitespaces into one space, as the default WP gallery code - // creates a mess with lots of spaces. - $content = trim( preg_replace( '/\s+/', ' ', $content ) ); - - // Normalize attribute quote style for 5.3-alpha. - $content = str_replace( '', - '', - ], - 'head_noscript_span' => [ - '', - 'No script', - ], - 'test_with_dev_mode' => [ - '', - null, - ], - 'noscript_no_unwrap_attr' => [ - '', - null, - ], - 'noscript_no_unwrap_arg' => [ - '', - null, - [ - 'unwrap_noscripts' => false, - ], - ], - 'script_kept_no_unwrap' => [ - ' - - - - ', - sprintf( - ' - - - - - ', - ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE - ), - [ - 'sanitize_js_scripts' => true, - 'unwrap_noscripts' => true, // This will be ignored because of the kept script. - 'validation_error_callback' => '__return_false', - ], - [ - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - ], - ], - 'inline_scripts_removed' => [ - ' - - - - - - - - - - - - - - - ', - ' - - - - - - - - ', - [ - 'sanitize_js_scripts' => true, - ], - [ - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_INLINE_SCRIPT, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - ], - ], - 'external_scripts_removed' => [ - ' - - - - - - - - ', - ' - - - - ', - [ - 'sanitize_js_scripts' => true, - ], - [ - AMP_Script_Sanitizer::CUSTOM_EXTERNAL_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_EXTERNAL_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_EXTERNAL_SCRIPT, - ], - ], - 'external_scripts_kept' => [ - ' - - - - - - - - ', - sprintf( - ' - - - - - - - - ', - ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE - ), - [ - 'sanitize_js_scripts' => true, - 'validation_error_callback' => '__return_false', - ], - [ - AMP_Script_Sanitizer::CUSTOM_EXTERNAL_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_EXTERNAL_SCRIPT, - AMP_Script_Sanitizer::CUSTOM_EXTERNAL_SCRIPT, - ], - ], - 'external_devmode_script_kept' => [ - ' - - - - - - ', - null, - [ - 'sanitize_js_scripts' => true, - ], - [], - ], - 'external_amp_script_kept' => [ - ' - - - - - - - ', - null, - [ - 'sanitize_js_scripts' => true, - ], - [], - ], - 'amp_onerror_script_kept' => [ - ' - - - - - - - ', - null, - [ - 'sanitize_js_scripts' => true, - ], - [], - ], - 'inline_event_handler_removed' => [ - ' - - - -
    Warning...
    - - - ', - ' - - - I should get unwrapped. -
    Warning...
    - - - ', - [ - 'sanitize_js_scripts' => true, - ], - [ - AMP_Script_Sanitizer::CUSTOM_EVENT_HANDLER_ATTR, - ], - ], - 'inline_event_handler_kept' => [ - ' - - - -
    Warning...
    - - - ', - sprintf( - ' - - - -
    Warning...
    - - - ', - ValidationExemption::AMP_UNVALIDATED_ATTRS_ATTRIBUTE - ), - [ - 'sanitize_js_scripts' => true, - 'validation_error_callback' => '__return_false', - ], - [ - AMP_Script_Sanitizer::CUSTOM_EVENT_HANDLER_ATTR, - ], - ], - 'event_handler_lookalikes_kept' => [ - ' - - - -
    Warning...
    - - - - - ', - ' - - - I should get unwrapped. -
    Warning...
    - - - - - ', - [ - 'sanitize_js_scripts' => true, - ], - [], - ], - ]; - } - - /** - * Test that noscript elements get replaced with their children. - * - * @dataProvider get_sanitizer_data - * @param string $source Source. - * @param string $expected Expected. - * @param array $sanitizer_args Sanitizer args. - * @covers ::sanitize() - */ - public function test_sanitize( $source, $expected = null, $sanitizer_args = [], $expected_error_codes = [] ) { - if ( null === $expected ) { - $expected = $source; - } - $dom = Document::fromHtml( $source, Options::DEFAULTS ); - $this->assertSame( substr_count( $source, 'getElementsByTagName( 'noscript' )->length ); - - $validation_error_callback_arg = isset( $sanitizer_args['validation_error_callback'] ) ? $sanitizer_args['validation_error_callback'] : null; - - $actual_error_codes = []; - - $sanitizer_args['validation_error_callback'] = static function ( $error ) use ( &$actual_error_codes, $validation_error_callback_arg ) { - $actual_error_codes[] = $error['code']; - - if ( $validation_error_callback_arg ) { - return $validation_error_callback_arg(); - } else { - return true; - } - }; - - $sanitizer = new AMP_Script_Sanitizer( $dom, $sanitizer_args ); - $sanitizer->sanitize(); - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom, $sanitizer_args ); - $validating_sanitizer->sanitize(); - $content = $dom->saveHTML( $dom->documentElement ); - $this->assertSimilarMarkup( $expected, $content ); - - $this->assertSame( $expected_error_codes, $actual_error_codes ); - } - - /** @return array */ - public function get_data_to_test_cascading_sanitizer_argument_changes_with_custom_scripts() { - return [ - 'custom_scripts_removed' => [ 3 ], - 'custom_scripts_px_verified' => [ 2 ], - 'custom_scripts_amp_unvalidated' => [ 1 ], - ]; - } - - /** - * @dataProvider get_data_to_test_cascading_sanitizer_argument_changes_with_custom_scripts - * - * @covers ::init() - * - * @param int $level Level. - */ - public function test_cascading_sanitizer_argument_changes_with_custom_scripts( $level ) { - - add_filter( - 'pre_http_request', - static function( $preempt, $request, $url ) { - $r = [ - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - 'headers' => [ 'content-type' => 'text/css' ], - ]; - if ( 'https://example.com/head.css' === $url ) { - $preempt = array_merge( - $r, - [ 'body' => 'head{background-color:white}' ] - ); - } elseif ( 'https://example.com/body.css' === $url ) { - $preempt = array_merge( - $r, - [ 'body' => 'body{background-color:black}' ] - ); - } - return $preempt; - }, - 10, - 3 - ); - - switch ( $level ) { - case 3: - $tag_exemption_attribute = ''; - $attr_exemption_attribute = ''; - break; - case 2: - $tag_exemption_attribute = ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE; - $attr_exemption_attribute = ValidationExemption::PX_VERIFIED_ATTRS_ATTRIBUTE . '="onload"'; - break; - default: - $tag_exemption_attribute = ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE; - $attr_exemption_attribute = ValidationExemption::AMP_UNVALIDATED_ATTRS_ATTRIBUTE . '="onload"'; - } - - // @todo In level 1, deny-listed CSS properties like -moz-binding and behavior should be allowed. Nevertheless, these are very rare now (since they are obsolete). - $dom = Document::fromHtml( - sprintf( - ' - - - - - - - Logo - - - - -
    - -
    -
    Blue Violet
    - - - - - - ', - $attr_exemption_attribute, - $tag_exemption_attribute - ), - Options::DEFAULTS - ); - - $sanitizers = [ - AMP_Script_Sanitizer::class => new AMP_Script_Sanitizer( - $dom, - [ - 'sanitize_js_scripts' => true, - ] - ), - AMP_Form_Sanitizer::class => new AMP_Form_Sanitizer( - $dom, - [ - 'native_post_forms_allowed' => 'never', // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - AMP_Img_Sanitizer::class => new AMP_Img_Sanitizer( - $dom, - [ - 'native_img_used' => false, // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - AMP_Video_Sanitizer::class => new AMP_Video_Sanitizer( - $dom, - [ - 'native_video_used' => false, // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - AMP_Audio_Sanitizer::class => new AMP_Audio_Sanitizer( - $dom, - [ - 'native_audio_used' => false, // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - AMP_Iframe_Sanitizer::class => new AMP_Iframe_Sanitizer( - $dom, - [ - 'native_iframe_used' => false, // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - AMP_Style_Sanitizer::class => new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'disable_style_processing' => false, // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - AMP_Tag_And_Attribute_Sanitizer::class => new AMP_Tag_And_Attribute_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'prefer_bento' => false, // Overridden by AMP_Script_Sanitizer when there is a kept script. - ] - ), - ]; - - /** @var AMP_Base_Sanitizer $sanitizer */ - foreach ( $sanitizers as $sanitizer ) { - $sanitizer->init( $sanitizers ); - } - - foreach ( $sanitizers as $sanitizer ) { - $sanitizer->sanitize(); - } - - $style_element_query = $dom->xpath->query( '//style' ); - $link_element_query = $dom->xpath->query( '//link[ @rel = "stylesheet" ]' ); - $first_style = $style_element_query->item( 0 ); - $this->assertEquals( $level > 1, $first_style->hasAttribute( Attribute::AMP_CUSTOM ) ); - $this->assertEquals( 1 === $level ? 2 : 1, $style_element_query->length, 'Expected styles to be concatenated into one style.' ); - $this->assertEquals( 1 === $level ? 2 : 0, $link_element_query->length, 'Expected external stylesheets to be left as-is in Level 1 only.' ); - - $css_text = join( - '', - array_map( - function ( Element $element ) { - return $element->textContent; - }, - iterator_to_array( $style_element_query ) - ) - ); - - foreach ( $style_element_query as $style_element ) { - $this->assertEquals( - 3 !== $level, - ValidationExemption::is_px_verified_for_node( $style_element ) - ); - } - foreach ( $link_element_query as $link_element ) { - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $link_element ) ); - } - - $this->assertEquals( - 3 === $level ? 0 : 1, - $dom->getElementsByTagName( Tag::SCRIPT )->length - ); - - if ( 1 === $level ) { - $this->assertStringContainsString( '/*comment*/', $css_text ); - } else { - $this->assertStringNotContainsString( '/*comment*/', $css_text ); - } - if ( $level > 1 ) { - $this->assertStringContainsString( 'head{background-color:white}', $css_text ); - $this->assertStringContainsString( 'body{background-color:black}', $css_text ); - } else { - $this->assertStringNotContainsString( 'head{background-color:white}', $css_text ); - $this->assertStringNotContainsString( 'body{background-color:black}', $css_text ); - } - - $this->assertEquals( - 1 === $level ? 0 : 1, - $dom->getElementsByTagName( Extension::IMG )->length, - 'Expected IMG to be converted to AMP-IMG when custom scripts are removed.' - ); - $this->assertMatchesRegularExpression( - 1 === $level ? '/}\s*img\s*{/' : '/}amp-img{/', - $css_text - ); - - $this->assertEquals( - 1 === $level ? 0 : 1, - $dom->getElementsByTagName( Extension::VIDEO )->length, - 'Expected VIDEO to be converted to AMP-VIDEO when custom scripts are removed.' - ); - $this->assertMatchesRegularExpression( - 1 === $level ? '/}\s*video\s*{/' : '/}amp-video{/', - $css_text - ); - - $this->assertEquals( - 1 !== $level ? 1 : 0, - $dom->getElementsByTagName( Extension::AUDIO )->length, - 'Expected AUDIO to be converted to AMP-AUDIO when custom scripts are removed.' - ); - - switch ( $level ) { - case 1: - $this->assertMatchesRegularExpression( '/}\s*audio\s*{\s*outline:\s*solid 1px green !important/', $css_text ); - break; - case 2: - $this->assertStringContainsString( '}amp-audio{', $css_text ); - break; - case 3: - $this->assertStringContainsString( '}amp-audio:not(#_', $css_text ); - break; - } - - $blueviolet_div = $dom->getElementById( 'blueviolet' ); - if ( $level < 3 ) { - $this->assertSame( 'color:blueviolet !important;', $blueviolet_div->getAttribute( 'style' ), 'Expected style attribute to be left as-is in level under 3.' ); - $this->assertStringNotContainsString( 'blueviolet', $css_text, 'Expected blueviolet not to be concatenated under level 3.' ); - } else { - $this->assertFalse( $blueviolet_div->hasAttribute( 'style' ), 'Expected no style attribute in level 3.' ); - $this->assertStringContainsString( 'blueviolet', $css_text, 'Expected ' ); - } - - $this->assertEquals( - 1 === $level ? 0 : 1, - $dom->getElementsByTagName( Extension::IFRAME )->length, - 'Expected IFRAME to be converted to AMP-IFRAME when custom scripts are removed.' - ); - $this->assertMatchesRegularExpression( - 1 === $level ? '/}\s*iframe\s*{/' : '/}amp-iframe{/', - $css_text - ); - - $post_form = $dom->xpath->query( '//form[ @method = "post" ]' )->item( 0 ); - $this->assertInstanceOf( Element::class, $post_form ); - $this->assertEquals( 3 === $level, $post_form->hasAttribute( Attribute::ACTION_XHR ) ); - $this->assertEquals( 3 !== $level, $post_form->hasAttribute( Attribute::ACTION ) ); - - if ( 1 === $level ) { - $this->assertStringContainsString( 'body.loaded', $css_text ); - } else { - $this->assertStringNotContainsString( 'body.loaded', $css_text ); - } - if ( 3 === $level ) { - $this->assertStringNotContainsString( 'body:after{', $css_text ); - } else { - $this->assertStringContainsString( 'body:after{', $css_text ); - } - - // Verify that prefer_bento got set. - $scripts = $sanitizers[ AMP_Tag_And_Attribute_Sanitizer::class ]->get_scripts(); - if ( 3 === $level ) { - $this->assertArrayHasKey( Extension::FACEBOOK_PAGE, $scripts ); - $this->assertArrayNotHasKey( Extension::FACEBOOK, $scripts ); - } else { - $this->assertArrayNotHasKey( Extension::FACEBOOK_PAGE, $scripts ); - $this->assertArrayHasKey( Extension::FACEBOOK, $scripts ); - } - } - - /** @return array */ - public function get_comment_reply_allowed_values() { - $values = [ - 'always', - 'conditionally', - 'never', - ]; - - $data = []; - foreach ( $values as $value ) { - $data[ $value ] = [ 'comment_reply_allowed' => $value ]; - } - return $data; - } - - /** - * @dataProvider get_comment_reply_allowed_values - * @param string $comment_reply_allowed - * @covers ::sanitize_js_script_elements() - */ - public function test_sanitize_js_script_elements_for_comment_reply( $comment_reply_allowed ) { - $dom = Document::fromHtml( - ' - - - - - - - ', - Options::DEFAULTS - ); - - $sanitizer = new AMP_Script_Sanitizer( - $dom, - [ - 'sanitize_js_scripts' => true, - 'comment_reply_allowed' => $comment_reply_allowed, - ] - ); - - $script = $dom->getElementById( 'comment-reply-js' ); - $this->assertInstanceOf( Element::class, $script ); - $sanitizer->sanitize(); - - if ( 'always' === $comment_reply_allowed ) { - $this->assertInstanceOf( Element::class, $script->parentNode ); - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $script ) ); - } elseif ( 'never' === $comment_reply_allowed ) { - $this->assertNull( $script->parentNode ); - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $script ) ); - } else { - $this->assertInstanceOf( Element::class, $script->parentNode ); - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $script ) ); - } - } - - /** - * @see wp_comment_form_unfiltered_html_nonce() - * @covers ::sanitize_js_script_elements() - */ - public function test_sanitize_js_script_elements_for_wp_unfiltered_html_comment_script() { - add_filter( - 'map_meta_cap', - static function ( $caps, $cap ) { - if ( 'unfiltered_html' === $cap ) { - $caps = [ 'exist' ]; - } - return $caps; - }, - 10, - 2 - ); - $this->assertTrue( current_user_can( 'unfiltered_html' ) ); - - $dom = Document::fromHtml( - ' - - - ' . get_echo( 'wp_comment_form_unfiltered_html_nonce' ) . ' - - ', - Options::DEFAULTS - ); - - $sanitizer = new AMP_Script_Sanitizer( - $dom, - [ - 'sanitize_js_scripts' => true, - ] - ); - - $sanitizer->sanitize(); - - $script = $dom->getElementsByTagName( Tag::SCRIPT )->item( 0 ); - $this->assertInstanceOf( Element::class, $script ); - $this->assertStringContainsString( '_wp_unfiltered_html_comment_disabled', $script->textContent ); - $this->assertTrue( DevMode::hasExemptionForNode( $script ) ); - } - - /** - * Test style[amp-boilerplate] preservation. - */ - public function test_boilerplate_preservation() { - ob_start(); - ?> - - - - - - - - - - - - - - - - - - - Hello, AMP world. - Has script? - - - true, - ]; - - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - AMP_Content_Sanitizer::sanitize_document( $dom, amp_get_content_sanitizers(), $args ); - - $content = $dom->saveHTML( $dom->documentElement ); - - $this->assertMatchesRegularExpression( '/\s*/', $content ); - $this->assertStringContainsString( '', $content ); - $this->assertStringContainsString( 'Has script? Nope!', $content ); - $this->assertStringContainsString( '', $content ); - } -} diff --git a/tests/php/test-amp-soundcloud-embed-handler.php b/tests/php/test-amp-soundcloud-embed-handler.php deleted file mode 100644 index 51329edb28f..00000000000 --- a/tests/php/test-amp-soundcloud-embed-handler.php +++ /dev/null @@ -1,193 +0,0 @@ -prevent_block_pre_render(); - - add_filter( 'pre_http_request', [ $this, 'mock_http_request' ], 10, 3 ); - } - - /** - * After a test method runs, reset any state in WordPress the test method might have changed. - */ - public function tear_down() { - remove_filter( 'pre_http_request', [ $this, 'mock_http_request' ] ); - parent::tear_down(); - } - - /** - * Mock HTTP request. - * - * @param mixed $preempt Whether to preempt an HTTP request's return value. Default false. - * @param mixed $r HTTP request arguments. - * @param string $url The request URL. - * @return array Response data. - */ - public function mock_http_request( $preempt, $r, $url ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $preempt; - } - - if ( false === strpos( $url, 'soundcloud.com' ) ) { - return $preempt; - } - unset( $r ); - - if ( false !== strpos( $url, 'sets' ) ) { - $body = $this->playlist_oembed_response; - } else { - $body = $this->track_oembed_response; - } - - return [ - 'body' => $body, - 'headers' => [], - 'response' => [ - 'code' => 200, - 'message' => 'ok', - ], - 'cookies' => [], - 'http_response' => null, - ]; - } - - /** - * Get the embed conversion data. - * - * @return array - */ - public function get_embed_conversion_data() { - return [ - 'no_embed' => [ - '

    Hello world.

    ', - '

    Hello world.

    ' . PHP_EOL, - ], - - 'track_simple' => [ - $this->track_url . PHP_EOL, - '

    ' . ( function_exists( 'wp_filter_oembed_iframe_title_attribute' ) ? 'Mozart – Requiem in D minor Complete Full by Jack Villano Villano' : '' ) . '

    ' . PHP_EOL, - ], - - 'playlist_simple' => [ - $this->playlist_url . PHP_EOL, - '

    ' . ( function_exists( 'wp_filter_oembed_iframe_title_attribute' ) ? 'Classical Music – The Essential Collection by Classical Music' : '' ) . '

    ' . PHP_EOL, - ], - ]; - } - - /** - * Test conversion. - * - * @dataProvider get_embed_conversion_data - * @covers AMP_SoundCloud_Embed_Handler::filter_embed_oembed_html() - * @covers AMP_SoundCloud_Embed_Handler::render() - * - * @param string $source Source. - * @param string $expected Expected. - */ - public function test_embed_conversion( $source, $expected ) { - $embed = new AMP_SoundCloud_Embed_Handler(); - $embed->register_embed(); - $filtered_content = apply_filters( 'the_content', $source ); - - $this->assertEquals( $expected, $filtered_content ); - } - - /** - * Get scripts data. - * - * @return array Scripts data. - */ - public function get_scripts_data() { - return [ - 'not_converted' => [ - '

    Hello World.

    ', - [], - ], - 'converted_track' => [ - $this->track_url . PHP_EOL, - [ 'amp-soundcloud' => true ], - ], - 'converted_playlist' => [ - $this->playlist_url . PHP_EOL, - [ 'amp-soundcloud' => true ], - ], - ]; - } - - /** - * Test get scripts. - * - * @covers AMP_SoundCloud_Embed_Handler::get_scripts() - * @dataProvider get_scripts_data - * - * @param string $source Source. - * @param string $expected Expected. - */ - public function test__get_scripts( $source, $expected ) { - $embed = new AMP_SoundCloud_Embed_Handler(); - $embed->register_embed(); - $source = apply_filters( 'the_content', $source ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( AMP_DOM_Utils::get_dom_from_content( $source ) ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-amp-style-sanitizer.php b/tests/php/test-amp-style-sanitizer.php deleted file mode 100644 index 8e92252ea57..00000000000 --- a/tests/php/test-amp-style-sanitizer.php +++ /dev/null @@ -1,3937 +0,0 @@ -register_core_themes(); - } - - /** - * Tear down. - */ - public function tear_down() { - global $wp_styles, $wp_scripts, $wp_customize; - $wp_styles = null; - $wp_scripts = null; - $wp_customize = null; - - $this->restore_theme_directories(); - - parent::tear_down(); - } - - /** - * Get data for tests. - * - * @return array - */ - public function get_body_style_attribute_data() { - return [ - 'empty' => [ - '', - '', - [], - ], - - 'span_one_style' => [ - 'This is green.', - 'This is green.', - [ - '.amp-wp-bb01159:not(#_#_#_#_#_){color:#0f0}', - ], - ], - - 'span_empty_style' => [ - 'This is default.', - 'This is default.', - [], - ], - - 'span_one_style_bad_format' => [ - 'This is green.', - 'This is green.', - [ - '.amp-wp-0837823:not(#_#_#_#_#_){color:#0f0}', - ], - ], - - 'span_two_styles_reversed' => [ - 'This is green.', - 'This is green.', - [ - '.amp-wp-be0c539:not(#_#_#_#_#_){color:#0f0;background-color:#000}', - ], - ], - - 'span_display_none' => [ - 'Kses-banned properties are allowed since Kses will have already applied if user does not have unfiltered_html.', - 'Kses-banned properties are allowed since Kses will have already applied if user does not have unfiltered_html.', - [ - '.amp-wp-224b51a:not(#_#_#_#_#_){display:none}', - ], - ], - - '!important_is_ok' => [ - '!important is converted.', - '!important is converted.', - [ - '.amp-wp-6a75598:not(#_#_#_#_#_){padding:1px;outline:3px}.amp-wp-6a75598:not(#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_){margin:2px}', - ], - ], - - '!important_with_spaces_also_converted' => [ - '!important is converted.', - '!important is converted.', - [ - '.amp-wp-952600b:not(#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_){color:red}', - ], - ], - - '!important_multiple_is_converted' => [ - '!important is converted.', - '!important is converted.', - [ - '.amp-wp-1e2bfaa:not(#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_){color:red;background:blue}', - ], - ], - - '!important_takes_precedence_over_inline' => [ - '
    bold!
    ', - '
    bold!
    ', - [ - 'div > span{font-style:italic}div > span:not(#_#_#_#_#_#_#_#_){font-weight:bold}@media screen and ( max-width: 640px ){div > span{font-style:normal}div > span:not(#_#_#_#_#_#_#_#_){font-weight:normal}}', - ], - ], - - 'illegal_unsafe_properties' => [ - '', - '', - [ - 'button{font-weight:bold}', - '@media screen{button{font-weight:bold}}', - ], - array_fill( 0, 4, AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY_NOLIST ), - ], - - 'illegal_at_rule_in_style_attribute' => [ - 'invalid @-rule omitted.', - 'invalid @-rule omitted.', - [ - '.amp-wp-481af57:not(#_#_#_#_#_){color:brown}', - ], - [], - ], - - 'illegal_at_rules_removed' => [ - ' - - - - - - - - ', - ' - - - - - - - - - ', - [ - '@page{margin:1cm}body{color:black}', - ], - [ AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_AT_RULE, AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_AT_RULE ], - ], - - 'allowed_at_rules_retained' => [ - '
    ', - '
    ', - [ - '@media screen and ( max-width: 640px ){body{font-size:small}}@font-face{font-family:"Open Sans";src:url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2")}@-moz-document url-prefix(){body{color:red}}@supports (display: grid){div{display:grid}}@-moz-keyframes appear{from{opacity:0}to{opacity:1}}@keyframes appear{from{opacity:0}to{opacity:1}}', - ], - ], - - 'moz_document_allowed' => [ - ' - -

    Hello

    - ', - ' -

    Hello

    - ', - [ - '@-moz-document url-prefix(){.entry .entry-content .has-drop-cap:not(:focus):first-letter{margin-top:.2em}}', - ], - [ - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY_NOLIST, - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY_NOLIST, - ], - ], - - 'selector_specificity' => [ - '
    onetwothree
    ', - '
    onetwothree
    ', - [ - '#child:not(#_#_#_#_#_#_#_){color:red}#parent #child:not(#_#_#_#_#_#_#_#_){color:pink}.foo:not(#_#_#_#_#_#_#_){color:blue}#me .foo:not(#_#_#_#_#_#_#_#_){color:green}', - '.amp-wp-64b4fd4:not(#_#_#_#_#_){color:yellow}', - '.amp-wp-ab79d9e:not(#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_){color:purple}', - ], - ], - - 'grid_lines' => [ - '
    ', - '
    ', - [ - '.wrapper{display:grid;grid-template-columns:[main-start] 1fr [content-start] 1fr [content-end] 1fr [main-end];grid-template-rows:[main-start] 100px [content-start] 100px [content-end] 100px [main-end]}', - ], - ], - - 'col_with_width_attribute' => [ - '
    ', - '
    ', - [ - '.amp-wp-cbcb5c2:not(#_#_#_#_#_){width:253px}', - ], - ], - - 'col_with_percent_width_attribute' => [ - '
    ', - '
    ', - [ - '.amp-wp-cd7753e:not(#_#_#_#_#_){width:50%}', - ], - ], - - 'col_with_star_width_attribute' => [ - '
    ', - '
    ', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'col_with_width_attribute_and_existing_style' => [ - '
    ', - '
    ', - [ - '.amp-wp-c8aa9e9:not(#_#_#_#_#_){width:50px;width:60px;background-color:red}', - ], - ], - - 'nested_css_var_in_function' => [ - '

    ', - '

    ', - [ - '.opacity3{color:rgba(0,0,255,var(--opacity))}', - ], - ], - - 'multi_selector_in_not_pseudo_class' => [ - '
      ', - '
        ', - [ - '.widget:not(.widget_text,.jetpack_widget_social_icons[title="a,b"]) ul{color:red}', - ], - ], - - 'selector_with_escaped_char_class_name' => [ - '
        ', - '
        ', - [ - '.lg\:w-full{width:100%}', - ], - ], - 'semicolon_outside_of_rule_in_media_query' => [ - '', - '', - [ - '@media (max-width: 450px){.sidebar{padding:0}}.sidebar{margin:0 auto}', - ], - ], - 'with_mustache_template' => [ - ' - - - ', - ' - - ', - [ - '.custom-population{color:red}', - '.amp-wp-f2a1aff:not(#_#_#_#_#_){color:blue}', - '.amp-wp-d4ea4c7:not(#_#_#_#_#_){outline:solid 1px black}', - ], - ], - 'with_mustache_template_script' => [ - ' - - - ', - ' - - ', - [ - '.custom-population{color:red}', - '.amp-wp-f2a1aff:not(#_#_#_#_#_){color:blue}', - '.amp-wp-d4ea4c7:not(#_#_#_#_#_){outline:solid 1px black}', - ], - ], - 'with_internal_amp_selectors_and_class_names' => [ - ' - - - - - - - - - - - - - - - ', - ' - - - - - - - - - - - - - ', - [ - 'amp-img[layout=intrinsic],amp-img.size-full{outline:solid 1px red}', - 'amp-img > *:first-child{outline:dotted 2px orange}', - ], - [ - AMP_Style_Sanitizer::CSS_DISALLOWED_SELECTOR, - AMP_Style_Sanitizer::CSS_DISALLOWED_SELECTOR, - AMP_Style_Sanitizer::CSS_DISALLOWED_SELECTOR, - AMP_Style_Sanitizer::CSS_DISALLOWED_SELECTOR, - AMP_Style_Sanitizer::DISALLOWED_ATTR_CLASS_NAME, - AMP_Style_Sanitizer::DISALLOWED_ATTR_CLASS_NAME, - AMP_Style_Sanitizer::DISALLOWED_ATTR_CLASS_NAME, - AMP_Style_Sanitizer::DISALLOWED_ATTR_CLASS_NAME, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG_ANCESTOR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - ], - ], - ]; - } - - /** - * Test sanitizer for style attributes that appear in the body. - * - * @dataProvider get_body_style_attribute_data - * @param string $source Source. - * @param string $expected_content Expected content. - * @param string $expected_stylesheets Expected stylesheets. - * @param array $expected_errors Expected error codes. - */ - public function test_body_style_attribute_sanitizer( $source, $expected_content, $expected_stylesheets, $expected_errors = [] ) { - $use_document_element = false !== strpos( $source, ' $use_document_element, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ]; - - $sanitizer = new AMP_Style_Sanitizer( $dom, $args ); - $sanitizer->sanitize(); - - $meta_sanitizer = new AMP_Meta_Sanitizer( $dom, $args ); - $meta_sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom, $args ); - $validating_sanitizer->sanitize(); - - if ( $use_document_element && count( $sanitizer->get_stylesheets() ) > 0 ) { - $this->assertEquals( 1, $dom->xpath->query( '//style[ @amp-custom ]' )->length, 'Expected stylesheet to be present in page. Failure means INVALID_CDATA_CSS_I_AMPHTML_NAME happened.' ); - } - - // Remove style elements since we will examine the underlying stylesheets instead. - foreach ( iterator_to_array( $dom->getElementsByTagName( 'style' ) ) as $element ) { - if ( 'noscript' === $element->parentNode->nodeName ) { - $element->parentNode->parentNode->removeChild( $element->parentNode ); - } else { - $element->parentNode->removeChild( $element ); - } - } - - // Test content. - if ( $use_document_element ) { - $content = $dom->saveHTML(); - } else { - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - } - $this->assertEqualMarkup( $expected_content, $content ); - - // Test stylesheet. - $this->assertEquals( $expected_stylesheets, array_values( $sanitizer->get_stylesheets() ) ); - - $this->assertEquals( $expected_errors, $error_codes ); - } - - /** - * Get link and style test data. - * - * @return array - */ - public function get_link_and_style_test_data() { - return [ - 'multiple_amp_custom_and_other_styles' => [ - '1ius', - [ - 'b:not(#_#_#_#_#_#_#_#_){color:red}', - 'i{color:blue}', - 'u{color:green}u:not(#_#_#_#_#_#_#_#_){text-decoration:underline}', - 's{color:yellow}', - ], - [], - ], - 'style_elements_with_link_elements' => [ - sprintf( - '', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - includes_url( 'css/dashicons.css' ) - ), - [ - 'strong.before-dashicon', - '.dashicons-dashboard:before', - 'strong.after-dashicon', - 's:not(#_#_#_#_#_#_#_#_){color:yellow}', - ], - [], - ], - 'style_with_no_head' => [ - 'Not good!', - [ - 'body{color:red}', - ], - [], - ], - 'style_with_not_selectors' => [ - '

        Hello

        ', - [ - 'body.foo:not(.bar) > p{color:blue}body.foo:not(.bar) p:not(.baz){color:green}body.foo p{color:yellow}', - ], - [], - ], - 'style_with_attribute_selectors' => [ - '', - [ - '.social-navigation a[href*="example.com"]{color:red}', - ], - [], - ], - 'style_on_root_element' => [ - 'Hi', - [ - 'html:not(#_#_#_#_#_#_#_#_){background-color:blue}', - '.amp-wp-10b06ba:not(#_#_#_#_#_){color:red}', - ], - [], - ], - 'styles_with_dynamic_elements' => [ - implode( - '', - [ - '', - '', - '', - '', - '', - '', - '', - '
        ', - '
        • Hello
        ', - ' ', - 'The current server time is .', - '', - ] - ), - [ - 'form [submit-success] b{color:green}', // The [submit-failure] selector is removed because there is no div[submit-failure]. - 'amp-live-list li .highlighted{background:yellow}', - 'body amp-list .portland{color:blue}', - 'amp-script .loaded{color:brown}', - ], - [], - ], - 'styles_with_calc_functions' => [ - implode( - '', - [ - '', - '', - '', - '', // Test unbalanced parentheses. - '
        ', - ] - ), - [ - 'body{color:red;width:calc(1px + calc(2vh / 3) - 2px * 5);outline:solid 1px blue}', - '.alignwide{max-width:-webkit-calc(50% + 22.5rem);border:solid 1px red}', - '.alignwide{color:red;content:")"}', - ], - [], - ], - 'style_with_media_element' => [ - '', - [ - '@media print{.print{display:none}}', - ], - [], - ], - 'selectors_with_ie_hacks_removed' => [ - 'Test', - [ - 'span{text-decoration:underline}', - ], - [], - ], - 'unamerican_lang_attribute_selectors_removed' => [ // USA is used for convenience here. No political statement intended. - 'Test', - [ - 'html[lang=en-US]{color:red}html[lang="en-US"]{color:white}html[lang^=en]{color:blue}', - ], - [], - ], - 'unamerican_lang_selector_selectors_removed' => [ // USA is used for convenience here. No political statement intended. - ' - - - Test - ', - [ - 'html:lang(en-US){color:red}body span:lang(en-US){color:red}html:lang(en){color:white}.test:lang(en-us, en-CA){color:white}html span.test:lang(en-US){color:blue}html:lang("en-US") span.test{color:blue}', - ], - [], - ], - 'external_link_without_css_file_extension' => [ - 'externally-styled', // phpcs:ignore - [ - 'span:before{content:"Returned from: https://example.com/_static/??-eJx9kN1SAyEMhV9Iip3aOl44Pgs"}', - ], - [], - ], - 'charset_ruleset_removed_without_warning' => [ - '', - [ - 'body{color:limegreen}', - ], - [], - ], - 'dynamic_classes_preserved_always' => [ - ' - - - - - - - - - - - - - - - - - - - - - - -

        Hello!

        - ', - [ - '.amp-viewer{color:blue}', - '.amp-mode-touch{color:blanchedalmond}', - '.amp-mode-mouse{color:bisque}', - '.amp-mode-keyboard-active{color:burlywood}', - '.amp-referrer-www-google-com{color:red}', - ], - [], - ], - 'dynamic_classes_and_attributes_preserved_conditionally' => [ - ' - - - - - - - - - - - - - - - - - - - - - - - - - This site uses cookies to personalize content. Learn more. - - -
        -
        - -
        - - - - -

        Section 1

        Content in section 1.

        Section 2

        Content in section 2.
        - - - - ', - [ - '.amp-viewer{color:blue}', - '.amp-referrer-www-google-com{color:red}', - '.amp-active{color:green}', - '.amp-carousel-slide{outline:solid 1px red}', - '.amp-date-picker-selecting{outline:solid 2px red}.CalendarDay{color:black}', - '.amp-form-submit-success{color:green}', - '.amp-access-laterpay-container{color:purple}', - '.amp-image-lightbox-caption{color:brown}', - '.user-valid,.user-invalid{outline:solid 1px red}', - '.amp-live-list-item-new{color:lime}#my-live-list [data-tombstone]{display:block}', - '.amp-sidebar-toolbar-target-hidden{color:lavender}#sidebar1[open]{outline:solid 1px red}', - '.amp-sticky-ad-close-button{color:aliceblue}', - '.amp-docked-video-shadow{color:azure}', - '.amp-geo-pending{color:saddlebrown}', - '.amp-geo-no-group{color:ghostwhite}', - '.amp-geo-group-foo{color:peru}', - '.amp-iso-country-us{color:oldlace}', - '.amp-video-eq{display:none}', - '.amp-next-page-links,.amp-next-page-link,.amp-next-page-image,.amp-next-page-text,.amp-next-page-separator{outline:solid 1px red}', - '#accord section[expanded]{outline:solid 1px blue}', - ], - [], - ], - 'test_with_dev_mode' => [ - '', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - [], - [], - ], - 'amp_experiment' => [ - ' - - - - - - - - - - - - - - - ', - [ - 'body[amp-x-button-color-experiment="0"] .button-color-experiment{color:red}', - 'body[amp-x-button-color-experiment="1"] .button-color-experiment{color:green}', - 'body[amp-x-button-color-experiment="2"] .button-color-experiment{color:blue}', - ], - [], - ], - 'classes_in_mustache_template' => [ - ' - - - - - - - - - - - ', - [ - 'h2.one{color:green}', - 'h2.two{color:red}', - ], - [], - ], - ]; - } - - /** - * Test style elements and link elements. - * - * @covers AMP_Style_Sanitizer::get_stylesheet_from_url() - * @covers AMP_Style_Sanitizer::fetch_external_stylesheet() - * @covers AMP_Style_Sanitizer::has_used_tag_names() - * @covers AMP_Style_Sanitizer::has_used_class_name() - * @covers AMP_Style_Sanitizer::has_used_attributes() - * @covers AMP_Style_Sanitizer::is_class_allowed_in_amp_date_picker() - * - * @dataProvider get_link_and_style_test_data - * @param string $source Source. - * @param array $expected_stylesheets Expected stylesheets. - * @param array $expected_errors Expected error codes. - */ - public function test_link_and_style_elements( $source, $expected_stylesheets, $expected_errors = [] ) { - add_filter( - 'locale', - static function() { - return 'en_US'; - } - ); - add_filter( - 'pre_http_request', - static function( $preempt, $request, $url ) { - $preempt = [ - 'response' => [ - 'code' => 200, - ], - 'headers' => [ - 'content-type' => 'text/css', - ], - 'body' => sprintf( 'span:before { content: "Returned from: %s"; }', $url ), - ]; - return $preempt; - }, - 10, - 3 - ); - $dom = Document::fromHtml( $source, Options::DEFAULTS ); - - $error_codes = []; - $args = [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ]; - - // Run the script sanitizer to unwrap noscript elements. - $sanitizer = new AMP_Script_Sanitizer( $dom, $args ); - $sanitizer->sanitize(); - - $sanitizer = new AMP_Style_Sanitizer( $dom, $args ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom, $args ); - $validating_sanitizer->sanitize(); - - $sanitized_html = $dom->saveHTML( $dom->documentElement ); - $actual_stylesheets = array_values( array_filter( $sanitizer->get_stylesheets() ) ); - $this->assertEquals( $expected_errors, $error_codes ); - $this->assertCount( count( $expected_stylesheets ), $actual_stylesheets ); - foreach ( $expected_stylesheets as $i => $expected_stylesheet ) { - if ( empty( $expected_stylesheet ) ) { - $this->assertEmpty( $actual_stylesheets[ $i ] ); - continue; - } - - if ( false === strpos( $expected_stylesheet, '{' ) ) { - $this->assertStringContainsString( $expected_stylesheet, $actual_stylesheets[ $i ] ); - } else { - $this->assertEquals( $expected_stylesheet, $actual_stylesheets[ $i ] ); - } - $this->assertStringContainsString( $expected_stylesheet, $sanitized_html ); - } - - if ( $actual_stylesheets ) { - $this->assertStringContainsString( "\n\n/*# sourceURL=amp-custom.css */", $sanitized_html ); - } - } - - /** - * Add test coverage for the property_allowlist condition in process_css_declaration_block which is not currently reachable given the spec. - * - * @covers AMP_Style_Sanitizer::process_css_declaration_block() - */ - public function test_allowlisted_properties_in_declaration_block() { - $dom = Document::fromHtml( - ' - - - - - - - ', - Options::DEFAULTS - ); - - $actual_error_codes = []; - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$actual_error_codes ) { - $actual_error_codes[] = $error['code']; - return true; - }, - ] - ); - - $spec = $this->get_private_property( $sanitizer, 'style_custom_cdata_spec' ); - $spec['css_spec']['declaration'][] = 'color'; - $this->set_private_property( $sanitizer, 'style_custom_cdata_spec', $spec ); - - $sanitizer->sanitize(); - - $this->assertEquals( - [ AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY ], - $actual_error_codes - ); - - $this->assertEquals( - [ - 'body{color:black}', - ], - $sanitizer->get_stylesheets() - ); - } - - /** - * Test that tree shaking and CSS limits are disabled when requested. - */ - public function test_tree_shaking_disabled() { - $dom = Document::fromHtml( - sprintf( - ' - - - - - - -
        - -
        - - - ', - str_repeat( 'a', 75001 ) - ), - Options::DEFAULTS - ); - - $args = [ - 'use_document_element' => true, - 'skip_tree_shaking' => true, - 'allow_excessive_css' => true, - ]; - - $sanitizer = new AMP_Style_Sanitizer( $dom, $args ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom, $args ); - $validating_sanitizer->sanitize(); - - $actual_stylesheets = array_values( array_filter( $sanitizer->get_stylesheets() ) ); - - $this->assertCount( 2, $actual_stylesheets ); - $this->assertStringStartsWith( '.selective-refresh-container{', $actual_stylesheets[0] ); - $this->assertStringStartsWith( '.my-partial{', $actual_stylesheets[1] ); - $this->assertGreaterThan( 75000, strlen( implode( '', $actual_stylesheets ) ) ); - - ValidationExemption::is_px_verified_for_node( $dom->xpath->query( '//style[ @amp-custom ]' )->item( 0 ) ); - } - - /** @return array */ - public function get_data_to_test_transform_important_qualifiers_arg() { - $html = ' - - - - - - - -
        -
        -
        - - - '; - - $html_important_keyframes = ' - - - - - - - '; - - return [ - 'transform' => [ - true, // transform_important_qualifiers - true, // should_sanitize - $html, - [ - '.foo:not(#_#_#_#_#_#_#_){color:red}', - '.foo[data-amp-original-style*="blue"]:not(#_#_#_#_#_#_#_){outline:solid 2px green}', - '.amp-wp-9605c4d:not(#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_){background:blue}', - '.amp-wp-32bb249:not(#_#_#_#_#_){background:red}', - ], - '$markup"; - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $sanitizer_classes = amp_get_content_sanitizers(); - foreach ( $sanitizers_args as $sanitizer_class => $sanitizer_args ) { - $sanitizer_classes[ $sanitizer_class ] = array_merge( - $sanitizer_classes[ $sanitizer_class ], - $sanitizer_args - ); - } - - $sanitized = AMP_Content_Sanitizer::sanitize_document( - $dom, - $sanitizer_classes, - [ - 'use_document_element' => true, - ] - ); - - $stylesheets = array_values( $sanitized['stylesheets'] ); - $this->assertEquals( $output, $stylesheets[0] ); - } - - /** - * Provide data for attribute selector test. - * - * @return array Data. - */ - public function get_attribute_selector_data() { - return [ - 'type_attribute' => [ - '', - // All selectors remain because only the existence of the attribute is examined. - [ - '[type="button"]' => true, - '[type*="reset"]' => true, - '[type^="submit"]' => true, - '[type$="button"]' => true, - ], - ], - 'tabindex_attribute' => [ - '', - // The div[tabindex] is removed because there is no div. The span[tabindex^=2] remains because value is not considered. - [ - 'div[tabindex]' => false, - 'span[tabindex]' => true, - 'span[tabindex=-1]' => true, - 'span[tabindex^=2]' => true, - ], - ], - 'href_attribute' => [ - 'Foo', - [ - 'a[href^=http]:after' => true, - 'a[href^="#"]:after' => true, - ], - ], - 'hidden_attribute' => [ - 'not hidden', - // Only div[hidden] should be removed because there is no div element; the other [hidden] selectors remain because it can be dynamically added. - [ - 'span[hidden]' => true, - '[hidden]' => true, - 'div[hidden]' => false, - 'span:not([hidden])' => true, - ], - ], - 'selected_readonly_disabled_multiple_autofocus_required' => [ - '', - [ - '[autofocus]' => true, - '[checked]' => true, - '[disabled]' => true, - '[multiple]' => true, - '[readonly]' => true, - '[required]' => true, - '[selected]' => true, - ], - ], - 'open_attribute' => [ - '
        MoreDetails
        ', - [ - '[open]' => true, - 'amp-lightbox[open]' => false, - 'details[open]' => true, - ], - ], - 'media_attributes' => [ - '', - [ - '[loop]' => true, - '[controls]' => true, - ], - ], - 'escaped_char_class_name' => [ - '
        ', - [ - '.lg' => false, - '.hover' => false, - '.hover\:bg-blue' => true, - '.lg\:w-full' => true, - '.lg\:w-full:hover' => true, - '.lg\:w-medium' => false, - '.\@\@\@' => true, - '.\@\@\@\@' => false, - '.w-1\/3' => true, - '.w-2\/3' => false, - ], - ], - 'toggle_class' => [ - implode( - '', - [ - '
        ', - '', - '', - '', - '', - '', - '', - ] - ), - [ - '.expanded' => true, - '.clicked' => true, - '.tapped' => true, - '.pressed' => true, - '.im-pressed' => true, - '.touch\:ed' => true, - '.exploded' => false, - '.stateful' => false, - ], - ], - 'bento_accordion_with_id' => [ - ' - -
        -

        Section 1

        -
        Content in section 1.
        -
        -
        - ', - [ - '#my-accordion' => true, - 'amp-accordion#my-accordion' => true, - ], - ], - 'amp_replacement_elements_with_id' => [ - ' - - - - - -
        -
        - ', - [ - '#my-img' => true, - 'amp-img#my-img' => true, - '#my-audio' => true, - 'amp-audio#my-audio' => true, - '#my-video' => true, - 'amp-video#my-video' => true, - '#my-iframe' => true, - 'amp-iframe#my-iframe' => true, - '#my-object' => true, - 'amp-google-document-embed#my-object' => true, - '#my-playbuzz' => true, - 'amp-playbuzz#my-playbuzz' => true, - '#my-o2' => true, - 'amp-o2-player#my-o2' => true, - // @todo Embeds? - ], - ], - ]; - } - - /** - * Test attribute selector tree shaking. - * - * @dataProvider get_attribute_selector_data - * @covers AMP_Base_Sanitizer::get_selector_conversion_mapping() - * @covers AMP_Base_Sanitizer::has_light_shadow_dom() - * - * @param string $markup Source HTML markup. - * @param array $selectors Mapping of selectors to whether they are expected. - */ - public function test_attribute_selector( $markup, $selectors ) { - $style = implode( - '', - array_map( - static function ( $selector ) { - return sprintf( '%s{ color: red; }', $selector ); - }, - array_keys( $selectors ) - ) - ); - - // The toggling of the 'add_noscript_fallback' arg is to catch a bizzare PHP DOM issue whereby if you replace - // an element in a Document, and that replaced element had an ID, the element will still be returned by - // getElementById even though it is no longer inside of the document. When add_noscript_fallback is false, - // then the original img (for example) will not be inside of the document (?). - foreach ( [ true, false ] as $add_noscript_fallback ) { - $html = "$markup"; - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $sanitized = AMP_Content_Sanitizer::sanitize_document( - $dom, - amp_get_content_sanitizers(), - array_merge( - compact( 'add_noscript_fallback' ), - [ 'use_document_element' => true ] - ) - ); - - $stylesheets = array_values( $sanitized['stylesheets'] ); - - $actual_selectors = array_values( array_filter( preg_split( '/{.+?}/s', $stylesheets[0] ) ) ); - $expected_selectors = array_keys( array_filter( $selectors ) ); - - $this->assertEqualSets( $expected_selectors, $actual_selectors, sprintf( 'add_noscript_fallback is %s', wp_json_encode( $add_noscript_fallback ) ) ); - } - } - - /** - * Data for testing CSS hack removal. - * - * @return array - */ - public function get_amp_css_hacks_data() { - return [ - [ - '.selector { !property: value; }', - ], - [ - '.selector { $property: value; }', - ], - [ - '.selector { &property: value; }', - ], - [ - '.selector { *property: value; }', - ], - [ - '.selector { )property: value; }', - ], - [ - '.selector { =property: value; }', - ], - [ - '.selector { %property: value; }', - ], - [ - '.selector { +property: value; }', - ], - [ - '.selector { @property: value; }', - ], - [ - '.selector { ,property: value; }', - ], - [ - '.selector { .property: value; }', - ], - [ - '.selector { /property: value; }', - ], - [ - '.selector { `property: value; }', - ], - [ - '.selector { ]property: value; }', - ], - [ - '.selector { #property: value; }', - ], - [ - '.selector { ~property: value; }', - ], - [ - '.selector { ?property: value; }', - ], - [ - '.selector { :property: value; }', - ], - [ - '.selector { |property: value; }', - ], - [ - '_::selection, .selector:not([attr*=\'\']) {}', - ], - [ - ':root .selector {}', - ], - [ - 'body:last-child .selector {}', - ], - [ - 'body:nth-of-type(1) .selector {}', - ], - [ - 'body:first-of-type .selector {}', - ], - [ - '.selector:not([attr*=\'\']) {}', - ], - [ - '.selector:not(*:root) {}', - ], - [ - '.selector:not(*:root) {}', - ], - [ - 'body:empty .selector {}', - ], - [ - 'body:last-child .selector, x:-moz-any-link {}', - ], - [ - 'body:last-child .selector, x:-moz-any-link, x:default {}', - ], - [ - 'body:not(:-moz-handler-blocked) .selector {}', - ], - [ - '_::-moz-progress-bar, body:last-child .selector {}', - ], - [ - '_::-moz-range-track, body:last-child .selector {}', - ], - [ - '_:-moz-tree-row(hover), .selector {}', - ], - [ - '_::selection, .selector:not([attr*=\'\']) {}', - ], - [ - '* html .selector {}', - ], - [ - '.unused-class.selector {}', - ], - [ - 'html > body .selector {}', - ], - [ - '.selector, {}', - ], - [ - '*:first-child+html .selector {}', - ], - [ - '.selector, x:-IE7 {}', - ], - [ - '*+html .selector {}', - ], - [ - 'body*.selector {}', - ], - [ - '.selector\ {}', - ], - [ - 'html > /**/ body .selector {}', - ], - [ - 'head ~ /**/ body .selector {}', - ], - [ - '_::selection, .selector:not([attr*=\'\']) {}', - ], - [ - ':root .selector {}', - ], - [ - 'body:last-child .selector {}', - ], - [ - 'body:nth-of-type(1) .selector {}', - ], - [ - 'body:first-of-type .selector {}', - ], - [ - '.selector:not([attr*=\'\']) {}', - ], - [ - 'body { -0-transition: all .3s ease-in-out; }', - ], - [ - 'body { 4-o-transition: all .3s ease-in-out; }', - ], - ]; - } - - /** - * Test removal of IE and Other Browser CSS Hacks - * - * @dataProvider get_amp_css_hacks_data - * @param string $input Hack input CSS rule. - */ - public function test_browser_css_hacks( $input ) { - $html = ""; - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $error_codes = []; - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $actual_stylesheets = array_values( $sanitizer->get_stylesheets() ); - $this->assertEmpty( $actual_stylesheets[0] ); - } - - /** - * Test handling of stylesheets with @font-face that have data: url source. - * - * Also confirm that class-based tree-shaking is working. - * - * @covers AMP_Style_Sanitizer::process_font_face_at_rule() - */ - public function test_font_data_url_handling() { - $html = ''; - $html .= ''; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $html .= ''; - - // Test with tree-shaking. - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - $error_codes = []; - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $this->assertEquals( [], $error_codes ); - $actual_stylesheets = array_values( $sanitizer->get_stylesheets() ); - $this->assertCount( 1, $actual_stylesheets ); - $this->assertStringContainsString( 'dashicons.woff") format("woff")', $actual_stylesheets[0] ); - $this->assertStringNotContainsString( 'data:application/font-woff;', $actual_stylesheets[0] ); - $this->assertStringContainsString( '.dashicons{', $actual_stylesheets[0] ); - $this->assertStringContainsString( '.dashicons-admin-appearance:before{', $actual_stylesheets[0] ); - $this->assertStringNotContainsString( '.dashicons-format-chat:before', $actual_stylesheets[0] ); - } - - /** - * Test handling of stylesheets with @font-face that have data: url source. - * - * Also confirm that class-based tree-shaking is working. - * - * @link https://github.com/ampproject/amp-wp/pull/2079 - * - * @covers AMP_Style_Sanitizer::process_font_face_at_rule() - */ - public function test_font_data_url_handling_without_file_sources() { - $theme = new WP_Theme( 'twentynineteen', ABSPATH . 'wp-content/themes' ); - if ( $theme->errors() ) { - $this->markTestSkipped( 'Twenty Nineteen is not installed.' ); - } - - $html = ''; - $html .= sprintf( '', esc_url( $theme->get_stylesheet_directory_uri() . '/style.css' ) ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $html .= ''; - $html .= ''; - $html .= ''; - - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - $error_codes = []; - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - ] - ); - $sanitizer->sanitize(); - $this->assertEquals( [], $error_codes ); - $actual_stylesheets = array_values( $sanitizer->get_stylesheets() ); - $this->assertCount( 3, $actual_stylesheets ); - - // Check font included in theme. - $this->assertStringContainsString( '@font-face{font-family:"NonBreakingSpaceOverride";', $actual_stylesheets[0] ); - $this->assertStringContainsString( 'format("woff2")', $actual_stylesheets[0] ); - $this->assertStringContainsString( 'format("woff")', $actual_stylesheets[0] ); - $this->assertStringNotContainsString( 'data:', $actual_stylesheets[0] ); - $this->assertStringContainsString( 'fonts/NonBreakingSpaceOverride.woff2', $actual_stylesheets[0] ); - $this->assertStringContainsString( 'fonts/NonBreakingSpaceOverride.woff', $actual_stylesheets[0] ); - $this->assertStringContainsString( 'font-display:optional', $actual_stylesheets[0] ); - - // Check font not included in theme, but included in plugin. - $this->assertStringContainsString( '@font-face{font-family:"Genericons";', $actual_stylesheets[1] ); - $this->assertStringContainsString( 'format("woff")', $actual_stylesheets[1] ); - $this->assertStringNotContainsString( 'data:', $actual_stylesheets[1] ); - $this->assertStringContainsString( 'assets/fonts/genericons.woff', $actual_stylesheets[1] ); - $this->assertStringContainsString( 'font-display:block', $actual_stylesheets[1] ); - - // Check font not included anywhere, so must remain inline. - $this->assertStringContainsString( '@font-face{font-family:"Custom";', $actual_stylesheets[2] ); - $this->assertStringContainsString( 'url("data:application/x-font-woff;charset=utf-8;base64,d09GRgABAAA")', $actual_stylesheets[2] ); - $this->assertStringContainsString( 'format("woff")', $actual_stylesheets[2] ); - $this->assertStringNotContainsString( 'font-display:', $actual_stylesheets[2] ); - } - - /** @return array */ - public function get_data_to_test_font_files_preloading() { - return [ - 'twentynineteen' => [ - 'theme_slug' => 'twentynineteen', - 'expected_urls' => [], // Twenty Nineteen theme uses "NonBreakingSpaceOverride" font which should use 'font-display:optional' property, thus should not be preloaded. - ], - 'twentytwenty' => [ - 'theme_slug' => 'twentytwenty', - 'expected_urls' => [], // Twenty Twenty theme uses "Inter var" and "NonBreakingSpaceOverride" font which should use 'font-display:optional' property, thus should not be preloaded. - ], - 'twentytwentyone' => [ - 'theme_slug' => 'twentytwentyone', - 'expected_urls' => [], // Twenty Twenty-One theme uses system font stack, no extra fonts are enqueued. - ], - 'custom_swap' => [ - 'theme_slug' => '', - 'expected_urls' => [ - '/fonts/OpenSans-Regular-webfont.woff2', - ], - 'html' => '', - ], - 'custom_optional' => [ - 'theme_slug' => '', - 'expected_urls' => [], - 'html' => '', - ], - 'custom_combined' => [ - 'theme_slug' => '', - 'expected_urls' => [ - '/fonts/OpenSans-Regular-webfont.woff2', - '/fonts/Lato-Regular-webfont.woff2', - ], - 'html' => '', - ], - 'custom_inlined' => [ - 'theme_slug' => '', - 'expected_urls' => [], // No preload link should be present because the data: URL was not converted into an external link. - 'html' => '', - ], - ]; - } - - /** - * Test that font files are preloaded with element. - * - * @dataProvider get_data_to_test_font_files_preloading - * @covers AMP_Style_Sanitizer::process_font_face_at_rule() - */ - public function test_font_files_preloading( $theme_slug, $expected_urls, $html = '' ) { - if ( ! empty( $theme_slug ) ) { - $theme = new WP_Theme( $theme_slug, ABSPATH . 'wp-content/themes' ); - if ( $theme->errors() ) { - $this->markTestSkipped( $theme->errors()->get_error_message() ); - } - - $html = ''; - $html .= sprintf( '', esc_url( $theme->get_stylesheet_directory_uri() . '/style.css' ) ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $html .= ''; - } - - // Do the assertions twice in order to ensure that preloads are still added when the CSS is cached. - foreach ( [ 'false', 'true' ] as $is_cached ) { - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - $error_codes = []; - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - ] - ); - $sanitizer->sanitize(); - $this->assertEquals( [], $error_codes, "Is cached: $is_cached" ); - - $link_elements = $dom->getElementsByTagName( 'link' ); - $link_elements_count = $link_elements->length; - - $actual_urls = array_map( - static function ( Element $link_element ) { - return $link_element->getAttribute( 'href' ); - }, - iterator_to_array( $link_elements ) - ); - - $this->assertEqualSets( $expected_urls, $actual_urls, "Is cached: $is_cached" ); - - for ( $i = 0; $i < $link_elements_count; $i ++ ) { - $this->assertStringEndsWith( - $expected_urls[ $i ], - $link_elements->item( $i )->getAttribute( 'href' ) - ); - $this->assertEquals( $link_elements->item( $i )->getAttribute( 'rel' ), 'preload' ); - $this->assertEquals( $link_elements->item( $i )->getAttribute( 'as' ), 'font' ); - $this->assertEquals( $link_elements->item( $i )->getAttribute( 'crossorigin' ), '' ); - } - } - } - - /** - * Test that auto-removal (tree shaking) does not remove rules for classes mentioned in class and [class] attributes. - * - * @covers AMP_Style_Sanitizer::get_used_class_names() - * @covers AMP_Style_Sanitizer::finalize_stylesheet_group() - */ - public function test_class_amp_bind_preservation() { - ob_start(); - ?> - - - - - - - - - - - - - - - - - - - - - - true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $this->assertEquals( [], $error_codes ); - $actual_stylesheets = array_values( $sanitizer->get_stylesheets() ); - $this->assertEquals( - [ - '.sidebar1{display:none}', - '.sidebar1.expanded{display:block}', - '.sidebar1.hidden{visibility:hidden}', - '.sidebar2{visibility:hidden}', - '.sidebar2.visible,.sidebar2.shown{display:block}', - '.sidebar3.open,.sidebar3.abierto{display:block}', - '.sidebar3.cerrado{display:none}', - '', - ], - $actual_stylesheets - ); - } - - /** @return array */ - public function get_data_to_test_dark_mode_classes() { - return [ - 'default' => [ - null, - [ - 'body.amp-dark-mode{background:black}', - '', - ], - ], - 'custom' => [ - 'is-dark-theme', - [ - '', - 'body.is-dark-theme{background:black}', - ], - ], - ]; - } - - /** - * Test that dark mode classes are not stripped out. - * - * @dataProvider get_data_to_test_dark_mode_classes - * - * @covers AMP_Style_Sanitizer::get_used_class_names() - * @covers AMP_Style_Sanitizer::finalize_stylesheet_group() - * - * @param null|string $dark_mode_class - * @param string[] $expected_stylesheets - */ - public function test_dark_mode_classes( $dark_mode_class, $expected_stylesheets ) { - ob_start(); - ?> - - - - - - - - data-prefers-dark-mode-class="" - - > - - - true ] - ); - $sanitizer->sanitize(); - $this->assertEquals( - $expected_stylesheets, - array_values( $sanitizer->get_stylesheets() ) - ); - } - - /** - * Test that auto-removal is performed and that excessive CSS will be removed entirely. - * - * @covers AMP_Style_Sanitizer::finalize_stylesheet_group() - */ - public function test_large_custom_css_and_rule_removal() { - $custom_max_size = null; - foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'style' ) as $spec_rule ) { - if ( isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) && 'style amp-custom' === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) { - $custom_max_size = $spec_rule[ AMP_Rule_Spec::CDATA ]['max_bytes']; - break; - } - } - $this->assertNotNull( $custom_max_size ); - - $html = ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ' - - '; - $html .= '...'; - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $error_codes = []; - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - - $this->assertEquals( - [ - '.b{color:blue}', - '#exists{color:white}', - 'span{color:white}', - '@font-face{font-family:"Open Sans";src:url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2")}', - '.b{background:lightblue}', - '@media screen and (max-width: 1000px){@supports (display: grid){.b::before{content:"@media screen and (max-width: 1000px) {"}.b::after{content:"}"}}}@media print{@media print{@media print{.b{color:blue}}}}@media screen and (min-width: 750px) and (max-width: 999px){.b::before{content:"@media screen and (max-width: 1000px) {}";content:"@media screen and (max-width: 1000px) {}"}}', - ], - array_values( $sanitizer->get_stylesheets() ) - ); - - $this->assertEquals( - [ AMP_Style_Sanitizer::STYLESHEET_TOO_LONG ], - $error_codes - ); - } - - /** - * Test handling of stylesheets with relative background-image URLs. - * - * @covers AMP_Style_Sanitizer::real_path_urls() - * @covers AMP_Style_Sanitizer::unrelativize_path() - * @covers AMP_Style_Sanitizer::reconstruct_url() - */ - public function test_relative_background_url_handling() { - $html = ''; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - ] - ); - $sanitizer->sanitize(); - $dom->saveHTML( $dom->documentElement ); - $actual_stylesheets = array_values( $sanitizer->get_stylesheets() ); - $this->assertCount( 1, $actual_stylesheets ); - $stylesheet = $actual_stylesheets[0]; - - $this->assertStringNotContainsString( '../images/spinner', $stylesheet ); - $this->assertStringContainsString( sprintf( '.spinner{background-image:url("%s")', admin_url( 'images/spinner-2x.gif' ) ), $stylesheet ); - } - - /** - * Return stylesheets that are to be fetched over HTTP. - */ - public function get_http_stylesheets() { - return [ - 'external_file' => [ - 'https://stylesheets.example.com/style.css', - 'text/css', - 'html { background-color: lightblue; } body::after { content:"This body has no ." }', - 'html{background-color:lightblue}body::after{content:"This body has no <\/style>."}', - [], - ], - 'external_file_schemeless' => [ - '//stylesheets.example.com/style.css', - 'text/css', - 'html { background-color: lightblue; background-image: url("data:image/svg+xml;utf8," ); }', - 'html{background-color:lightblue;background-image:url("data:image/svg+xml;utf8,")}', - [], - ], - 'dynamic_file' => [ - set_url_scheme( add_query_arg( 'action', 'kirki-styles', home_url() ), 'http' ), - 'text/css', - 'body{color:red}', - 'body{color:red}', - [], - ], - 'local_css_file_outside_normal_dirs' => [ - home_url( '/style.css' ), - 'text/css', - 'body{color:green}', - 'body{color:green}', - [], - ], - 'not_css_file' => [ - home_url( '/this.is.not.css' ), - 'image/jpeg', - 'JPEG...', - null, - [ AMP_Style_Sanitizer::STYLESHEET_FETCH_ERROR ], - ], - ]; - } - - /** - * Test handling external stylesheet. - * - * @dataProvider get_http_stylesheets - * @covers AMP_Style_Sanitizer::process_link_element() - * @covers AMP_Style_Sanitizer::fetch_external_stylesheet() - * - * @param string $href Request URL. - * @param string $content_type Content type. - * @param string $response_body Response body. - * @param string $expected_stylesheet Expected stylesheet. - * @param array $expected_error_codes Error codes when getting the stylesheet. - */ - public function test_external_stylesheet_handling( $href, $content_type, $response_body, $expected_stylesheet, $expected_error_codes ) { - $request_count = 0; - add_filter( - 'pre_http_request', - function( $preempt, $request, $url ) use ( $href, &$request_count, $content_type, $response_body ) { - $this->assertMatchesRegularExpression( '#^https?://#', $url ); - if ( set_url_scheme( $url, 'https' ) === set_url_scheme( $href, 'https' ) ) { - $request_count++; - $preempt = [ - 'response' => [ - 'code' => 200, - ], - 'headers' => [ - 'content-type' => $content_type, - ], - 'body' => $response_body, - ]; - } - return $preempt; - }, - 10, - 3 - ); - - $sanitize_and_get_stylesheets = static function() use ( $href ) { - $html = sprintf( '', esc_url( $href ) ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $found_error_codes = []; - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$found_error_codes ) { - $found_error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $dom->saveHTML( $dom->documentElement ); - return [ $found_error_codes, array_values( $sanitizer->get_stylesheets() ) ]; - }; - - $this->assertEquals( 0, $request_count ); - - list( $found_error_codes, $actual_stylesheets ) = $sanitize_and_get_stylesheets(); - $this->assertEquals( 1, $request_count, 'Expected HTTP request.' ); - - if ( empty( $expected_error_codes ) ) { - $this->assertCount( 1, $actual_stylesheets ); - $this->assertEquals( $expected_stylesheet, $actual_stylesheets[0] ); - } else { - $this->assertEquals( $expected_error_codes, $found_error_codes ); - $this->assertCount( 0, $actual_stylesheets ); - } - - $sanitize_and_get_stylesheets(); - $this->assertEquals( 1, $request_count, 'Expected HTTP request to be cached.' ); - } - - /** - * Test cache-control support when retrieving external stylesheets. - * - * @covers AMP_Style_Sanitizer::process_link_element() - * @covers AMP_Style_Sanitizer::fetch_external_stylesheet() - */ - public function test_external_stylesheet_cache_control() { - $request_count = 0; - $href = 'https://www.example.com/styles.css'; - $response_body = 'body{color:red}'; - $headers = [ - 'content-type' => 'text/css', - 'cache-control' => 'max-age=' . ( YEAR_IN_SECONDS + MONTH_IN_SECONDS ), - ]; - $status_code = 200; - - add_filter( - 'pre_http_request', - function( $preempt, $request, $url ) use ( $href, &$request_count, $response_body, $headers, $status_code ) { - $this->assertMatchesRegularExpression( '#^https?://#', $url ); - if ( set_url_scheme( $url, 'https' ) === set_url_scheme( $href, 'https' ) ) { - $request_count++; - $preempt = [ - 'response' => [ - 'code' => $status_code, - ], - 'headers' => $headers, - 'body' => $response_body, - ]; - } - return $preempt; - }, - 10, - 3 - ); - - $sanitize_and_get_stylesheets = static function() use ( $href ) { - $html = sprintf( '', esc_url( $href ) ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $found_error_codes = []; - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$found_error_codes ) { - $found_error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $dom->saveHTML( $dom->documentElement ); - return [ $found_error_codes, array_values( $sanitizer->get_stylesheets() ) ]; - }; - - $this->assertEquals( 0, $request_count ); - - list( $found_error_codes, $actual_stylesheets ) = $sanitize_and_get_stylesheets(); - $this->assertEmpty( $found_error_codes ); - $this->assertEquals( 1, $request_count, 'Expected HTTP request.' ); - - $this->assertCount( 1, $actual_stylesheets ); - $this->assertEquals( $response_body, $actual_stylesheets[0] ); - - $cache_key = CachedRemoteGetRequest::TRANSIENT_PREFIX . md5( CachedRemoteGetRequest::class . $href ); - - // Verify that the transients are not polluting the autoloaded options. - $autoloaded_options = wp_load_alloptions(); - $this->assertArrayNotHasKey( "_transient_{$cache_key}", $autoloaded_options ); - - $transient = get_transient( $cache_key ); - $this->assertNotFalse( $transient ); - - /** - * Cached response. - * - * @var CachedResponse - */ - $cached_response = unserialize( $transient ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize - $this->assertInstanceOf( CachedResponse::class, $cached_response ); - - $this->assertEquals( $response_body, $cached_response->get_body() ); - $this->assertEquals( $headers, $cached_response->get_headers() ); - $this->assertEquals( $status_code, $cached_response->get_status_code() ); - - $expiry = $cached_response->get_expiry(); - $this->assertGreaterThan( ( new DateTimeImmutable( '+ 1 year' ) )->getTimestamp(), $expiry->getTimestamp() ); - - $sanitize_and_get_stylesheets(); - $this->assertEquals( 1, $request_count, 'Expected HTTP request to be cached.' ); - } - - /** - * Data for test_external_stylesheet() - * - * @return array - */ - public function get_external_stylesheet_data() { - return [ - 'successful' => [ - 'style_url' => 'https://www.example.com/styles.css', - 'http_response' => [ - 'body' => 'body { color: #fff }', - 'code' => 200, - 'headers' => [ - 'cache-control' => 'max-age=1441', - 'content-type' => 'text/css', - ], - ], - 'expected_styles' => [ 'body{color:#fff}' ], - 'expected_errors' => [], - 'expected_cached_response' => new CachedResponse( - 'body { color: #fff }', - [ - 'cache-control' => 'max-age=1441', - 'content-type' => 'text/css', - ], - 200, - new DateTimeImmutable( '+ 1441 seconds' ) - ), - ], - 'failed' => [ - 'style_url' => 'https://www.example.com/not-found/styles.css', - 'http_response' => [ - 'body' => 'Not Found!', - 'code' => 404, - 'headers' => [ - 'content-type' => 'text/html', - ], - ], - 'expected_styles' => [], - 'expected_errors' => [ AMP_Style_Sanitizer::STYLESHEET_FETCH_ERROR ], - 'expected_cached_response' => new CachedResponse( - FailedToGetFromRemoteUrl::withHttpStatus( 'https://www.example.com/not-found/styles.css', 404 )->getMessage(), - [], - 404, - new DateTimeImmutable( '+ ' . DAY_IN_SECONDS . ' seconds' ) - ), - ], - ]; - } - - /** - * Test that external stylesheets fetches are cached. - * - * @dataProvider get_external_stylesheet_data - * @covers AMP_Style_Sanitizer::process_link_element() - * - * @param string $style_url Stylesheet URL. - * @param array $http_response Mocked HTTP response. - * @param array $expected_styles Expected minified stylesheets. - * @param array $expected_errors Expected error codes. - * @param CachedResponse $expected_cached_response Expected cache response. - */ - public function test_external_stylesheet( $style_url, $http_response, $expected_styles, $expected_errors, $expected_cached_response ) { - $request_count = 0; - - add_filter( - 'pre_http_request', - function( $preempt, $request, $url ) use ( $style_url, $http_response, &$request_count ) { - $this->assertMatchesRegularExpression( '#^https?://#', $url ); - if ( set_url_scheme( $url, 'https' ) === set_url_scheme( $style_url, 'https' ) ) { - $request_count++; - $preempt = [ - 'response' => [ - 'code' => $http_response['code'], - ], - 'headers' => $http_response['headers'], - 'body' => $http_response['body'], - ]; - } - return $preempt; - }, - 10, - 3 - ); - - $sanitize_and_get_stylesheets = static function( $css_url ) { - $html = sprintf( '', esc_url( $css_url ) ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $found_error_codes = []; - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$found_error_codes ) { - $found_error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $dom->saveHTML( $dom->documentElement ); - return [ $found_error_codes, array_values( $sanitizer->get_stylesheets() ) ]; - }; - - $this->assertEquals( 0, $request_count ); - - list( $found_error_codes, $actual_stylesheets ) = $sanitize_and_get_stylesheets( $style_url ); - - $this->assertEquals( $expected_errors, $found_error_codes ); - $this->assertEquals( $expected_styles, $actual_stylesheets ); - $this->assertEquals( 1, $request_count, 'Expected HTTP request.' ); - - $cache_key = CachedRemoteGetRequest::TRANSIENT_PREFIX . md5( CachedRemoteGetRequest::class . $style_url ); - $transient = get_transient( $cache_key ); - $this->assertNotFalse( $transient ); - - /** - * Cached response. - * - * @var CachedResponse - */ - $cached_response = unserialize( $transient ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize - $this->assertInstanceOf( CachedResponse::class, $cached_response ); - - $this->assertEquals( $expected_cached_response->get_body(), $cached_response->get_body() ); - $this->assertEquals( $expected_cached_response->get_headers(), $cached_response->get_headers() ); - $this->assertEquals( $expected_cached_response->get_status_code(), $cached_response->get_status_code() ); - - $expiry = $cached_response->get_expiry(); - $this->assertEquals( $cached_response->get_expiry()->getTimestamp(), $expiry->getTimestamp() ); - - $sanitize_and_get_stylesheets( $style_url ); - $this->assertEquals( 1, $request_count, 'Expected HTTP request to be cached.' ); - } - - /** - * Get amp-keyframe styles. - * - * @return array - */ - public function get_keyframe_data() { - $keyframes_max_size = null; - foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'style' ) as $spec_rule ) { - if ( isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) && 'style[amp-keyframes]' === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) { - $keyframes_max_size = $spec_rule[ AMP_Rule_Spec::CDATA ]['max_bytes']; - break; - } - } - $this->assertNotNull( $keyframes_max_size ); - - return [ - 'style_amp_keyframes' => [ - '', - '', - [], - ], - - 'style_amp_keyframes_max_overflow' => [ - '', - '', - [ AMP_Style_Sanitizer::STYLESHEET_TOO_LONG ], - ], - - 'style_amp_keyframes_last_child' => [ - 'before between as after', - 'before between as after', - [], - ], - - 'denylisted_and_allowlisted_keyframe_properties' => [ - '', - '', - array_fill( 0, 3, AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY ), - ], - - 'style_amp_keyframes_with_disallowed_rules' => [ - '', - '', - [ AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_DECLARATION, AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_IMPORTANT, AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_AT_RULE ], - ], - - 'style_amp_keyframes_turn_unit' => [ - '', - '', - [], - ], - - 'keyframes_with_non_declaration_block' => [ - '', - '', - [ AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_DECLARATION ], - ], - ]; - } - - /** - * Test amp-keyframe styles. - * - * @covers AMP_Style_Sanitizer::process_css_keyframes() - * @dataProvider get_keyframe_data - * @param string $source Markup to process. - * @param string $expected The markup to expect. - * @param array $expected_errors Expected error codes. - */ - public function test_keyframe_sanitizer( $source, $expected = null, $expected_errors = [] ) { - $expected = isset( $expected ) ? $expected : $source; - $expected = preg_replace( '#(?=)#', "\n\n/*# sourceURL=amp-keyframes.css */", $expected ); - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $error_codes = []; - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ] - ); - $sanitizer->sanitize(); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $content = preg_replace( '#\s+(?=@keyframes)#', '', $content ); - $content = preg_replace( '#\s+(?=)#', '', $content ); - $content = preg_replace( '/(?<=>)\s+(?=<)/', '', $content ); - $this->assertEquals( $expected, $content ); - - $this->assertEquals( $expected_errors, $error_codes ); - } - - /** - * Get stylesheet URLs. - * - * @returns array Stylesheet URL data. - */ - public function get_stylesheet_urls() { - - // Make sure core-bundled themes are registered. - if ( WP_CONTENT_DIR !== ABSPATH . 'wp-content/themes' ) { - register_theme_directory( ABSPATH . 'wp-content/themes' ); - } - - $theme = new WP_Theme( 'twentyseventeen', ABSPATH . 'wp-content/themes' ); - - return [ - 'url_without_path' => [ - 'https://example.com', - null, - AMP_Style_Sanitizer::STYLESHEET_URL_SYNTAX_ERROR, - ], - 'url_not_string' => [ - false, - null, - AMP_Style_Sanitizer::STYLESHEET_URL_SYNTAX_ERROR, - ], - 'theme_stylesheet_without_host' => [ - '/wp-content/themes/twentyseventeen/style.css', - $theme->get_stylesheet_directory() . '/style.css', - ], - 'theme_stylesheet_with_host' => [ - $theme->get_stylesheet_directory_uri() . '/style.css', - $theme->get_stylesheet_directory() . '/style.css', - ], - 'theme_stylesheet_with_relative_paths' => [ - $theme->get_stylesheet_directory_uri() . '/foo/./bar/baz/../../../style.css', - $theme->get_stylesheet_directory() . '/style.css', - ], - 'theme_stylesheet_with_trailing_dot' => [ - $theme->get_stylesheet_directory_uri() . '/foo./bar.css', - null, - AMP_Style_Sanitizer::STYLESHEET_FILE_PATH_NOT_FOUND, - ], - 'dashicons_without_host' => [ - '/wp-includes/css/dashicons.css', - ABSPATH . WPINC . '/css/dashicons.css', - ], - 'dashicons_with_host' => [ - includes_url( 'css/dashicons.css' ), - ABSPATH . WPINC . '/css/dashicons.css', - ], - 'admin_without_host' => [ - '/wp-admin/css/common.css', - ABSPATH . 'wp-admin/css/common.css', - ], - 'admin_with_host' => [ - admin_url( 'css/common.css' ), - ABSPATH . 'wp-admin/css/common.css', - ], - 'admin_with_host_https' => [ - set_url_scheme( admin_url( 'css/common.css' ), 'https' ), - ABSPATH . 'wp-admin/css/common.css', - ], - 'admin_with_host_http' => [ - set_url_scheme( admin_url( 'css/common.css' ), 'http' ), - ABSPATH . 'wp-admin/css/common.css', - ], - 'admin_with_no_host_scheme' => [ - preg_replace( '#^\w+:(?=//)#', '', admin_url( 'css/common.css' ) ), - ABSPATH . 'wp-admin/css/common.css', - ], - 'amp_disallowed_file_extension' => [ - content_url( 'themes/twentyseventeen/index.php' ), - null, - AMP_Style_Sanitizer::STYLESHEET_DISALLOWED_FILE_EXT, - ], - 'amp_file_path_not_found' => [ - content_url( 'themes/twentyseventeen/404.css' ), - null, - AMP_Style_Sanitizer::STYLESHEET_FILE_PATH_NOT_FOUND, - ], - 'amp_file_path_illegal_linux' => [ - content_url( '../../../../../../../../../../../../../../../bad.css' ), - null, - AMP_Style_Sanitizer::STYLESHEET_INVALID_RELATIVE_PATH, - ], - 'amp_file_path_illegal_windows' => [ - content_url( '..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\bad.css' ), - null, - AMP_Style_Sanitizer::STYLESHEET_FILE_PATH_NOT_ALLOWED, - ], - 'amp_file_path_illegal_location' => [ - site_url( 'outside/root.css' ), - null, - AMP_Style_Sanitizer::STYLESHEET_FILE_PATH_NOT_ALLOWED, - ], - 'amp_external_file' => [ - '//s.w.org/wp-includes/css/dashicons.css', - false, - AMP_Style_Sanitizer::STYLESHEET_EXTERNAL_FILE_URL, - ], - ]; - } - - /** - * Tests get_validated_url_file_path. - * - * @dataProvider get_stylesheet_urls - * @covers AMP_Style_Sanitizer::get_validated_url_file_path() - * - * @param string $source Source URL. - * @param string|null $expected Expected path or null if error. - * @param string $error_code Error code. Optional. - */ - public function test_get_validated_url_file_path( $source, $expected, $error_code = null ) { - $dom = Document::fromHtml( '', Options::DEFAULTS ); - - $sanitizer = new AMP_Style_Sanitizer( $dom ); - $actual = $sanitizer->get_validated_url_file_path( $source, [ 'css' ] ); - if ( isset( $error_code ) ) { - $this->assertInstanceOf( 'WP_Error', $actual ); - $this->assertEquals( $error_code, $actual->get_error_code() ); - } else { - $this->assertIsString( $actual ); - $this->assertEquals( $expected, $actual ); - } - } - - /** - * Get data for CSS rules with url() values. - * - * @returns array Data. - */ - public function get_style_rules_with_url_values() { - return [ - 'url_with_spaces' => [ - 'html { background-image:url(url with spaces.png); }', - 'html{background-image:url("urlwithspaces.png")}', - ], - 'data_url_with_spaces' => [ - 'html { background: url(data:image/png; base64, ivborw0kggoaaaansuheugaaacwaaaascamaaaapwqozaaaabgdbtueaalgpc/xhbqaaaafzukdcak7ohokaaaamuexurczmzpf399fx1+bm5mzy9amaaadisurbvdjlvzxbesmgces5/p8/t9furvcrmu73jwlzosgsiizurcjo/ad+eqjjb4hv8bft+idpqocx1wjosbfhh2xssxeiyn3uli/6mnree07uiwjev8ueowds88ly97kqytlijkktuybbruayvh5wohixmpi5we58ek028czwyuqdlkpg1bkb4nnm+veanfhqn1k4+gpt6ugqcvu2h2ovuif/gwufyy8owepdyzsa3avcqpvovvzzz2vtnn2wu8qzvjddeto90gsy9mvlqtgysy231mxry6i2ggqjrty0l8fxcxfcbbhwrsyyaaaaaelftksuqmcc); }', - 'html{background:url("data:image/png;base64,ivborw0kggoaaaansuheugaaacwaaaascamaaaapwqozaaaabgdbtueaalgpc/xhbqaaaafzukdcak7ohokaaaamuexurczmzpf399fx1+bm5mzy9amaaadisurbvdjlvzxbesmgces5/p8/t9furvcrmu73jwlzosgsiizurcjo/ad+eqjjb4hv8bft+idpqocx1wjosbfhh2xssxeiyn3uli/6mnree07uiwjev8ueowds88ly97kqytlijkktuybbruayvh5wohixmpi5we58ek028czwyuqdlkpg1bkb4nnm+veanfhqn1k4+gpt6ugqcvu2h2ovuif/gwufyy8owepdyzsa3avcqpvovvzzz2vtnn2wu8qzvjddeto90gsy9mvlqtgysy231mxry6i2ggqjrty0l8fxcxfcbbhwrsyyaaaaaelftksuqmcc")}', - ], - 'svg_url_with_spaces_in_single_quotes' => [ - 'html { mask-image: url(\'data:image/svg+xml;utf8,\\00003Csvg viewBox=\"0 0 100 100\" xmlns=\"http://www.w3.org/2000/svg\"\\00003E\\00003Ccircle cx=\"50\" cy=\"50\" r=\"50\"/\\00003E\\00003C/svg\\00003E\' ); }', - 'html{mask-image:url("data:image/svg+xml;utf8,")}', - ], - 'svg_url_with_spaces_in_double_quotes' => [ - 'html { mask-image: url( "data:image/svg+xml;utf8,\\00003Csvg viewBox=\'0 0 100 100\' xmlns=\'http://www.w3.org/2000/svg\'\\00003E\\00003Ccircle cx=\'50\' cy=\'50\' r=\'50\'/\\00003E\\00003C/svg\\00003E" ); }', - "html{mask-image:url(\"data:image/svg+xml;utf8,\")}", - ], - 'svg_url_with_encoded_spaces_in_quotes' => [ - 'html { mask-image: url("data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2243%22%20height%3D%2244%22%20viewBox%3D%220%200%2043%2044%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%3Cdefs%3E%3Cpath%20d%3D%22M42.5%2018H22v8.5h11.8C32.7%2031.9%2028.1%2035%2022%2035c-7.2%200-13-5.8-13-13S14.8%209%2022%209c3.1%200%205.9%201.1%208.1%202.9l6.4-6.4C32.6%202.1%2027.6%200%2022%200%209.8%200%200%209.8%200%2022s9.8%2022%2022%2022c11%200%2021-8%2021-22%200-1.3-.2-2.7-.5-4z%22%20id%3D%22a%22%2F%3E%3C%2Fdefs%3E%3Cuse%20fill%3D%22%23FFF%22%20xlink%3Ahref%3D%22%23a%22%20fill-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E"); }', - 'html{mask-image:url("data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2243%22%20height%3D%2244%22%20viewBox%3D%220%200%2043%2044%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%3Cdefs%3E%3Cpath%20d%3D%22M42.5%2018H22v8.5h11.8C32.7%2031.9%2028.1%2035%2022%2035c-7.2%200-13-5.8-13-13S14.8%209%2022%209c3.1%200%205.9%201.1%208.1%202.9l6.4-6.4C32.6%202.1%2027.6%200%2022%200%209.8%200%200%209.8%200%2022s9.8%2022%2022%2022c11%200%2021-8%2021-22%200-1.3-.2-2.7-.5-4z%22%20id%3D%22a%22%2F%3E%3C%2Fdefs%3E%3Cuse%20fill%3D%22%23FFF%22%20xlink%3Ahref%3D%22%23a%22%20fill-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E")}', - ], - 'svg_url_with_encoded_spaces_in_no_quotes' => [ - 'html { mask-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2243%22%20height%3D%2244%22%20viewBox%3D%220%200%2043%2044%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%3Cdefs%3E%3Cpath%20d%3D%22M42.5%2018H22v8.5h11.8C32.7%2031.9%2028.1%2035%2022%2035c-7.2%200-13-5.8-13-13S14.8%209%2022%209c3.1%200%205.9%201.1%208.1%202.9l6.4-6.4C32.6%202.1%2027.6%200%2022%200%209.8%200%200%209.8%200%2022s9.8%2022%2022%2022c11%200%2021-8%2021-22%200-1.3-.2-2.7-.5-4z%22%20id%3D%22a%22%2F%3E%3C%2Fdefs%3E%3Cuse%20fill%3D%22%23FFF%22%20xlink%3Ahref%3D%22%23a%22%20fill-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E); }', - 'html{mask-image:url("data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2243%22%20height%3D%2244%22%20viewBox%3D%220%200%2043%2044%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%3Cdefs%3E%3Cpath%20d%3D%22M42.5%2018H22v8.5h11.8C32.7%2031.9%2028.1%2035%2022%2035c-7.2%200-13-5.8-13-13S14.8%209%2022%209c3.1%200%205.9%201.1%208.1%202.9l6.4-6.4C32.6%202.1%2027.6%200%2022%200%209.8%200%200%209.8%200%2022s9.8%2022%2022%2022c11%200%2021-8%2021-22%200-1.3-.2-2.7-.5-4z%22%20id%3D%22a%22%2F%3E%3C%2Fdefs%3E%3Cuse%20fill%3D%22%23FFF%22%20xlink%3Ahref%3D%22%23a%22%20fill-rule%3D%22evenodd%22%2F%3E%3C%2Fsvg%3E")}', - ], - ]; - } - - /** - * Test handling of stylesheets with spaces in the background-image URLs. - * - * @dataProvider get_style_rules_with_url_values - * @covers AMP_Style_Sanitizer::remove_spaces_from_url_values() - * - * @param string $source Source URL string. - * @param string|null $expected Expected normalized URL string. - */ - public function test_remove_spaces_from_url_values( $source, $expected ) { - $html = ''; - - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $sanitizer = new AMP_Style_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $stylesheets = array_values( $sanitizer->get_stylesheets() ); - - $this->assertStringContainsString( $expected, $stylesheets[0] ); - } - - /** - * Get font url test data. - * - * @return array Data. - */ - public function get_font_urls() { - return [ - 'tangerine' => [ - 'https://fonts.googleapis.com/css?family=Tangerine', - [], - ], - 'tangerine2' => [ - '//fonts.googleapis.com/css?family=Tangerine', - [], - ], - 'tangerine3' => [ - 'http://fonts.googleapis.com/css?family=Tangerine', - [], - ], - 'tangerine4' => [ - 'https://fonts.googleapis.com/css2?family=Tangerine', - [], - ], - 'typekit' => [ - 'https://use.typekit.net/abc.css', - [], - ], - 'fontscom' => [ - 'https://fast.fonts.net/abc.css', - [], - ], - 'fontawesome' => [ - 'https://maxcdn.bootstrapcdn.com/font-awesome/123/css/font-awesome.min.css', - [], - ], - ]; - } - - /** - * Tests that font URLs get validated. - * - * @covers ::amp_filter_font_style_loader_tag_with_crossorigin_anonymous() - * @dataProvider get_font_urls - * @param string $url Font URL. - * @param array $error_codes Error codes. - */ - public function test_font_urls( $url, $error_codes ) { - $tag = sprintf( '', esc_url( $url ) ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $tag = amp_filter_font_style_loader_tag_with_crossorigin_anonymous( $tag, 'font', $url ); - - $dom = Document::fromHtml( sprintf( '%s', $tag ), Options::DEFAULTS ); - - $validation_errors = []; - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$validation_errors ) { - $validation_errors[] = $error; - }, - ] - ); - $sanitizer->sanitize(); - - $this->assertEqualSets( $error_codes, wp_list_pluck( $validation_errors, 'code' ) ); - - $link = $dom->getElementsByTagName( 'link' )->item( 0 ); - if ( empty( $error_codes ) ) { - $this->assertInstanceOf( 'DOMElement', $link ); - $this->assertEquals( - preg_replace( '#^(http:)?(?=//)#', 'https:', $url ), - $link->getAttribute( 'href' ) - ); - $this->assertEquals( 'anonymous', $link->getAttribute( 'crossorigin' ) ); - } else { - $this->assertEmpty( $link ); - } - } - - /** - * Test addition of crossorigin attribute to external stylesheet links. - * - * @covers AMP_Style_Sanitizer::process_link_element() - * @covers ::amp_filter_font_style_loader_tag_with_crossorigin_anonymous() - */ - public function test_cors_enabled_stylesheet_url() { - - // Test supplying crossorigin attribute. - $url = 'https://fonts.googleapis.com/css?family=Tangerine'; - $link = amp_filter_font_style_loader_tag_with_crossorigin_anonymous( "", 'font', $url ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $document = Document::fromHtml( "$link", Options::DEFAULTS ); - $sanitizer = new AMP_Style_Sanitizer( $document, [ 'use_document_element' => true ] ); - $sanitizer->sanitize(); - $link = $document->getElementsByTagName( 'link' )->item( 0 ); - $this->assertInstanceOf( 'DOMElement', $link ); - $this->assertEquals( 'anonymous', $link->getAttribute( 'crossorigin' ) ); - - // Test that existing crossorigin attribute is not overridden. - $link = amp_filter_font_style_loader_tag_with_crossorigin_anonymous( "", 'font', $url ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $document = Document::fromHtml( "$link", Options::DEFAULTS ); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $sanitizer = new AMP_Style_Sanitizer( $document, [ 'use_document_element' => true ] ); - $sanitizer->sanitize(); - $link = $document->getElementsByTagName( 'link' )->item( 0 ); - $this->assertInstanceOf( 'DOMElement', $link ); - $this->assertEquals( 'use-credentials', $link->getAttribute( 'crossorigin' ) ); - } - - /** - * Data source for test_css_import. - * - * @return array - */ - public function get_import_test_data() { - return [ - 'local_css_files' => [ - [ - plugins_url( 'tests/php/data/css/foo/../login.css', AMP__FILE__ ), - plugins_url( 'tests/php/data/css/buttons.css', AMP__FILE__ ), - ], - '
        ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - 0, // Zero HTTP requests. - null, // No preempting of request, as no external requests. - static function ( WP_UnitTestCase $test, $stylesheet ) { - $expected_order = [ - preg_quote( 'input[type="checkbox"]:disabled', '/' ), - preg_quote( '.wp-core-ui .button', '/' ), - preg_quote( 'div::after{content:"After login"}', '/' ), - ]; - $test->assertMatchesRegularExpression( - '/.*' . implode( '.*', $expected_order ) . '/s', - $stylesheet - ); - }, - ], - - 'local_css_with_import_failure_rejecting' => [ - [ - admin_url( 'css/local-does-not-exist.css' ), - 'https://bogus.example.com/remote-does-not-exist.css', - plugins_url( 'tests/php/data/css/foo/../login.css', AMP__FILE__ ), - 'https://bogus.example.com/remote-also-does-not-exist.css', - ], - '
        ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - 4, // All four result in HTTP requests, even the local one because it doesn't exist on the filesystem. - static function ( $requested_url ) { - if ( false !== strpos( $requested_url, 'does-not-exist' ) ) { - return new WP_Error( 'does_not_exist' ); - } - return null; - }, - static function ( WP_UnitTestCase $test, $stylesheet ) { - $expected_order = [ - 'local-does-not-exist.css', - 'remote-does-not-exist.css', - 'remote-also-does-not-exist.css', - 'remote-finally-does-not-exist.css', - '.form-table td', // From imported forms.css. - 'body.locale-he-il', // From imported l10n.css. - '.login .message', // From login.css. - 'div::after{content:"End"}', - ]; - - $previous = -1; - foreach ( $expected_order as $i => $expected ) { - $test->assertStringContainsString( $expected, $stylesheet, "Did not see $expected at position $i." ); - $position = strpos( $stylesheet, $expected ); - $test->assertGreaterThan( $previous, $position, "Expected $expected to be after previous (at position $i)." ); - $previous = $position; - } - }, - [ - 'auto_reject' => true, - ], - ], - - 'local_css_with_import_failure_accepting' => [ - [ - admin_url( 'css/local-does-not-exist.css' ), - 'https://bogus.example.com/remote-does-not-exist.css', - plugins_url( 'tests/php/data/css/foo/../login.css', AMP__FILE__ ), - 'https://bogus.example.com/remote-also-does-not-exist.css', - ], - '
        ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - 4, // All four result in HTTP requests, even the local one because it doesn't exist on the filesystem. - static function ( $requested_url ) { - if ( false !== strpos( $requested_url, 'does-not-exist' ) ) { - return new WP_Error( 'does_not_exist' ); - } - return null; - }, - static function ( WP_UnitTestCase $test, $stylesheet ) { - $expected_absent = [ - 'local-does-not-exist.css', - 'remote-does-not-exist.css', - 'remote-also-does-not-exist.css', - 'remote-finally-does-not-exist.css', - ]; - foreach ( $expected_absent as $expected ) { - $test->assertStringNotContainsString( $expected, $stylesheet, "Expected to not see $expected." ); - } - - $expected_order = [ - '.form-table td', // From imported forms.css. - 'body.locale-he-il', // From imported l10n.css. - '.login .message', // From login.css. - 'div::after{content:"End"}', - ]; - - $previous = -1; - foreach ( $expected_order as $i => $expected ) { - $test->assertStringContainsString( $expected, $stylesheet, "Did not see $expected at position $i." ); - $position = strpos( $stylesheet, $expected ); - $test->assertGreaterThan( $previous, $position, "Expected $expected to be after previous (at position $i)." ); - $previous = $position; - } - }, - [ - 'auto_reject' => false, - ], - ], - - 'dynamic_stylesheet_with_relative_import' => [ - includes_url( '/dynamic/import-buttons.php' ), - '
        ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - 1, - static function( $requested_url ) { - if ( false !== strpos( $requested_url, 'import-buttons.php' ) ) { - return '@import url( "../css/./foo/../buttons.css" );body{color:#123456}'; - } - return null; - }, - static function ( WP_UnitTestCase $test, $stylesheet ) { - $test->assertMatchesRegularExpression( - '/.*' . preg_quote( '.wp-core-ui .button', '/' ) . '.*' . preg_quote( 'body{color:#123456}', '/' ) . '.*' . preg_quote( 'div::after{content:"After import-buttons"}', '/' ) . '/s', - $stylesheet - ); - }, - ], - - 'dynamic_stylesheet_with_absolute_import' => [ - includes_url( '/dynamic/import-buttons.php' ), - '
        ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - 1, - static function( $requested_url ) { - if ( false !== strpos( $requested_url, 'import-buttons.php' ) ) { - return sprintf( '@import "%s";body{color:#123456}', plugins_url( 'tests/php/data/css/buttons.css', AMP__FILE__ ) ); - } - return null; - }, - static function ( WP_UnitTestCase $test, $stylesheet ) { - $test->assertMatchesRegularExpression( - '/.*' . preg_quote( '.wp-core-ui .button', '/' ) . '.*' . preg_quote( 'body{color:#123456}', '/' ) . '.*' . preg_quote( 'div::after{content:"After import-buttons2"}', '/' ) . '/s', - $stylesheet - ); - }, - ], - - 'dynamic_stylesheet_with_nested_dynamic_stylesheet' => [ - includes_url( '/dynamic/import-buttons.php' ), - '
        ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - 2, - static function( $requested_url ) { - $self_call_url = includes_url( '/dynamic/nested.php' ); - if ( false !== strpos( $requested_url, 'import-buttons.php' ) ) { - return sprintf( '@import "%s";body{color:#123456}', $self_call_url ); - } elseif ( wp_parse_url( $self_call_url, PHP_URL_PATH ) === wp_parse_url( $requested_url, PHP_URL_PATH ) ) { - return 'div::before{ content:"HELLO NESTED"; }'; - } - return null; - }, - static function ( WP_UnitTestCase $test, $stylesheet ) { - $test->assertMatchesRegularExpression( - '/.*' . preg_quote( 'div::before{content:"HELLO NESTED"}', '/' ) . '.*' . preg_quote( 'body{color:#123456}', '/' ) . '.*' . preg_quote( 'div::after{content:"After import-buttons2"}', '/' ) . '/s', - $stylesheet - ); - }, - ], - ]; - } - - /** - * Test CSS imports. - * - * @dataProvider get_import_test_data - * @covers AMP_Style_Sanitizer::fetch_external_stylesheet() - * @covers AMP_Style_Sanitizer::splice_imported_stylesheet() - * @covers AMP_Style_Sanitizer::process_css_list() - * @covers AMP_Style_Sanitizer::replace_inside_css_list() - * - * @param array|string $stylesheet_urls Stylesheet URLs. - * @param string $style_element HTML markup for the stylesheet URL. - * @param int $expected_http_request_count Expected number of HTTP requests. - * @param callable $mock_response Function that returns the mocked CSS data. - * @param callable $assert Function that runs the assertions. - * @param array $options Additional options. - */ - public function test_css_import( $stylesheet_urls, $style_element, $expected_http_request_count, $mock_response, $assert, $options = [] ) { - $stylesheet_urls = (array) $stylesheet_urls; - - $markup = ''; - $imports = implode( - '', - array_map( - static function ( $stylesheet_url ) { - return sprintf( '@import url("%s");', $stylesheet_url ); - }, - $stylesheet_urls - ) - ); - $markup .= preg_replace( ':(?<=', $stylesheet_url ); - $markup .= 'hello'; - - $dom = Document::fromHtml( $markup, Options::DEFAULTS ); - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - ] - ); - $sanitizer->sanitize(); - $stylesheets = array_values( $sanitizer->get_stylesheets() ); - - $this->assertCount( 1, $stylesheets ); - $this->assertEquals( 'body{color:red}', $stylesheets[0] ); - $link = $dom->xpath->query( '//link[ @rel = "stylesheet" ]' )->item( 0 ); - $this->assertInstanceOf( 'DOMElement', $link ); - $this->assertEquals( set_url_scheme( $stylesheet_url, 'https' ), $link->getAttribute( 'href' ) ); - } - - /** - * Test CSS with Unicode characters. - * - * @covers \AMP_DOM_Utils::get_content_from_dom_node() - */ - public function test_unicode_stylesheet() { - wp(); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - - ob_start(); - ?> - - - - - - - - - - - - - assertStringContainsString( ".dashicons-admin-customizer:before{content:\"\xEF\x95\x80\"}", $sanitized_html ); - $this->assertStringContainsString( 'span::after{content:"⚡️"}', $sanitized_html ); - } - - /** - * Test style element with old-school XHTML CDATA. - * - * @covers \AMP_Style_Sanitizer::parse_stylesheet() - */ - public function test_style_element_cdata() { - $html = ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= '

        Hello World

        '; - - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - ] - ); - - $sanitizer->sanitize(); - - $style = $dom->xpath->query( '//style[ @amp-custom ]' )->item( 0 ); - $this->assertInstanceOf( 'DOMElement', $style ); - - $expected = "body{color:red}body{color:green}body{color:blue}\n\n/*# sourceURL=amp-custom.css */"; - $this->assertEquals( $expected, $style->nodeValue ); - } - - /** - * Test that a font stylesheet is moved to the head. - * - * @covers \AMP_Style_Sanitizer::sanitize() - */ - public function test_body_font_stylesheet_moved_to_head() { - $html = ''; // phpcs:ignore - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $link = $dom->getElementById( 'the-font' ); - $this->assertInstanceOf( 'DOMElement', $link ); - $this->assertEquals( 'body', $link->parentNode->nodeName ); - - $sanitizer_args = [ 'use_document_element' => true ]; - - $sanitizer = new AMP_Style_Sanitizer( $dom, $sanitizer_args ); - $sanitizer->sanitize(); - - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom, $sanitizer_args ); - $sanitizer->sanitize(); - - $this->assertInstanceOf( 'DOMElement', $link->parentNode ); - $this->assertEquals( 'head', $link->parentNode->nodeName ); - } - - /** - * Get prioritization test data. - * - * @todo Refactor to use custom theme or existing theme instead of requiring Twenty Ten. - * - * @covers AMP_Style_Sanitizer::remove_admin_bar_if_css_excluded() - * - * @return array - */ - public function get_prioritization_data() { - add_filter( - 'theme_root', - static function () { - return ABSPATH . 'wp-content/themes'; - } - ); - add_filter( - 'theme_root_uri', - static function () { - return site_url( 'wp-content/themes' ); - } - ); - - $render_template = static function () { - ob_start(); - ?> - > - [ - function () use ( $render_template ) { - $this->go_to( amp_get_permalink( self::factory()->post->create() ) ); - show_admin_bar( true ); - _wp_admin_bar_init(); - switch_theme( 'twentyten' ); - require_once get_template_directory() . '/functions.php'; - add_action( - 'wp_head', - static function() { - printf( '', esc_html( str_repeat( 'a', 75000 - 10 ) ) ); - }, - -1000 - ); - add_action( 'wp_enqueue_scripts', 'twentyten_scripts_styles' ); - AMP_Theme_Support::add_hooks(); - wp_add_inline_style( 'admin-bar', '.admin-bar-inline-style{ color:red }' ); - - add_action( - 'wp_footer', - function() { - ?> -
        -
        -
        -

        Hi

        -
        - assertInstanceOf( 'DOMElement', $original_dom->getElementById( 'wpadminbar' ), 'Expected admin bar element to be present originally.' ); - $this->assertInstanceOf( 'DOMElement', $original_dom->getElementById( 'admin-bar-css' ), 'Expected admin bar CSS to be present originally.' ); - $this->assertStringContainsString( 'admin-bar', $original_dom->body->getAttribute( 'class' ) ); - $this->assertStringContainsString( 'earlyprintstyle', $original_source, 'Expected early print style to not be present.' ); - - $this->assertStringContainsString( '.wp-block-audio figcaption', $amphtml_source, 'Expected block-library/style.css' ); - $this->assertStringContainsString( '[class^="wp-block-"]:not(.wp-block-gallery) figcaption', $amphtml_source, 'Expected twentyten/blocks.css' ); - $amphtml_source = preg_replace( '/\s*>\s*/', '>', $amphtml_source ); // Account for variance in postcss. - $this->assertStringContainsString( '.amp-wp-default-form-message>p', $amphtml_source, 'Expected amp-default.css' ); - $this->assertStringContainsString( 'ab-empty-item', $amphtml_source, 'Expected admin-bar.css to still be present.' ); - $this->assertStringNotContainsString( 'earlyprintstyle', $amphtml_source, 'Expected early print style to not be present.' ); - $this->assertStringContainsString( 'admin-bar', $amphtml_dom->body->getAttribute( 'class' ) ); - $this->assertInstanceOf( 'DOMElement', $amphtml_dom->getElementById( 'wpadminbar' ) ); - }, - ], - // @todo Add other scenarios in the future. - ]; - } - - /** - * Test stylesheet prioritization. - * - * @dataProvider get_prioritization_data - * @covers \AMP_Style_Sanitizer::finalize_stylesheet_group() - * @covers \AMP_Style_Sanitizer::get_stylesheet_priority() - * - * @param callable $html_generator Generator of HTML. - * @param callable $assert Function which runs assertions. - */ - public function test_prioritized_stylesheets( $html_generator, $assert ) { - if ( version_compare( get_bloginfo( 'version' ), '5.0', '<' ) ) { - $this->markTestSkipped( 'Requires WordPress 5.0.' ); - } - global $wp_theme_directories; // Note that get_theme_roots() does not work, for some reason. - - // @todo Remove once https://github.com/WordPress/gutenberg/pull/23104 is in a release. - // Temporarily fixes an issue with PHP errors being thrown in Gutenberg v8.3.0 on PHP 7.4. - $theme_features = [ - 'editor-color-palette', - 'editor-gradient-presets', - 'editor-font-sizes', - ]; - foreach ( $theme_features as $theme_feature ) { - if ( ! current_theme_supports( $theme_feature ) ) { - add_theme_support( $theme_feature, [] ); - } - } - - $theme_exists = false; - foreach ( $wp_theme_directories as $theme_root ) { - $theme_exists = wp_get_theme( 'twentyten', $theme_root )->exists(); - if ( $theme_exists ) { - break; - } - } - if ( ! $theme_exists ) { - $this->markTestSkipped( 'Requires Twenty Ten to be installed.' ); - } - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->go_to( home_url() ); - $html = $html_generator(); - - $original_dom = Document::fromHtml( $html, Options::DEFAULTS ); - $amphtml_dom = clone( $original_dom ); - - $error_codes = []; - $args = [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$error_codes ) { - $error_codes[] = $error['code']; - }, - ]; - - $sanitizer = new AMP_Img_Sanitizer( $amphtml_dom, $args ); - $sanitizer->sanitize(); - - $sanitizer = new AMP_Style_Sanitizer( $amphtml_dom, $args ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $amphtml_dom, $args ); - $validating_sanitizer->sanitize(); - - $assert( $original_dom, $html, $amphtml_dom, $amphtml_dom->saveHTML(), $sanitizer->get_stylesheets() ); - } - - /** - * Provide data to test_get_stylesheet_priority(). - * - * @return array[] Array of test data. - */ - public function get_stylesheet_priority_data() { - return [ - 'Non-AMP handle' => [ [ 'link', [ 'id' => 'mediaelement-css' ] ], 1000 ], - 'Admin bar handle' => [ [ 'link', [ 'id' => 'admin-bar-css' ] ], 200 ], - 'Dashicons handle' => [ [ 'link', [ 'id' => 'dashicons-css' ] ], 90 ], - 'Parent theme styles' => [ [ 'link', [ 'href' => get_theme_root_uri() . '/parent-theme/style.css' ] ], 1 ], - 'Child theme styles' => [ [ 'link', [ 'href' => get_theme_root_uri() . '/child-theme/style.css' ] ], 10 ], - 'Core frontend handle' => [ [ 'link', [ 'id' => 'wp-block-library-css' ] ], 20 ], - 'Plugin asset' => [ [ 'link', [ 'href' => plugins_url() . '/some-plugin/style.css' ] ], 30 ], - 'Query monitor plugin asset' => [ [ 'link', [ 'href' => plugins_url() . '/query-monitor/style.css' ] ], 150 ], - 'Other styles from wp-includes' => [ [ 'link', [ 'href' => includes_url() ] ], 40 ], - 'All other links' => [ [ 'link', [ 'id' => 'something-else' ] ], 50 ], - 'Parent theme inline styles' => [ [ 'style', [ 'id' => 'parent-theme-inline-css' ] ], 2 ], - 'Child theme inline styles' => [ [ 'style', [ 'id' => 'child-theme-inline-css' ] ], 12 ], - 'Admin bar inline styles' => [ [ 'style', [ 'id' => 'admin-bar-inline-css' ] ], 200 ], - 'Customizer inline styles' => [ [ 'style', [ 'id' => 'wp-custom-css' ] ], 60 ], - 'Other inline styles' => [ [ 'style', [ 'id' => 'something-else' ] ], 70 ], - 'Non-AMP handle for print' => [ - [ - 'link', - [ - 'id' => 'mediaelement-css', - 'media' => 'print', - ], - ], - 1100, - ], - 'Admin bar handle for print' => [ - [ - 'link', - [ - 'id' => 'admin-bar-css', - 'media' => 'print', - ], - ], - 300, - ], - 'Dashicons handle for print' => [ - [ - 'link', - [ - 'id' => 'dashicons-css', - 'media' => 'print', - ], - ], - 190, - ], - 'Parent theme styles for print' => [ - [ - 'link', - [ - 'href' => get_theme_root_uri() . '/parent-theme/style.css', - 'media' => 'print', - ], - ], - 101, - ], - 'Child theme styles for print' => [ - [ - 'link', - [ - 'href' => get_theme_root_uri() . '/child-theme/style.css', - 'media' => 'print', - ], - ], - 110, - ], - 'Core frontend handle for print' => [ - [ - 'link', - [ - 'id' => 'wp-block-library-css', - 'media' => 'print', - ], - ], - 120, - ], - 'Plugin asset for print' => [ - [ - 'link', - [ - 'href' => plugins_url() . '/some-plugin/style.css', - 'media' => 'print', - ], - ], - 130, - ], - 'Query monitor plugin asset for print' => [ - [ - 'link', - [ - 'href' => plugins_url() . '/query-monitor/style.css', - 'media' => 'print', - ], - ], - 250, - ], - 'Other styles from wp-includes for print' => [ - [ - 'link', - [ - 'href' => includes_url(), - 'media' => 'print', - ], - ], - 140, - ], - 'All other links for print' => [ - [ - 'link', - [ - 'id' => 'something-else', - 'media' => 'print', - ], - ], - 150, - ], - 'Parent theme inline styles for print' => [ - [ - 'style', - [ - 'id' => 'parent-theme-inline-css', - 'media' => 'print', - ], - ], - 102, - ], - 'Child theme inline styles for print' => [ - [ - 'style', - [ - 'id' => 'child-theme-inline-css', - 'media' => 'print', - ], - ], - 112, - ], - 'Admin bar inline styles for print' => [ - [ - 'style', - [ - 'id' => 'admin-bar-inline-css', - 'media' => 'print', - ], - ], - 300, - ], - 'Customizer inline styles for print' => [ - [ - 'style', - [ - 'id' => 'wp-custom-css', - 'media' => 'print', - ], - ], - 160, - ], - 'Other inline styles for print' => [ - [ - 'style', - [ - 'id' => 'something-else', - 'media' => 'print', - ], - ], - 170, - ], - 'Style attribute' => [ [ null, [ 'something' ] ], 70 ], - ]; - } - - /** - * Test retrieval of stylesheet priorities. - * - * @covers \AMP_Style_Sanitizer::get_stylesheet_priority() - * - * @dataProvider get_stylesheet_priority_data - * - * @param array $node_data Node to check the priority of. - * @param int $expected Expected priority. - */ - public function test_get_stylesheet_priority( $node_data, $expected ) { - global $wp_styles; - $wp_styles = new WP_Styles(); - - $parent_theme_filter = static function () { - return 'parent-theme'; - }; - $child_theme_filter = static function () { - return 'child-theme'; - }; - - $dom = new Document(); - - if ( isset( $node_data[0] ) ) { - $node = AMP_DOM_Utils::create_node( $dom, $node_data[0], $node_data[1] ); - } else { - $node = $dom->createAttribute( $node_data[1][0] ); - } - - $sanitizer = new AMP_Style_Sanitizer( $dom ); - - add_filter( 'template', $parent_theme_filter ); - add_filter( 'stylesheet', $child_theme_filter ); - $wp_styles->add( 'parent-theme', get_template_directory_uri() . '/style.css' ); - $wp_styles->add( 'child-theme', get_stylesheet_directory_uri() . '/style.css' ); - $this->assertEquals( - $expected, - $this->call_private_method( $sanitizer, 'get_stylesheet_priority', [ $node ] ), - 'Node data: ' . wp_json_encode( $node_data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ) - ); - remove_filter( 'stylesheet', $child_theme_filter ); - remove_filter( 'template', $parent_theme_filter ); - } - - /** - * Test get_css_parser_validation_error_codes. - * - * @covers AMP_Style_Sanitizer::get_css_parser_validation_error_codes() - */ - public function test_get_css_parser_validation_error_codes() { - $expected = [ - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_AT_RULE, - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_DECLARATION, - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_IMPORTANT, - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY, - AMP_Style_Sanitizer::CSS_SYNTAX_INVALID_PROPERTY_NOLIST, - AMP_Style_Sanitizer::CSS_SYNTAX_PARSE_ERROR, - AMP_Style_Sanitizer::STYLESHEET_FETCH_ERROR, - AMP_Style_Sanitizer::STYLESHEET_TOO_LONG, - AMP_Style_Sanitizer::CSS_DISALLOWED_SELECTOR, - ]; - - $this->assertEqualSets( $expected, AMP_Style_Sanitizer::get_css_parser_validation_error_codes() ); - } - - /** - * Test get_styles. - * - * @covers AMP_Style_Sanitizer::get_styles() - */ - public function test_get_styles() { - $sanitizer = new AMP_Style_Sanitizer( new Document() ); - $this->assertEquals( [], $sanitizer->get_styles() ); - } - - /* - * Gets the test data for test_viewport_rules_added_to_meta_viewport(). - * - * @return array The test data. - */ - public function get_viewport_data() { - return [ - 'existing_meta_viewport_remains_when_no_style_rule' => [ - '', - ], - 'viewport_rule_converted_to_meta_viewport' => [ - '', - '', - ], - 'vendor_prefixed_viewport_rule_converted_to_meta_viewport' => [ - '', - '', - ], - 'viewport_merged_rules' => [ - '', - '', - ], - 'nested_viewport_in_at_rule' => [ - '', - '', - ], - ]; - } - - /** - * Test sanitization of tags and attributes for the entire document, including the HEAD. - * - * @dataProvider get_viewport_data - * @covers AMP_Style_Sanitizer::sanitize() - * @covers AMP_Meta_Sanitizer::sanitize() - * @covers AMP_Meta_Sanitizer::ensure_viewport_is_present() - * - * @param string $markup The markup to sanitize. - * @param string $expected The expected result after sanitizing. - */ - public function test_viewport_rules_added_to_meta_viewport( $markup, $expected = null ) { - $opening_markup = ''; - $closing_markup = ''; - $markup = $opening_markup . $markup . $closing_markup; - - if ( null === $expected ) { - $expected = $markup; - } else { - $expected = $opening_markup . $expected . $closing_markup; - } - - $dom = Document::fromHtml( $markup, Options::DEFAULTS ); - $style_sanitizer = new AMP_Style_Sanitizer( $dom ); - $style_sanitizer->sanitize(); - $meta_sanitizer = new AMP_Meta_Sanitizer( $dom ); - $meta_sanitizer->sanitize(); - - $content = $dom->saveHTML( $dom->documentElement ); - $this->assertEquals( $expected, $content ); - } - - /** - * Test that stylesheet processing can be disabled (for level 1 sandboxing). - * - * @covers AMP_Style_Sanitizer::sanitize() - */ - public function test_disable_style_processing() { - $dom = Document::fromHtml( - ' - - - - - - - -
        Blue Violet
        - - - - - - ', - Options::DEFAULTS - ); - - $sanitizer = new AMP_Style_Sanitizer( - $dom, - [ - 'use_document_element' => true, - 'disable_style_processing' => true, - ] - ); - $sanitizer->sanitize(); - $this->assertCount( 0, $sanitizer->get_stylesheets() ); - - $style_query = $dom->xpath->query( '//style' ); - $this->assertEquals( 2, $style_query->length ); - foreach ( $style_query as $style_element ) { - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $style_element ) ); - } - $this->assertStringContainsString( '/*comment*/', $style_query->item( 0 )->textContent ); - $this->assertStringContainsString( 'body.loaded', $style_query->item( 0 )->textContent ); - $this->assertStringContainsString( 'audio { outline: solid 1px green !important; }', $style_query->item( 0 )->textContent ); - - $link_query = $dom->xpath->query( '//link[ @rel = "stylesheet" ]' ); - $this->assertEquals( 3, $link_query->length ); - foreach ( $link_query as $link_element ) { - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $link_element ) ); - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $link_element->getAttributeNode( 'rel' ) ) ); - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $link_element->getAttributeNode( 'href' ) ) ); - } - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $dom->xpath->query( '//link[ @rel = "canonical" ]' )->item( 0 ) ) ); - - $style_attribute = $dom->getElementById( 'blueviolet' )->getAttributeNode( 'style' ); - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $style_attribute ) ); - $this->assertEquals( 'color:blueviolet !important;', $style_attribute->nodeValue ); - } -} diff --git a/tests/php/test-amp-tag-and-attribute-sanitizer-private-methods.php b/tests/php/test-amp-tag-and-attribute-sanitizer-private-methods.php deleted file mode 100644 index a67a78f4995..00000000000 --- a/tests/php/test-amp-tag-and-attribute-sanitizer-private-methods.php +++ /dev/null @@ -1,1934 +0,0 @@ -allowed_tags = AMP_Allowed_Tags_Generated::get_allowed_tags(); - $this->globally_allowed_attrs = AMP_Allowed_Tags_Generated::get_allowed_attributes(); - $this->layout_allowed_attrs = AMP_Allowed_Tags_Generated::get_layout_attributes(); - } - - public function get_attr_spec_rule_data() { - return [ - 'test_attr_spec_rule_mandatory_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-img', - 'attribute_name' => 'src', - 'attribute_value' => '/path/to/resource', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_mandatory', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_mandatory_alternate_attr_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-img', - 'attribute_name' => 'src', - 'use_alternate_name' => 'srcset', - 'attribute_value' => '/path/to/resource', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_mandatory', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_mandatory_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-img', - 'attribute_name' => 'src', - 'attribute_value' => '/path/to/resource', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_mandatory', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_mandatory_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-img', - 'attribute_name' => 'alt', - 'attribute_value' => 'alternate', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_mandatory', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - - 'test_attr_spec_rule_value_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'template', - 'attribute_name' => 'type', - 'attribute_value' => 'amp-mustache', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_value_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'template', - 'attribute_name' => 'type', - 'attribute_value' => 'invalid', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_value_not_applicable' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'template', - 'attribute_name' => 'type', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_value', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - - 'test_attr_spec_rule_value_casei_lower_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'type', - 'attribute_value' => 'text/html', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_value_casei_upper_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'type', - 'attribute_value' => 'TEXT/HTML', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_value_casei_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'type', - 'attribute_value' => 'invalid', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_value_casei_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'template', - 'attribute_name' => 'type', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - - 'test_attr_spec_rule_value_regex_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'target', - 'attribute_value' => '_blank', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_value_regex_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'target', - 'attribute_value' => '_blankzzz', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_value_regex_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'target', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_value_regex', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - - 'test_attr_spec_rule_value_regex_casei_lower_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-playbuzz', - 'attribute_name' => 'data-comments', - 'attribute_value' => 'false', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_value_regex_casei_upper_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-playbuzz', - 'attribute_name' => 'data-comments', - 'attribute_value' => 'FALSE', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_value_regex_casei_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-playbuzz', - 'attribute_name' => 'data-comments', - 'attribute_value' => 'invalid', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_value_casei', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_value_regex_casei_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-playbuzz', - 'attribute_name' => 'data-comments', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_value_regex_casei', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'test_attr_spec_rule_disallowed_relative_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'data-share-endpoint', - 'attribute_value' => 'http://example.com', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_relative', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_disallowed_relative_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'data-share-endpoint', - 'attribute_value' => '//example.com', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_relative', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_disallowed_relative_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'data-share-endpoint', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_disallowed_relative', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - - 'test_attr_spec_rule_disallowed_empty_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-user-notification', - 'attribute_name' => 'data-dismiss-href', - 'attribute_value' => 'https://example.com', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_empty', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_disallowed_empty_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-user-notification', - 'attribute_name' => 'data-dismiss-href', - 'attribute_value' => '', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_empty', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_disallowed_empty_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-user-notification', - 'attribute_name' => 'data-dismiss-href', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_disallowed_empty', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'test_attr_spec_rule_disallowed_value_regex_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'rel', - 'attribute_value' => 'whatever', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_value_regex', - ], - 'expected' => AMP_Rule_Spec::PASS, - ], - 'test_attr_spec_rule_disallowed_value_regex_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'rel', - 'attribute_value' => 'components', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_value_regex', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_disallowed_value_regex_fail_2' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'rel', - 'attribute_value' => 'import', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'check_attr_spec_rule_disallowed_value_regex', - ], - 'expected' => AMP_Rule_Spec::FAIL, - ], - 'test_attr_spec_rule_disallowed_value_regex_na' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'a', - 'attribute_name' => 'rel', - 'attribute_value' => 'invalid', - 'include_attr' => false, - 'include_attr_value' => false, - 'func_name' => 'check_attr_spec_rule_disallowed_value_regex', - ], - 'expected' => AMP_Rule_Spec::NOT_APPLICABLE, - ], - ]; - } - - /** - * @dataProvider get_attr_spec_rule_data - * @group allowed-tags-private-methods - */ - public function test_validate_attr_spec_rules( $data, $expected ) { - - if ( isset( $data['include_attr_value'] ) && $data['include_attr_value'] ) { - $attr_value = '="' . $data['attribute_value'] . '"'; - } else { - $attr_value = ''; - } - if ( isset( $data['use_alternate_name'] ) && $data['use_alternate_name'] && $data['include_attr'] ) { - $attribute = $data['use_alternate_name'] . $attr_value; - } elseif ( isset( $data['include_attr'] ) && $data['include_attr'] ) { - $attribute = $data['attribute_name'] . $attr_value; - } else { - $attribute = ''; - } - - $source = '<' . $data['tag_name'] . ' ' . $attribute . '>Some test content'; - - $attr_spec_list = $this->allowed_tags[ $data['tag_name'] ][ $data['rule_spec_index'] ]['attr_spec_list']; - foreach ( $attr_spec_list as $attr_name => $attr_val ) { - if ( isset( $attr_spec_list[ $attr_name ][ AMP_Rule_Spec::ALTERNATIVE_NAMES ] ) ) { - foreach ( $attr_spec_list[ $attr_name ][ AMP_Rule_Spec::ALTERNATIVE_NAMES ] as $attr_alt_name ) { - $attr_spec_list[ $attr_alt_name ] = $attr_spec_list[ $attr_name ]; - } - } - } - - $attr_spec_rule = $attr_spec_list[ $data['attribute_name'] ]; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $data['tag_name'] )->item( 0 ); - - $got = $this->call_private_method( $sanitizer, $data['func_name'], [ $node, $data['attribute_name'], $attr_spec_rule ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $source, wp_json_encode( $data ) ) ); - } - - public function get_is_allowed_attribute_data() { - return [ - 'test_is_amp_allowed_attribute_allowlisted_regex_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'data-whatever-else-you-want', - 'attribute_value' => 'whatever', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_global_attribute_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'itemid', - 'attribute_value' => 'whatever', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_tag_spec_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'media', - 'attribute_value' => 'whatever', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_disallowed_attr_fail' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-social-share', - 'attribute_name' => 'bad-attr', - 'attribute_value' => 'whatever', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => false, - ], - - 'test_is_amp_allowed_attribute_layout_height_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-ad', - 'attribute_name' => 'height', - 'attribute_value' => 'not_tested', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_layout_heights_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-ad', - 'attribute_name' => 'heights', - 'attribute_value' => 'not_tested', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_layout_width_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-ad', - 'attribute_name' => 'width', - 'attribute_value' => 'not_tested', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_layout_sizes_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-ad', - 'attribute_name' => 'sizes', - 'attribute_value' => 'not_tested', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - 'test_is_amp_allowed_attribute_layout_layout_pass' => [ - [ - 'rule_spec_index' => 0, - 'tag_name' => 'amp-ad', - 'attribute_name' => 'layout', - 'attribute_value' => 'not_tested', - 'include_attr' => true, - 'include_attr_value' => true, - 'func_name' => 'is_amp_allowed_attribute', - ], - 'expected' => true, - ], - ]; - } - - /** - * @dataProvider get_is_allowed_attribute_data - * @group allowed-tags-private-methods - */ - public function test_is_allowed_attribute( $data, $expected ) { - - if ( isset( $data['include_attr_value'] ) && $data['include_attr_value'] ) { - $attr_value = '="' . $data['attribute_value'] . '"'; - } else { - $attr_value = ''; - } - if ( isset( $data['use_alternate_name'] ) && $data['use_alternate_name'] && $data['include_attr'] ) { - $attribute = $data['use_alternate_name'] . $attr_value; - } elseif ( isset( $data['include_attr'] ) && $data['include_attr'] ) { - $attribute = $data['attribute_name'] . $attr_value; - } else { - $attribute = ''; - } - $source = '<' . $data['tag_name'] . ' ' . $attribute . '>Some test content'; - - $attr_spec_list = array_merge( $this->globally_allowed_attrs, $this->allowed_tags[ $data['tag_name'] ][ $data['rule_spec_index'] ]['attr_spec_list'] ); - if ( isset( $this->allowed_tags[ $data['tag_name'] ][ $data['rule_spec_index'] ]['tag_spec']['amp_layout'] ) ) { - $attr_spec_list = array_merge( $attr_spec_list, $this->layout_allowed_attrs ); - } - foreach ( $attr_spec_list as $attr_name => $attr_val ) { - if ( isset( $attr_spec_list[ $attr_name ][ AMP_Rule_Spec::ALTERNATIVE_NAMES ] ) ) { - foreach ( $attr_spec_list[ $attr_name ][ AMP_Rule_Spec::ALTERNATIVE_NAMES ] as $attr_alt_name ) { - $attr_spec_list[ $attr_alt_name ] = $attr_spec_list[ $attr_name ]; - } - } - } - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $data['tag_name'] )->item( 0 ); - $attr = $node->getAttributeNode( $data['attribute_name'] ); - - $got = $this->call_private_method( $sanitizer, $data['func_name'], [ $attr, $attr_spec_list ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $source, wp_json_encode( $data ) ) ); - } - - public function get_remove_node_data() { - return [ - 'remove_single_bad_tag' => [ - [ - 'source' => '', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'remove_bad_tag_with_single_empty_parent' => [ - [ - 'source' => '
        ', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'remove_bad_tag_with_multiple_empty_parents' => [ - [ - 'source' => '

        ', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'remove_bad_tag_leave_siblings' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'remove_bad_tag_and_empty_parent_leave_parent_siblings' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'remove_bad_tag_and_multiple_empty_parent_leave_parent_siblings' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'remove_bad_tag_leave_empty_siblings_and_parent' => [ - [ - 'source' => '

        ', - 'tag_name' => 'bad-tag', - ], - '

        ', - ], - 'remove_single_bad_tag_with_non-empty_parent' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'remove_bad_tag_and_empty_parent_leave_non-empty_grandparent' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'remove_bad_tag_and_empty_grandparent_leave_non-empty_greatgrandparent' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - ]; - } - - /** - * @dataProvider get_remove_node_data - * @group allowed-tags-private-methods - */ - public function test_remove_node( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $data['tag_name'] )->item( 0 ); - - $this->call_private_method( $sanitizer, 'remove_node', [ $node ] ); - - $got = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - /** @return array */ - public function get_replace_node_with_children_data() { - return [ - 'text_child' => [ - [ - 'source' => 'Good Data', - 'tag_name' => 'bad-tag', - ], - 'Good Data', - ], - 'comment_child' => [ - [ - 'source' => '', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'single_child' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'multiple_children' => [ - [ - 'source' => '

        Good Data

        More Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        More Good Data

        ', - ], - 'no_children' => [ - [ - 'source' => '', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'children_with_empty_parent' => [ - [ - 'source' => '
        Good Data
        ', - 'tag_name' => 'bad-tag', - ], - '
        Good Data
        ', - ], - 'no_children_empty_parent' => [ - [ - 'source' => '
        ', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'nested_invalid_elements' => [ - [ - 'source' => '

        Example Summary

        Example expanded text

        ', - 'tag_name' => 'bad-details', - ], - '

        Example Summary

        Example expanded text

        ', - ], - 'children_multiple_empty_parents' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'no_children_multiple_empty_parents' => [ - [ - 'source' => '

        ', - 'tag_name' => 'bad-tag', - ], - '', - ], - 'no_children_leave_siblings' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'no_children_and_empty_parent_leave_parent_siblings' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'no_children_and_multiple_empty_parent_leave_parent_siblings' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'no_children_leave_empty_siblings_and_parent' => [ - [ - 'source' => '

        ', - 'tag_name' => 'bad-tag', - ], - '

        ', - ], - 'no_childreng_with_non-empty_parent' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'no_children_and_empty_parent_leave_non-empty_grandparent' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - 'no_children_and_empty_grandparent_leave_non-empty_greatgrandparent' => [ - [ - 'source' => '

        Good Data

        ', - 'tag_name' => 'bad-tag', - ], - '

        Good Data

        ', - ], - ]; - } - - /** - * @dataProvider get_replace_node_with_children_data - * @group allowed-tags-private-methods - */ - public function test_replace_node_with_children( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $data['tag_name'] )->item( 0 ); - - $this->call_private_method( $sanitizer, 'replace_node_with_children', [ $node ] ); - - $got = AMP_DOM_Utils::get_content_from_dom( $dom ); - $got = preg_replace( '/(?<=>)\s+(?=<)/', '', $got ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - /** - * Get data for testing get_ancestor_with_matching_spec_name. - * - * @return array Data. - */ - public function get_ancestor_with_matching_spec_name_data() { - return [ - 'ancestor_is_immediate_parent' => [ - [ - 'source' => '

        Good Data

        ', - 'node_tag_name' => 'p', - 'ancestor_tag_name' => 'article', - ], - 'article', - ], - 'ancestor_is_distant_parent' => [ - [ - 'source' => '

        Good Data

        ', - 'node_tag_name' => 'p', - 'ancestor_tag_name' => 'article', - ], - 'article', - ], - 'ancestor_has_attributes' => [ - [ - 'source' => '

        Good Data

        ', - 'node_tag_name' => 'p', - 'ancestor_tag_name' => 'form [method=post]', - ], - 'form', - ], - 'ancestor_does_not_exist' => [ - [ - 'source' => '

        Good Data

        ', - 'node_tag_name' => 'p', - 'ancestor_tag_name' => 'article', - ], - null, - ], - ]; - } - - /** - * Test get_ancestor_with_matching_spec_name. - * - * @dataProvider get_ancestor_with_matching_spec_name_data - * @group allowed-tags-private-methods - * @covers AMP_Tag_And_Attribute_Sanitizer::get_ancestor_with_matching_spec_name() - * - * @param array $data Data. - * @param string $expected Expected. - */ - public function test_get_ancestor_with_matching_spec_name( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - if ( $expected ) { - $ancestor_node = $dom->getElementsByTagName( $expected )->item( 0 ); - } else { - $ancestor_node = null; - } - - $got = $this->call_private_method( $sanitizer, 'get_ancestor_with_matching_spec_name', [ $node, $data['ancestor_tag_name'] ] ); - - $this->assertEquals( $ancestor_node, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - /** - * Get test data for test_get_ancestor_with_matching_spec_name. - * - * @return array Test data. - */ - public function get_validate_attr_spec_list_for_node_data() { - return [ - 'no_attributes' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [], - ], - 1, // Because there are no mandatory attributes. - ], - 'attributes_no_spec' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [], - ], - 1, // Because there are no mandatory attributes. - ], - 'attributes_alternative_names' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'alternative_names' => [ - 'attribute1_alternative1', - 'attribute1_alternative2', - 'attribute1_alternative3', - ], - ], - ], - ], - 2, // Because there are no mandatory attributes. - ], - 'attributes_mandatory' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'mandatory' => true, - ], - ], - ], - 4, - ], - 'attributes_mandatory_alternative_name' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'mandatory' => true, - 'alternative_names' => [ - 'attribute1_alternative1', - 'attribute1_alternative2', - 'attribute1_alternative3', - ], - ], - ], - ], - 2, - ], - 'attributes_value' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value' => 'required_value', - ], - ], - ], - 4, - ], - 'attributes_value_regex' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_regex' => '(this|that)', - ], - ], - ], - 2, - ], - 'attributes_value_casei' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_casei' => 'value', - ], - ], - ], - 4, - ], - 'attributes_value_regex_casei' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_regex_casei' => '(this|that)', - ], - ], - ], - 2, - ], - 'attributes_allow_relative_false_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - ], - ], - ], - 2, - ], - 'attributes_allow_relative_false_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - ], - ], - ], - 2, // Still passes because relative URL is not checked until sanitization. - ], - 'attributes_allow_empty_false_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_url' => [ - 'allow_empty' => false, - ], - ], - ], - ], - 2, - ], - 'attributes_allow_empty_false_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'value_url' => [ - 'allow_empty' => false, - ], - ], - ], - ], - 2, // Allow empty is not used until sanitization. - ], - 'attributes_disallowed_regex' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_spec_list' => [ - 'attribute1' => [ - 'disallowed_value_regex' => 'disallowed_value', - 'alternative_names' => [ - 'attribute1_alternative1', - 'attribute1_alternative2', - 'attribute1_alternative3', - ], - ], - ], - ], - 2, - ], - ]; - } - - /** - * @dataProvider get_validate_attr_spec_list_for_node_data - * @group allowed-tags-private-methods - */ - public function test_validate_attr_spec_list_for_node( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - - $got = $this->call_private_method( $sanitizer, 'validate_attr_spec_list_for_node', [ $node, $data['attr_spec_list'] ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - public function get_check_attr_spec_rule_value_data() { - return [ - 'no_attributes' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'value_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => 'value1', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => 'valuex', - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'value_no_attr' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => 'value1', - ], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'value_empty_pass1' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => '', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_empty_pass2' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => '', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_empty_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => '', - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'value_alternative_attr_name_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => 'value1', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_alternative_attr_name_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value' => 'value1', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - ]; - } - - /** - * @dataProvider get_check_attr_spec_rule_value_data - * @group allowed-tags-private-methods - */ - public function test_check_attr_spec_rule_value( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $got = $this->call_private_method( $sanitizer, 'check_attr_spec_rule_value', [ $node, $data['attr_name'], $data['attr_spec_rule'] ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - public function get_check_attr_spec_rule_value_casei_data() { - return [ - 'no_attributes' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'value_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'value1', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_upper_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'value1', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'valuex', - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'value_no_attr' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'value1', - ], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'value_empty_pass1' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => '', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_empty_pass2' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => '', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_empty_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => '', - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'value_alternative_attr_name_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'value1', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_alternative_attr_name__upper_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'value1', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_alternative_attr_name_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_casei' => 'value1', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - ]; - } - - /** - * @dataProvider get_check_attr_spec_rule_value_casei_data - * @group allowed-tags-private-methods - */ - public function test_check_attr_spec_rule_value_casei( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $got = $this->call_private_method( $sanitizer, 'check_attr_spec_rule_value_casei', [ $node, $data['attr_name'], $data['attr_spec_rule'] ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - public function get_check_attr_spec_rule_disallowed_value_regex() { - return [ - 'no_attributes' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'value_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'disallowed_value_regex' => '(not_this|or_this)', - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'disallowed_value_regex' => '(not_this|or_this)', - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'value_no_attr' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'disallowed_value_regex' => '(not_this|or_this)', - ], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'value_alternative_attr_name_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'disallowed_value_regex' => '(not_this|or_this)', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'value_alternative_attr_name_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'disallowed_value_regex' => '(not_this|or_this)', - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - ]; - } - - /** - * Gets the test data for test_check_attr_spec_rule_valid_url(). - * - * @return array The test data. - */ - public function get_check_attr_spec_rule_valid_url() { - return [ - 'no_attribute' => [ - '', - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'correct_url' => [ - '', - AMP_Rule_Spec::PASS, - ], - 'correct_url_leading_space' => [ - '', - AMP_Rule_Spec::PASS, - ], - 'non_parseable_url' => [ - '', - AMP_Rule_Spec::FAIL, - ], - 'wrong_protocol' => [ - '', - AMP_Rule_Spec::FAIL, - ], - 'wrong_host' => [ - '', - AMP_Rule_Spec::FAIL, - ], - ]; - } - - /** - * Tests check_attr_spec_rule_valid_url. - * - * @dataProvider get_check_attr_spec_rule_valid_url - * @group allowed-tags-private-methods - * @covers AMP_Tag_And_Attribute_Sanitizer::check_attr_spec_rule_valid_url() - * - * @param array $source The HTML source to test. - * @param string $expected The expected return value. - * @throws ReflectionException If it's not possible to create a reflection to call the private method. - */ - public function test_check_attr_spec_rule_valid_url( $source, $expected ) { - $node_tag_name = 'a'; - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $node = $dom->getElementsByTagName( $node_tag_name )->item( 0 ); - $attr_name = 'baz'; - $attr_spec_rule = [ 'value_url' => [] ]; - - $this->assertEquals( - $expected, - $this->call_private_method( $sanitizer, 'check_attr_spec_rule_valid_url', [ $node, $attr_name, $attr_spec_rule ] ), - sprintf( 'using source: %s', $source ) - ); - } - - /** - * @dataProvider get_check_attr_spec_rule_disallowed_value_regex - * @group allowed-tags-private-methods - */ - public function test_check_attr_spec_rule_disallowed_value_regex( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $got = $this->call_private_method( $sanitizer, 'check_attr_spec_rule_disallowed_value_regex', [ $node, $data['attr_name'], $data['attr_spec_rule'] ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - public function get_check_attr_spec_rule_allowed_protocol() { - return [ - 'no_attributes' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'protocol_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'protocol_pass_leading_space' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'protocol_multiple_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'protocol_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'protocol_multiple_fail' => [ - [ - 'source' => '', - 'node_tag_name' => 'img', - 'attr_name' => 'srcset', - 'attr_spec_rule' => [ - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'protocol_alternative_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'alternative_names' => [ - 'attribute1_alternative1', - ], - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'protocol_alternative_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'alternative_names' => [ - 'attribute1_alternative1', - ], - 'value_url' => [ - 'protocol' => [ - 'http', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'protocol_mailto_pass' => [ - [ - 'source' => '', - 'node_tag_name' => 'a', - 'attr_name' => 'href', - 'attr_spec_rule' => [ - 'value_url' => [ - 'protocol' => [ - 'mailto', - 'https', - ], - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - ]; - } - - /** - * Gets the test data for test_parse_protocol(). - * - * @return array The test data. - */ - public function get_parse_protocol_data() { - return [ - 'empty_string' => [ - '', - false, - ], - 'only_space' => [ - ' ', - false, - ], - 'traditional_https' => [ - 'https://example.com', - 'https', - ], - 'trailing_space' => [ - 'https://foo.com ', - 'https', - ], - 'no_colon' => [ - '//image.png ', - false, - ], - 'mailto' => [ - 'mailto:?&subject=Foo&body=https://example.com/', - 'mailto', - ], - ]; - } - - /** - * Tests parse_protocol. - * - * @dataProvider get_parse_protocol_data - * @group allowed-tags-private-methods - * @covers AMP_Tag_And_Attribute_Sanitizer::parse_protocol() - * - * @param array $url The URL to parse. - * @param string $expected The expected return value. - * @throws ReflectionException If it's not possible to create a reflection to call the private method. - */ - public function test_parse_protocol( $url, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( '' ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $this->assertEquals( - $expected, - $this->call_private_method( $sanitizer, 'parse_protocol', [ $url ] ) - ); - } - - /** - * Gets the test data for test_normalize_url_from_attribute_value(). - * - * @return array The test data. - */ - public function get_normalize_url_data() { - $normalized_url = 'https://example.com'; - - return [ - 'nothing_to_remove' => [ - 'https://example.com', - ], - 'empty_string' => [ - '', - ], - 'only_space' => [ - ' ', - '', - ], - 'leading_space' => [ - ' https://example.com', - $normalized_url, - ], - 'leading_tab' => [ - "\thttps://example.com", - $normalized_url, - ], - 'trailing_linefeed' => [ - "https://example.com \n", - $normalized_url, - ], - 'trailing_space' => [ - 'https://example.com ', - $normalized_url, - ], - 'enclosed_in_spaces' => [ - ' https://example.com ', - $normalized_url, - ], - 'space_inside' => [ - ' https: //exam ple.com ', - 'https: //exam ple.com', - ], - 'tabs_inside' => [ - "https:\t//exam\tple.com ", - $normalized_url, - ], - 'leading_slashes' => [ - '//example.com', - ], - 'url_encoded_space_not_removed' => [ - 'https://example.com?foo=++baz', - ], - ]; - } - - /** - * Tests normalize_url_from_attribute_value. - * - * @dataProvider get_normalize_url_data - * @group allowed-tags-private-methods - * @covers AMP_Tag_And_Attribute_Sanitizer::normalize_url_from_attribute_value() - * - * @param array $url The URL to normalize. - * @param string|null $expected The expected return value. - * @throws ReflectionException If it's not possible to create a reflection to call the private method. - */ - public function test_normalize_url_from_attribute_value( $url, $expected = null ) { - if ( null === $expected ) { - $expected = $url; - } - - $dom = AMP_DOM_Utils::get_dom_from_content( '' ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $this->assertEquals( - $expected, - $this->call_private_method( $sanitizer, 'normalize_url_from_attribute_value', [ $url ] ) - ); - } - - /** - * @dataProvider get_check_attr_spec_rule_allowed_protocol - * @group allowed-tags-private-methods - */ - public function test_check_attr_spec_rule_allowed_protocol( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $got = $this->call_private_method( $sanitizer, 'check_attr_spec_rule_allowed_protocol', [ $node, $data['attr_name'], $data['attr_spec_rule'] ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } - - public function get_check_attr_spec_rule_disallowed_relative() { - return [ - 'no_attributes' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [], - ], - AMP_Rule_Spec::NOT_APPLICABLE, - ], - 'disallowed_relative_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'disallowed_relative_multiple_pass' => [ - [ - 'source' => '', - 'node_tag_name' => 'img', - 'attr_name' => 'srcset', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'disallowed_relative_alternative_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'disallowed_relative_alternative_multiple_pass' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::PASS, - ], - 'disallowed_relative_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'disallowed_relative_multiple_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'disallowed_relative_alternative_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'attribute1', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - 'alternative_names' => [ - 'attribute1_alternative1', - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - 'disallowed_relative_alternative_multiple_fail' => [ - [ - 'source' => '
        ', - 'node_tag_name' => 'div', - 'attr_name' => 'srcset', - 'attr_spec_rule' => [ - 'value_url' => [ - 'allow_relative' => false, - ], - 'alternative_names' => [ - 'source_set', - ], - ], - ], - AMP_Rule_Spec::FAIL, - ], - ]; - } - - /** - * @dataProvider get_check_attr_spec_rule_disallowed_relative - * @group allowed-tags-private-methods - */ - public function test_check_attr_spec_rule_disallowed_relative( $data, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $data['source'] ); - $node = $dom->getElementsByTagName( $data['node_tag_name'] )->item( 0 ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - - $got = $this->call_private_method( $sanitizer, 'check_attr_spec_rule_disallowed_relative', [ $node, $data['attr_name'], $data['attr_spec_rule'] ] ); - - $this->assertEquals( $expected, $got, sprintf( "using source: %s\n%s", $data['source'], wp_json_encode( $data ) ) ); - } -} diff --git a/tests/php/test-amp-tumblr-embed-handler.php b/tests/php/test-amp-tumblr-embed-handler.php deleted file mode 100644 index 1ba5a50789c..00000000000 --- a/tests/php/test-amp-tumblr-embed-handler.php +++ /dev/null @@ -1,187 +0,0 @@ - $body, - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - } - - /** - * Get conversion data. - * - * @return array - */ - public function get_conversion_data() { - return [ - 'no_embed' => [ - '', - '', - ], - - 'grant-wood-american-gothic' => [ - 'https://ifpaintingscouldtext.tumblr.com/post/92003045635/grant-wood-american-gothic-1930', - 'https://ifpaintingscouldtext.tumblr.com/post/92003045635/grant-wood-american-gothic-1930', - ], - - 'how-do-vaccines-work' => [ - 'https://teded.tumblr.com/post/184736320764/how-do-vaccines-work', - 'https://teded.tumblr.com/post/184736320764/how-do-vaccines-work', - ], - ]; - } - - /** - * Test conversion. - * - * @covers ::sanitize_raw_embeds() - * @dataProvider get_conversion_data - * - * @param string $url URL. - * @param string $expected Expected content. - */ - public function test__conversion( $url, $expected ) { - $embed = new AMP_Tumblr_Embed_Handler(); - - // Check with all filters applied (including wpautop). - $content = apply_filters( 'the_content', $url ); - $dom = AMP_DOM_Utils::get_dom_from_content( $content ); - $embed->sanitize_raw_embeds( $dom ); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $this->assertEqualMarkup( $expected, $content ); - - if ( $url && function_exists( 'do_blocks' ) ) { - $embed_block = "\n
        \n{$url}\n
        \n"; - $content = apply_filters( 'the_content', $embed_block ); - $dom = AMP_DOM_Utils::get_dom_from_content( $content ); - $embed->sanitize_raw_embeds( $dom ); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( - '
        ' . $expected . '
        ', - $content - ); - } - - // Check with no filters applied. - $dom = AMP_DOM_Utils::get_dom_from_content( ( new WP_Embed() )->shortcode( [], $url ) ); - $embed->sanitize_raw_embeds( $dom ); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $this->assertEqualMarkup( $expected, $content ); - - // Check with no filters applied and with the script pre-remoevd. - $content = ( new WP_Embed() )->shortcode( [], $url ); - $content = preg_replace( '##', '', $content ); - $dom = AMP_DOM_Utils::get_dom_from_content( $content ); - $embed->sanitize_raw_embeds( $dom ); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $this->assertEqualMarkup( $expected, $content ); - } - - /** - * Data for test_get_scripts(). - * - * @return array Data. - */ - public function get_scripts_data() { - return [ - 'not_converted' => [ - '

        Hello World.

        ', - [], - ], - 'converted' => [ - 'https://ifpaintingscouldtext.tumblr.com/post/92003045635/grant-wood-american-gothic-1930' . PHP_EOL, - [ 'amp-iframe' => true ], - ], - ]; - } - - /** - * Test AMP_Tag_And_Attribute_Sanitizer::get_scripts(). - * - * @dataProvider get_scripts_data - * - * @param string $source Source content. - * @param array $expected Expected scripts. - */ - public function test_get_scripts( $source, $expected ) { - $embed = new AMP_Tumblr_Embed_Handler(); - - $filtered_content = apply_filters( 'the_content', $source ); - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $whitelist_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $whitelist_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $whitelist_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-amp-twitter-embed-handler.php b/tests/php/test-amp-twitter-embed-handler.php deleted file mode 100644 index 67b6f212d3c..00000000000 --- a/tests/php/test-amp-twitter-embed-handler.php +++ /dev/null @@ -1,250 +0,0 @@ -prevent_block_pre_render(); - - add_filter( 'pre_http_request', [ $this, 'mock_http_request' ], 10, 3 ); - } - - /** - * After a test method runs, reset any state in WordPress the test method might have changed. - */ - public function tear_down() { - remove_filter( 'pre_http_request', [ $this, 'mock_http_request' ] ); - parent::tear_down(); - } - - /** - * Mock HTTP request. - * - * @param mixed $preempt Whether to preempt an HTTP request's return value. Default false. - * @param mixed $r HTTP request arguments. - * @param string $url The request URL. - * @return array Response data. - */ - public function mock_http_request( $preempt, $r, $url ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $preempt; - } - - $host = wp_parse_url( $url, PHP_URL_HOST ); - - if ( 'publish.twitter.com' !== $host ) { - return $preempt; - } - - if ( false !== strpos( $url, '987437752164737025' ) ) { - $body = $this->oembed_response_1; - } else { - $body = $this->oembed_response_2; - } - - unset( $r ); - - return [ - 'body' => $body, - 'headers' => [], - 'response' => [ - 'code' => 200, - 'message' => 'ok', - ], - 'cookies' => [], - 'http_response' => null, - ]; - } - - /** - * Get conversion data. - * - * @return array - */ - public function get_conversion_data() { - $overflow_button = ''; - - return [ - 'no_embed' => [ - '

        Hello world.

        ', - '

        Hello world.

        ' . PHP_EOL, - ], - 'url_simple' => [ - 'https://twitter.com/wordpress/status/987437752164737025' . PHP_EOL, - "$overflow_button
        \n

        Celebrate the WordPress 15th Anniversary on May 27 https://t.co/jv62WkI9lr pic.twitter.com/4ZECodSK78

        \n

        — WordPress (@WordPress) April 20, 2018

        \n\n", - ], - 'url_with_big_tweet_id' => [ - 'https://twitter.com/wordpress/status/705219971425574912' . PHP_EOL, - "$overflow_button
        \n

        On our way to the #GoogleDance! #SMX 💃🏻 pic.twitter.com/N8kZ9M3eN4

        \n

        — Search Engine Land (@sengineland) March 3, 2016

        \n\n", - ], - 'timeline_url_with_profile' => [ - 'https://twitter.com/wordpress' . PHP_EOL, - "

        $overflow_button

        \n", - ], - 'timeline_url_with_likes' => [ - 'https://twitter.com/wordpress/likes' . PHP_EOL, - "

        $overflow_button

        \n", - ], - 'timeline_url_with_list' => [ - 'https://twitter.com/wordpress/lists/random_list' . PHP_EOL, - "

        $overflow_button

        \n", - ], - 'timeline_url_with_list2' => [ - 'https://twitter.com/robertnyman/lists/web-gdes' . PHP_EOL, - "

        $overflow_button

        \n", - ], - ]; - } - - /** - * Test conversion. - * - * @dataProvider get_conversion_data - * @param string $source Source. - * @param string $expected Expected content. - */ - public function test__conversion( $source, $expected ) { - $embed = new AMP_Twitter_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEquals( $expected, $content ); - } - - public function get_scripts_data() { - return [ - 'not_converted' => [ - '

        Hello World.

        ', - [], - ], - 'converted' => [ - 'https://twitter.com/altjoen/status/987437752164737025' . PHP_EOL, - [ 'amp-twitter' => true ], - ], - ]; - } - - /** - * Test get_scripts(). - * - * @dataProvider get_scripts_data - * - * @param string $source Source content. - * @param array $expected Expected scripts. - */ - public function test__get_scripts( $source, $expected ) { - $embed = new AMP_Twitter_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } - - /** - * Data for test__raw_embed_sanitizer. - * - * @return array Data. - */ - public function get_raw_embed_dataset() { - $overflow_button = ''; - - return [ - 'no_embed' => [ - '

        Hello world.

        ', - '

        Hello world.

        ', - ], - 'embed_blockquote_without_twitter' => [ - '
        lorem ipsum
        ', - '
        lorem ipsum
        ', - ], - - 'blockquote_embed' => [ - wpautop( ' ' ), // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Arrays.ArrayDeclarationSpacing.ArrayItemNoNewLine - '' . "\n\n", - ], - - 'blockquote_embed_with_data_conversation' => [ - wpautop( ' ' ), // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Arrays.ArrayDeclarationSpacing.ArrayItemNoNewLine - '' . "\n\n", - ], - - 'blockquote_embed_with_data_theme' => [ - wpautop( ' ' ), // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Arrays.ArrayDeclarationSpacing.ArrayItemNoNewLine - '' . "\n\n", - ], - - 'blockquote_embed_not_autop' => [ - ' ', // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Arrays.ArrayDeclarationSpacing.ArrayItemNoNewLine - ' ', - ], - ]; - } - - /** - * Test raw_embed_sanitizer. - * - * @param string $source Content. - * @param string $expected Expected content. - * @dataProvider get_raw_embed_dataset - * @covers AMP_Twitter_Embed_Handler::sanitize_raw_embeds() - */ - public function test__raw_embed_sanitizer( $source, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $embed = new AMP_Twitter_Embed_Handler(); - - $embed->sanitize_raw_embeds( $dom ); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEquals( $expected, $content ); - } -} diff --git a/tests/php/test-amp-video-sanitizer.php b/tests/php/test-amp-video-sanitizer.php deleted file mode 100644 index 488907c3378..00000000000 --- a/tests/php/test-amp-video-sanitizer.php +++ /dev/null @@ -1,433 +0,0 @@ -remove_added_uploads(); - } - parent::tear_down(); - } - - /** @covers ::get_selector_conversion_mapping() */ - public function test_get_selector_conversion_mapping() { - $dom = Document::fromHtmlFragment( '

        Hello world

        ' ); - - $with_defaults = new AMP_Video_Sanitizer( $dom ); - $this->assertEquals( - [ 'video' => [ 'amp-video', 'amp-youtube' ] ], - $with_defaults->get_selector_conversion_mapping() - ); - - $with_false_native_used = new AMP_Video_Sanitizer( $dom, [ 'native_video_used' => false ] ); - $this->assertEquals( - [ 'video' => [ 'amp-video', 'amp-youtube' ] ], - $with_false_native_used->get_selector_conversion_mapping() - ); - - $with_true_native_used = new AMP_Video_Sanitizer( $dom, [ 'native_video_used' => true ] ); - $this->assertEquals( - [], - $with_true_native_used->get_selector_conversion_mapping() - ); - } - - /** - * Get data. - * - * @return array - */ - public function get_data() { - return [ - 'no_videos' => [ - '

        Lorem Ipsum Demet Delorit.

        ', - '

        Lorem Ipsum Demet Delorit.

        ', - ], - - 'simple_video' => [ - '', - 'https://example.com/video.mp4', - [ - 'add_noscript_fallback' => true, - ], - ], - - 'simple_video_without_noscript' => [ - '', - 'https://example.com/video.mp4', - [ - 'add_noscript_fallback' => false, - ], - ], - - 'video_with_aspect-ratio' => [ - '', - 'https://example.com/video.mp4', - [ - 'add_noscript_fallback' => false, - ], - ], - - 'video_with_aspect-ratio_and_more' => [ - '', - 'https://example.com/video.mp4', - [ - 'add_noscript_fallback' => false, - ], - ], - - 'video_without_dimensions' => [ - '', - 'https://example.com/file.mp4', - ], - - 'video_with_autoplay' => [ - '', - 'https://example.com/file.mp4', - ], - - 'local_video_without_dimensions' => [ - sprintf( '', '{{video_url}}' ), - sprintf( '%1$s', '{{video_url}}' ), - ], - - 'local_video_without_dimensions_and_native' => [ - sprintf( '', '{{video_url}}' ), - sprintf( '', '{{video_url}}', ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ), - [ - 'native_video_used' => true, - ], - ], - - 'local_video_without_dimensions_and_with_data_layout' => [ - sprintf( '', '{{video_url}}' ), - sprintf( '%1$s', '{{video_url}}' ), - ], - - 'local_video_without_dimensions_and_with_fixed_height_layout' => [ - sprintf( '', '{{video_url}}' ), - sprintf( '%1$s', '{{video_url}}' ), - ], - - 'layout_fill_video_without_dimensions' => [ - '', - 'https://example.com/file.mp4', - ], - - 'data_layout_fill_video_without_dimensions' => [ - '', - 'https://example.com/file.mp4', - ], - - 'layout_nodisplay_video_without_dimensions' => [ - '', - 'https://example.com/file.mp4', - ], - - 'layout_fixed_video_without_dimensions' => [ - '', - 'https://example.com/file.mp4', - ], - - 'autoplay_attribute' => [ - '', - 'https://example.com/video.mp4', - ], - - 'autoplay_attribute__false' => [ - '', - 'https://example.com/video.mp4', - ], - - 'video_with_allowlisted_attributes__enabled' => [ - '', - 'https://example.com/video.mp4', - ], - - 'video_with_allowlisted_attributes__disabled' => [ - '', - 'https://example.com/video.mp4', - ], - - 'video_with_custom_attribute' => [ - '', - 'https://example.com/video.mp4', - ], - - 'video_with_sizes_attribute_is_overridden' => [ - '', - 'https://example.com/file.mp4', - ], - - 'video_with_children' => [ - ' - - ', - ' - - - - https://example.com/video.mp4 - - - ', - ], - - 'video_with_layout_from_editor_fill' => [ - '
        ', - '
        https://example.com/file.mp4
        ', - ], - - 'video_with_layout_from_editor_fixed' => [ - '
        ', - '
        https://example.com/file.mp4
        ', - ], - - 'video_with_noloading_from_editor' => [ - '
        ', - '
        https://example.com/file.mp4
        ', - ], - - 'multiple_same_video' => [ - ' - - - - - ', - ' - https://example.com/video.mp4 - https://example.com/video.mp4 - https://example.com/video.mp4 - https://example.com/video.mp4 - ', - ], - - 'multiple_different_videos' => [ - ' - - - - ', - ' - https://example.com/video1.mp4 - https://example.com/video2.ogv - https://example.com/video3.webm - ', - ], - - 'https_not_required' => [ - '', - 'https://example.com/video.mp4', - ], - - 'http_video_with_children' => [ - ' - - ', - ' - - - - - http://example.com/video.mp4 - - - ', - ], - - 'amp_video_with_fallback' => [ - '', - null, - ], - - 'video_with_fallback' => [ - '
        ', - '', - ], - - 'test_with_dev_mode' => [ - '', - null, // No change. - [ - 'add_dev_mode' => true, - ], - ], - ]; - } - - /** - * Get video attachment ID. - * - * @return int|WP_Error ID or error. - */ - protected function get_video_attachment_id() { - $temp_file = trailingslashit( get_temp_dir() ) . 'video-converter-test-' . wp_generate_uuid4() . '.mp4'; - copy( DIR_TESTDATA . '/uploads/small-video.mp4', $temp_file ); - $attachment_id = self::factory()->attachment->create_upload_object( $temp_file ); - - // Remove the file extension from the post_title media_handle_upload(). - $attachment = get_post( $attachment_id, ARRAY_A ); - $attachment['post_title'] = str_replace( '.mp4', '', $attachment['post_title'] ); - $attachment['post_name'] = str_replace( '-mp4', '', $attachment['post_name'] ); - wp_update_post( wp_slash( $attachment ) ); - - return $attachment_id; - } - - /** - * Test converter. - * - * @dataProvider get_data - * @covers ::sanitize() - * @covers ::filter_video_dimensions() - * @covers ::filter_attributes() - * - * @param string $source Source. - * @param string $expected Expected. - * @param array $args Sanitizer args. - */ - public function test_converter( $source, $expected = null, $args = [] ) { - if ( null === $expected ) { - $expected = $source; - } - - if ( false !== strpos( $source, '{{video_url}}' ) ) { - $video_url = set_url_scheme( wp_get_attachment_url( $this->get_video_attachment_id() ), 'https' ); - $source = str_replace( '{{video_url}}', esc_url( $video_url ), $source ); - $expected = str_replace( '{{video_url}}', esc_url( $video_url ), $expected ); - } - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - if ( ! empty( $args['add_dev_mode'] ) ) { - $dom->documentElement->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - } - - $sanitizer = new AMP_Video_Sanitizer( $dom, $args ); - $sanitizer->sanitize(); - - $sanitizer = new AMP_Script_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( $expected, $content ); - } - - /** - * Test that HTTPS is enforced. - * - * @covers ::sanitize() - */ - public function test__https_required() { - $source = ''; - $expected = ''; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Video_Sanitizer( - $dom, - [ - 'require_https_src' => true, - ] - ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $this->assertEqualMarkup( $expected, $content ); - } - - /** - * Test that scripts don't picked up as expected. - * - * @covers ::sanitize() - * @covers ::get_scripts() - */ - public function test_get_scripts__didnt_convert() { - $source = '

        Hello World

        '; - $expected = []; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Video_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $sanitizer->get_scripts(), - $validating_sanitizer->get_scripts() - ); - $this->assertEquals( $expected, $scripts ); - } - - /** - * Test that scripts get picked up. - * - * @covers ::sanitize() - * @covers ::get_scripts() - */ - public function test_get_scripts__did_convert() { - $source = ''; - $expected = [ 'amp-video' => true ]; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Video_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $sanitizer->get_scripts(), - $validating_sanitizer->get_scripts() - ); - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-amp-vimeo-embed-handler.php b/tests/php/test-amp-vimeo-embed-handler.php deleted file mode 100644 index d7e7e3549bd..00000000000 --- a/tests/php/test-amp-vimeo-embed-handler.php +++ /dev/null @@ -1,166 +0,0 @@ - [ - '

        Hello world.

        ', - '

        Hello world.

        ' . PHP_EOL, - ], - - 'url_simple' => [ - 'https://vimeo.com/172355597' . PHP_EOL, - '

        ' . PHP_EOL, - ], - - 'url_unlisted' => [ - 'https://vimeo.com/172355597/abcdef0123' . PHP_EOL, - '

        ' . PHP_EOL, - ], - - 'url_player' => [ - 'https://player.vimeo.com/video/172355597' . PHP_EOL, - '

        ' . PHP_EOL, - ], - ]; - } - - /** - * Test conversion. - * - * @dataProvider get_conversion_data - * - * @param string $source Source. - * @param string $expected Expected. - */ - public function test__conversion( $source, $expected ) { - $embed = new AMP_Vimeo_Embed_Handler(); - $embed->register_embed(); - $filtered_content = apply_filters( 'the_content', $source ); - - $this->assertEquals( $expected, $filtered_content ); - } - - /** - * Get scripts data. - * - * @return array Scripts data. - */ - public function get_scripts_data() { - return [ - 'not_converted' => [ - '

        Hello World.

        ', - [], - ], - 'converted' => [ - 'https://vimeo.com/172355597' . PHP_EOL, - [ 'amp-vimeo' => true ], - ], - ]; - } - - /** - * Test get_scripts(). - * - * @dataProvider get_scripts_data - * @covers AMP_Vimeo_Embed_Handler::get_scripts() - * - * @param string $source Source. - * @param string $expected Expected. - */ - public function test__get_scripts( $source, $expected ) { - $embed = new AMP_Vimeo_Embed_Handler(); - $embed->register_embed(); - $source = apply_filters( 'the_content', $source ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( AMP_DOM_Utils::get_dom_from_content( $source ) ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } - - /** - * Gets the test data for test_video_override(). - * - * @return array The test data. - */ - public function get_video_override_data() { - return [ - 'no_src_empty_html' => [ - '', - [ 'foo' => 'baz' ], - null, - ], - 'no_src_with_html' => [ - 'Initial HTML here', - [ 'foo' => 'baz' ], - null, - ], - 'non_vimeo_src' => [ - 'Initial HTML here', - [ 'src' => 'https://youtube.com/1234567' ], - null, - ], - 'non_numeric_video_id' => [ - 'Initial HTML here', - [ 'src' => 'https://vimeo.com/abcdefg' ], - '', - ], - 'valid_video_id' => [ - 'Initial HTML here', - [ 'src' => 'https://vimeo.com/1234567' ], - '', - ], - 'http_url' => [ - 'Initial HTML here', - [ 'src' => 'https://vimeo.com/1234567' ], - '', - ], - ]; - } - - /** - * Test video_override(). - * - * @dataProvider get_video_override_data - * @covers AMP_Vimeo_Embed_Handler::video_override() - * - * @param string $html The initial HTML. - * @param array $attr The attributes of the shortcode. - * @param string $expected The expected return value. - */ - public function test_video_override( $html, $attr, $expected ) { - if ( null === $expected ) { - $expected = $html; - } - - $embed = new AMP_Vimeo_Embed_Handler(); - $this->assertEquals( $expected, $embed->video_override( $html, $attr ) ); - } -} diff --git a/tests/php/test-amp-wordpress-embed-handler.php b/tests/php/test-amp-wordpress-embed-handler.php deleted file mode 100644 index 391c617b694..00000000000 --- a/tests/php/test-amp-wordpress-embed-handler.php +++ /dev/null @@ -1,436 +0,0 @@ - - - - - - - '; - } elseif ( self::WP_58_STABLE_POST_URL === $url ) { - $content_type = 'text/html'; - $body = ' - - - - - - - '; - } elseif ( - strpos( $url, 'https://amp-wp.org/wp-json/oembed/1.0/embed' ) === 0 - && - isset( $query_vars['url'] ) - && - self::WP_58_STABLE_POST_URL === $query_vars['url'] - ) { - $content_type = 'application/json'; - $body = '{"version":"1.0","provider_name":"AMP for WordPress","provider_url":"https:\\/\\/amp-wp.org","author_name":"Alberto Medina","author_url":"https:\\/\\/amp-wp.org\\/author\\/albertomedina\\/","title":"Introducing v2.0 of the official AMP Plugin for WordPress","type":"rich","width":500,"height":282,"html":"
        Introducing v2.0 of the official AMP Plugin for WordPress<\\/a><\\/blockquote> - ', - ' - -
        -

        Proposal for a Performance team

        -
        - - - ', - ], - 'post_embed_html_custom_html_block' => [ - // This is the embed code that the user can copy into a non-WordPress context. See get_post_embed_html(). - ' - -
        Proposal for a Performance team
        - - ', - ' - -
        - Proposal for a Performance team -
        - -
        - ', - ], - 'internal_post_embed_block' => [ - ' - -
        - {{url}} -
        - - ', - sprintf( - ' -
        -
        Internal
        -
        - ', - esc_attr( '“Internal” — ' . get_bloginfo( 'blogname' ) ) - ), - [ - 'post_title' => 'Internal', - ], - ], - 'internal_post_embed_shortcode' => [ - '[embed]{{url}}[/embed]', - sprintf( - ' - -
        -

        Internal

        -
        - -
        - ', - esc_attr( '“Internal” — ' . get_bloginfo( 'blogname' ) ) - ), - [ - 'post_title' => 'Internal', - ], - ], - ]; - } - - /** - * Test conversion. - * - * @covers ::sanitize_raw_embeds() - * @covers ::create_amp_wordpress_embed_and_replace_node() - * @dataProvider get_conversion_data - * - * @param string $source Source. - * @param string $expected Expected. - * @param array $post_args Post args. - */ - public function test__conversion( $source, $expected, $post_args = [] ) { - - if ( $post_args ) { - $post_id = self::factory()->post->create( $post_args ); - $source = str_replace( '{{url}}', get_permalink( $post_id ), $source ); - $expected = str_replace( '{{url}}', get_permalink( $post_id ), $expected ); - $expected = str_replace( - '{{data_url}}', - str_replace( '&', '&', esc_url( add_query_arg( 'embed', 'true', get_permalink( $post_id ) ) ) ), - $expected - ); - } - - // Capture the response bodies to facilitate updating the request mocking. - $http_response_bodies = []; - add_filter( - 'pre_http_request', - function ( $pre, $args, $url ) use ( &$http_response_bodies ) { - if ( false !== $pre ) { - $http_response_bodies[ $url ] = wp_remote_retrieve_body( $pre ); - } - return $pre; - }, - 1000, - 3 - ); - add_filter( - 'http_response', - static function ( $response, $args, $url ) use ( &$http_response_bodies ) { - $http_response_bodies[ $url ] = wp_remote_retrieve_body( $response ); - return $response; - }, - 1000, - 3 - ); - - $embed = new AMP_WordPress_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export - $this->assertSimilarMarkup( $expected, $content, 'Response bodies for HTTP requests: ' . var_export( $http_response_bodies, true ) . "\nActual markup: $content" ); - } - - /** - * Get scripts data. - * - * @return array Scripts data. - */ - public function get_scripts_data() { - return [ - 'not_converted' => [ - '

        Hello World.

        ', - [], - ], - 'converted' => [ - self::WP_58_STABLE_POST_URL . PHP_EOL, - [ 'amp-wordpress-embed' => true ], - ], - ]; - } - - /** - * Test get_scripts(). - * - * @dataProvider get_scripts_data - * @covers ::get_scripts() - * - * @param string $source Source. - * @param string $expected Expected. - */ - public function test__get_scripts( $source, $expected ) { - $embed = new AMP_WordPress_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $embed->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } - - /** - * Test register_embed and unregister_embed. - * - * @covers ::register_embed() - * @covers ::unregister_embed() - */ - public function test_register_and_unregister_embed() { - $embed = new AMP_WordPress_Embed_Handler(); - - $this->assertEquals( 10, has_action( 'wp_head', 'wp_oembed_add_host_js' ) ); - - $embed->register_embed(); - $this->assertFalse( has_action( 'wp_head', 'wp_oembed_add_host_js' ) ); - - $embed->unregister_embed(); - $this->assertEquals( 10, has_action( 'wp_head', 'wp_oembed_add_host_js' ) ); - } -} diff --git a/tests/php/test-amp.php b/tests/php/test-amp.php deleted file mode 100644 index 60bdea25bf0..00000000000 --- a/tests/php/test-amp.php +++ /dev/null @@ -1,113 +0,0 @@ - [ - null, - false, - AMP_Theme_Support::READER_MODE_SLUG, - ], - 'no_args' => [ - [], - false, - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'paired_implied' => [ - [ - 'template_dir' => 'amp-templates', - ], - false, - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'paired_with_template_dir' => [ - [ - AMP_Theme_Support::PAIRED_FLAG => true, - 'template_dir' => 'amp-templates', - ], - false, - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'canonical_with_template_dir' => [ - [ - // This should be a rare scenario, as standard mode should mean no separate templates. - AMP_Theme_Support::PAIRED_FLAG => false, - 'template_dir' => 'amp-templates', - ], - true, - AMP_Theme_Support::STANDARD_MODE_SLUG, - ], - 'paired_without_template_dir' => [ - [ - AMP_Theme_Support::PAIRED_FLAG => true, - ], - false, - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - ]; - } - - /** - * Test amp_is_canonical(). - * - * @dataProvider get_amp_is_canonical_test_data - * @covers ::amp_is_canonical() - * @covers AMP_Theme_Support::get_support_mode_added_via_theme() - * @covers AMP_Theme_Support::read_theme_support() - * @param mixed $theme_support_args Theme support args. - * @param bool $is_canonical Whether canonical. - * @param string $expected_mode Expected mode. - */ - public function test_amp_is_canonical( $theme_support_args, $is_canonical, $expected_mode ) { - delete_option( AMP_Options_Manager::OPTION_NAME ); - if ( isset( $theme_support_args ) ) { - if ( is_array( $theme_support_args ) ) { - add_theme_support( AMP_Theme_Support::SLUG, $theme_support_args ); - } else { - add_theme_support( AMP_Theme_Support::SLUG ); - } - } - $this->assertSame( $expected_mode, AMP_Options_Manager::get_option( Option::THEME_SUPPORT ) ); - $this->assertSame( $is_canonical, amp_is_canonical() ); - } - - /** - * Test that amp_bootstrap_plugin() will be called as early as possible upon plugins_loaded. - */ - public function test_amp_bootstrap_plugin_priority() { - $this->assertSame( ~PHP_INT_MAX, has_action( 'plugins_loaded', 'amp_bootstrap_plugin' ) ); - } -} diff --git a/tests/php/test-class-amp-accessibility-sanitizer.php b/tests/php/test-class-amp-accessibility-sanitizer.php deleted file mode 100644 index a686350ccdb..00000000000 --- a/tests/php/test-class-amp-accessibility-sanitizer.php +++ /dev/null @@ -1,216 +0,0 @@ -original_wp_current_template_content = $_wp_current_template_content; - } - - /** - * Tear down. - * - * @inheritDoc - */ - public function tear_down() { - - parent::tear_down(); - - global $_wp_current_template_content; - $_wp_current_template_content = $this->original_wp_current_template_content; - } - - public function get_sanitize_test_data() { - return [ - 'valid markup remains unchanged' => [ - '
        ', - '
        ', - ], - - 'missing role is added' => [ - '
        ', - '
        ', - ], - - 'missing tab index is added' => [ - '
        ', - '
        ', - ], - - 'missing both attributes' => [ - '
        ', - '
        ', - ], - - 'no attributes needed on elements' => [ - '', - '', - ], - - 'no attributes needed on ', - '', - ], - ]; - } - - /** - * Test sanitizing to enforce accessibility requirements. - * - * @dataProvider get_sanitize_test_data - * @covers AMP_Accessibility_Sanitizer::sanitize() - * - * @param string $source Source HTML. - * @param string $expected Expected target HTML. - */ - public function test_sanitize( $source, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - - $sanitizer = new AMP_Accessibility_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $actual = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( $expected, $actual ); - } - - /** - * Data provider for $this->test_add_skip_link() - * - * @return string[][] - */ - public function get_skip_link_test_data() { - - $style_element = ''; - - return [ - 'with_id' => [ - 'source' => '
        Hello World!
        ', - 'expected' => $style_element . '
        Hello World!
        ', - ], - 'without_id' => [ - 'source' => '
        Hello World!
        ', - 'expected' => $style_element . '
        Hello World!
        ', - ], - 'without_main_element' => [ - 'source' => '
        Hello World!
        ', - 'expected' => '
        Hello World!
        ', - ], - ]; - - } - - /** - * @dataProvider get_skip_link_test_data - * - * @covers ::add_skip_link() - * - * @param string $source Source HTML. - * @param string $expected Expected target HTML. - */ - public function test_add_skip_link( $source, $expected ) { - - global $_wp_current_template_content, $_wp_theme_features; - - $_wp_current_template_content = true; - $_wp_theme_features['block-templates'] = true; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - - $sanitizer = new AMP_Accessibility_Sanitizer( $dom ); - $sanitizer->add_skip_link(); - - $actual = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( $expected, $actual ); - } - - /** - * @covers ::add_skip_link() - */ - public function test_add_skip_link_for_none_fse_theme() { - - global $_wp_current_template_content, $_wp_theme_features; - - $source = '
        Hello World!
        '; - $expected = '
        Hello World!
        '; - - // Test 1: If it's not block theme. - unset( $_wp_theme_features['block-templates'] ); - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Accessibility_Sanitizer( $dom ); - $sanitizer->add_skip_link(); - $actual = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( $expected, $actual ); - - // Test 2: If it's not block template. - $_wp_theme_features['block-templates'] = true; - $_wp_current_template_content = false; - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Accessibility_Sanitizer( $dom ); - $sanitizer->add_skip_link(); - $actual = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( $expected, $actual ); - - } -} diff --git a/tests/php/test-class-amp-admin-pointer.php b/tests/php/test-class-amp-admin-pointer.php deleted file mode 100644 index 966c839588c..00000000000 --- a/tests/php/test-class-amp-admin-pointer.php +++ /dev/null @@ -1,51 +0,0 @@ -instance = new AMP_Admin_Pointers(); - } - - /** - * Test init. - * - * @covers AMP_Admin_Pointers::init() - */ - public function test_init() { - $this->instance->init(); - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ $this->instance, 'enqueue_scripts' ] ) ); - } -} diff --git a/tests/php/test-class-amp-auto-lightbox-disable-sanitizer.php b/tests/php/test-class-amp-auto-lightbox-disable-sanitizer.php deleted file mode 100644 index 898598bb27a..00000000000 --- a/tests/php/test-class-amp-auto-lightbox-disable-sanitizer.php +++ /dev/null @@ -1,30 +0,0 @@ -Hello World!'; - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - - $sanitizer = new AMP_Auto_Lightbox_Disable_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $this->assertTrue( $dom->body->hasAttribute( 'data-amp-auto-lightbox-disable' ) ); - } -} diff --git a/tests/php/test-class-amp-base-sanitizer.php b/tests/php/test-class-amp-base-sanitizer.php deleted file mode 100644 index c239a0e4d68..00000000000 --- a/tests/php/test-class-amp-base-sanitizer.php +++ /dev/null @@ -1,816 +0,0 @@ -set_private_property( AMP_Validation_Manager::class, 'is_validate_request', false ); - parent::tear_down(); - } - - /** - * Gets data for test_set_layout(). - * - * @return array - */ - public function get_data() { - return [ - 'both_dimensions_included' => [ - [ - 'width' => 100, - 'height' => 100, - 'layout' => 'responsive', - ], - [ - 'width' => 100, - 'height' => 100, - 'layout' => 'responsive', - ], - ], - - 'both_dimensions_missing' => [ - [], - [ - 'height' => 400, - 'layout' => 'fixed-height', - 'width' => 'auto', - ], - ], - - 'both_dimensions_empty' => [ - [ - 'width' => '', - 'height' => '', - ], - [ - 'height' => 400, - 'layout' => 'fixed-height', - 'width' => 'auto', - ], - ], - - 'no_width' => [ - [ - 'height' => 100, - ], - [ - 'height' => 100, - 'layout' => 'fixed-height', - 'width' => 'auto', - ], - ], - - 'no_height' => [ - [ - 'width' => 200, - ], - [ - 'height' => 400, - 'layout' => 'fixed-height', - 'width' => 'auto', - ], - ], - - 'no_layout_specified' => [ - [ - 'width' => 100, - 'height' => 100, - ], - [ - 'width' => 100, - 'height' => 100, - ], - ], - - 'fill_with_bottom_right_removes_empty_style' => [ - [ - 'style' => 'position:absolute;top:0;left:0;right:0;bottom:0', - ], - [ - 'layout' => 'fill', - ], - ], - - 'fill_100p_dimensions_and_absolute_position' => [ - [ - 'style' => 'position:absolute;top:0;left:0;right:0;bottom:0', - 'width' => '100%', - 'height' => '100%', - ], - [ - 'layout' => 'fill', - ], - ], - - 'fill_both_dimension_attrs_and_absolute_position' => [ - [ - 'width' => '100%', - 'height' => '100%', - 'style' => 'position:absolute', - ], - [ - 'layout' => 'fill', - ], - ], - - 'fill_both_dimensions_styles_and_absolute_position' => [ - [ - 'style' => 'width: 100%; height:100%; position:absolute', - ], - [ - 'layout' => 'fill', - ], - ], - - 'fill_both_dimensions_with_unrelated_style' => [ - [ - 'width' => '100%', - 'height' => '100%', - 'style' => 'position:absolute; color:red', - ], - [ - 'layout' => 'fill', - 'style' => 'color:red', - ], - ], - - 'fill_with_bottom_right_keeps_unrelated_styles' => [ - [ - 'style' => 'position:absolute;background-color:white;top:0;left:0;right:0;bottom:0;color:red;', - ], - [ - 'layout' => 'fill', - 'style' => 'background-color:white;color:red', - ], - ], - - 'fill_with_width_height_removes_empty_style' => [ - [ - 'style' => 'position:absolute;top:0;left:0;width:100%;height:100%', - ], - [ - 'layout' => 'fill', - ], - ], - - 'fill_with_width_height_keeps_unrelated_styles' => [ - [ - 'style' => 'position:absolute;background-color:white;top:0;left:0;width:100%;height:100%;color:red;', - ], - [ - 'layout' => 'fill', - 'style' => 'background-color:white;color:red', - ], - ], - - 'fill_can_handle_whitespace_noise' => [ - [ - 'style' => '; position : absolute ; top : 0; color: red; left:0; right:0;;; bottom:0;; ', - ], - [ - 'layout' => 'fill', - 'style' => 'color:red', - ], - ], - ]; - } - - /** @covers ::get_selector_conversion_mapping() */ - public function test_get_selector_conversion_mapping() { - $sanitizer = new StubSanitizer( new Document() ); - $this->assertEquals( [], $sanitizer->get_selector_conversion_mapping() ); - } - - /** @covers ::has_light_shadow_dom() */ - public function test_has_light_shadow_dom() { - $sanitizer = new StubSanitizer( new Document() ); - $this->assertSame( true, $sanitizer->has_light_shadow_dom() ); - } - - /** - * @covers ::update_args() - * @covers ::get_args() - * @covers ::get_arg() - */ - public function test_update_args() { - $sanitizer = new StubSanitizer( - new Document(), - [ - 'foo' => 1, - 'bar' => 2, - ] - ); - $this->assertEquals( - [ - 'foo' => 1, - 'bar' => 2, - ], - $sanitizer->get_args() - ); - $this->assertNull( $sanitizer->get_arg( 'none' ) ); - $this->assertEquals( 1, $sanitizer->get_arg( 'foo' ) ); - $sanitizer->update_args( - [ - 'foo' => 'one', - 'baz' => 'three', - ] - ); - $this->assertEquals( 'one', $sanitizer->get_arg( 'foo' ) ); - $this->assertEquals( - [ - 'foo' => 'one', - 'bar' => 2, - 'baz' => 'three', - ], - $sanitizer->get_args() - ); - $this->assertEquals( 'three', $sanitizer->get_arg( 'baz' ) ); - } - - /** - * Test AMP_Base_Sanitizer::set_layout(). - * - * @dataProvider get_data - * @param array $source_attributes Source Attrs. - * @param array $expected_attributes Expected Attrs. - * @param array $args Args. - * @covers ::set_layout() - */ - public function test_set_layout( $source_attributes, $expected_attributes, $args = [] ) { - $sanitizer = new StubSanitizer( new Document(), $args ); - $returned_attributes = $sanitizer->set_layout( $source_attributes ); - $this->assertEquals( $expected_attributes, $returned_attributes ); - } - - /** - * Get sanitize_dimension data. - * - * @return array Data. - */ - public function get_sanitize_dimension_data() { - return [ - 'empty' => [ - [ '', 'width' ], - '', - ], - - 'empty_space' => [ - [ ' ', 'width' ], - '', - ], - - 'int' => [ - [ 123, 'width' ], - 123, - ], - - 'int_as_string' => [ - [ '123', 'width' ], - 123, - ], - - 'with_px' => [ - [ '567px', 'width' ], - 567, - ], - - '100%_width__with_max' => [ - [ '100%', 'width' ], - 'auto', - [ 'content_max_width' => 600 ], - ], - - '100%_width__no_max' => [ - [ '100%', 'width' ], - 'auto', - ], - - '50%_width__with_max' => [ - [ '50%', 'width' ], - 300, - [ 'content_max_width' => 600 ], - ], - - '%_height' => [ - [ '100%', 'height' ], - '', - ], - - 'non_int' => [ - [ 'abcd', 'width' ], - '', - ], - ]; - } - - /** - * Test AMP_Base_Sanitizer::sanitize_dimension(). - * - * @param array $source_params Source Attrs. - * @param array $expected_value Expected Attrs. - * @param array $args Args. - * @dataProvider get_sanitize_dimension_data - * @covers ::sanitize_dimension() - */ - public function test_sanitize_dimension( $source_params, $expected_value, $args = [] ) { - $sanitizer = new StubSanitizer( new Document(), $args ); - list( $value, $dimension ) = $source_params; - - $actual_value = $sanitizer->sanitize_dimension( $value, $dimension ); - - $this->assertEquals( $expected_value, $actual_value ); - } - - /** - * Tests remove_invalid_child. - * - * @covers ::remove_invalid_child() - * @covers ::should_sanitize_validation_error() - * @covers ::prepare_validation_error() - */ - public function test_remove_invalid_child() { - $parent_tag_name = 'div'; - $dom_document = new Document( '1.0', 'utf-8' ); - $parent = $dom_document->createElement( $parent_tag_name ); - $child = $dom_document->createElement( 'script' ); - $child->setAttribute( 'id', 'foo' ); - $child->setAttribute( 'src', 'http://example.com/bad.js?ver=123' ); - $dom_document->appendChild( $parent ); - $parent->appendChild( $child ); - - $expected_error = [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => $child->nodeName, - 'parent_name' => $parent_tag_name, - 'node_attributes' => [ - 'id' => 'foo', - 'src' => 'http://example.com/bad.js?ver=__normalized__', - ], - 'foo' => 'bar', - 'sources' => null, - 'type' => AMP_Validation_Error_Taxonomy::JS_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ]; - - // Test forcibly sanitized with filter. - add_filter( 'amp_validation_error_sanitized', '__return_true' ); - $this->assertEquals( $child, $parent->firstChild ); - $sanitizer = new AMP_Iframe_Sanitizer( - $dom_document, - [ - 'validation_error_callback' => 'AMP_Validation_Manager::add_validation_error', - ] - ); - $sanitizer->remove_invalid_child( $child, [ 'foo' => 'bar' ] ); - $this->assertEquals( null, $parent->firstChild ); - $this->assertCount( 0, AMP_Validation_Manager::$validation_results ); - remove_filter( 'amp_validation_error_sanitized', '__return_true' ); - - // Test unsanitized. - $child = $dom_document->createElement( 'link' ); - $child->setAttribute( 'id', 'foo' ); - $child->setAttribute( 'href', 'http://example.com/bad.css?ver=123' ); - $expected_error['node_name'] = 'link'; - unset( $expected_error['node_attributes']['src'] ); - $expected_error['node_attributes']['href'] = 'http://example.com/bad.css?ver=__normalized__'; - $expected_error['type'] = AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE; - add_filter( 'amp_validation_error_sanitized', '__return_false' ); - AMP_Validation_Manager::reset_validation_results(); - $parent->appendChild( $child ); - $sanitizer->remove_invalid_child( $child, [ 'foo' => 'bar' ] ); - $this->assertEquals( $child, $parent->firstChild ); - $this->assertCount( 1, AMP_Validation_Manager::$validation_results ); - $this->assertEquals( - [ - 'error' => $expected_error, - 'sanitized' => false, - ], - AMP_Validation_Manager::$validation_results[0] - ); - - // Make sure the validation error is not duplicated since it was not sanitized. - $sanitizer->remove_invalid_child( $child, [ 'foo' => 'bar' ] ); - $this->assertCount( 1, AMP_Validation_Manager::$validation_results ); - AMP_Validation_Manager::$validation_results = null; - } - - /** @covers ::remove_invalid_child() */ - public function test_remove_invalid_child_with_validation_exemptions() { - // When no exemption attributes are present, the element gets removed. - $dom = Document::fromHtml( '
        ' ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( AMP_Base_Sanitizer::class, [ $dom ] ); - $this->assertTrue( $sanitizer->remove_invalid_child( $el ) ); - $this->assertNull( $el->parentNode ); - - // When PX-verified attribute is present, the element does not get removed. - $dom = Document::fromHtml( sprintf( '
        ', ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ) ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( AMP_Base_Sanitizer::class, [ $dom ] ); - $this->assertFalse( $sanitizer->remove_invalid_child( $el ) ); - $this->assertInstanceOf( Element::class, $el->parentNode ); - - // When AMP-unvalidated attribute is present, the element does not get removed. - $dom = Document::fromHtml( sprintf( '
        ', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ) ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( AMP_Base_Sanitizer::class, [ $dom ] ); - $this->assertFalse( $sanitizer->remove_invalid_child( $el ) ); - $this->assertInstanceOf( Element::class, $el->parentNode ); - - // Ensure that element is marked as being AMP-unvalidated if validation callback prevents removal. - $dom = Document::fromHtml( '
        ' ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( - AMP_Base_Sanitizer::class, - [ - $dom, - [ - 'validation_error_callback' => '__return_false', - ], - ] - ); - $this->assertFalse( $sanitizer->remove_invalid_child( $el ) ); - $this->assertInstanceOf( Element::class, $el->parentNode ); - $this->assertTrue( $el->hasAttribute( ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ) ); - } - - /** - * Tests remove_invalid_child with script text normalization. - * - * @covers ::remove_invalid_child() - * @covers ::should_sanitize_validation_error() - * @covers ::prepare_validation_error() - */ - public function test_remove_invalid_child_with_script_text_normalization() { - $dom = new Document( '1.0', 'utf-8' ); - $parent_tag = 'div'; - $parent = $dom->createElement( $parent_tag ); - $dom->appendChild( $parent ); - $child = $dom->createElement( 'script' ); - ob_start(); - ?> - - ', '' ], '', ob_get_clean() ); - $expected_text = "\t\t\n\t\t\tvar exampleSingleQuotedNonce = __SINGLE_QUOTED_STRING__;\n\t\t\tvar exampleSingleQuotedUniqid = __SINGLE_QUOTED_STRING__;\n\t\t\tvar exampleDoubleQuotedNonce = __DOUBLE_QUOTED_STRING__;\n\t\t\tvar exampleDoubleQuotedUniqid = __DOUBLE_QUOTED_STRING__;\n\t\t\tvar exampleDoubleQuotedStringWithEscapedChars = __DOUBLE_QUOTED_STRING__;\n\t\t\tvar exampleSingleQuotedStringWithEscapedChars = __SINGLE_QUOTED_STRING__;\n\t\t\tvar exampleEmptyDoubleString = __DOUBLE_QUOTED_STRING__;\n\t\t\tvar exampleEmptySingleString = __SINGLE_QUOTED_STRING__;\n\t\t\tvar exampleEscapedQuoteInSingleString = __SINGLE_QUOTED_STRING__;\n\t\t\tvar exampleEscapedQuoteInDoubleString = __DOUBLE_QUOTED_STRING__;\n\t\t\tvar exampleRandomNumber1 = __INT__;\n\t\t\tvar exampleRandomNumber2 = __INT__ ;\n\t\t\tvar exampleRandomNumber3=__INT__;\n\t\t\tvar exampleRandomNumber4=__INT__;\n\t\t\tvar exampleRandomFloat1 = __FLOAT__;\n\t\t\tvar exampleRandomFloat2 = __FLOAT__ ;\n\t\t\tvar singleQuotedStringWithSlashes = __SINGLE_QUOTED_STRING__;\n\t\t\tvar doubleQuotedStringWithSlashes = __DOUBLE_QUOTED_STRING__;\n\t\t\tvar exampleObject={\n\t\t\t\t__SINGLE_QUOTED_STRING__:__INT__,\n\t\t\t\t__SINGLE_QUOTED_STRING__:__DOUBLE_QUOTED_STRING__,\n\t\t\t\tbaz:__FLOAT__\n\t\t\t};\n\t\t\tvar exampleRandomObject = {__DOUBLE_QUOTED_STRING__:__DOUBLE_QUOTED_STRING__,__DOUBLE_QUOTED_STRING__:__DOUBLE_QUOTED_STRING__,__DOUBLE_QUOTED_STRING__:__INT__,__DOUBLE_QUOTED_STRING__:__FLOAT__};\n\t\t\n\t\t"; - - $child->appendChild( $dom->createTextNode( $initial_text ) ); - $parent->appendChild( $child ); - - $expected_error = [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => $child->nodeName, - 'parent_name' => $parent_tag, - 'sources' => null, - 'type' => AMP_Validation_Error_Taxonomy::JS_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - 'node_attributes' => [], - 'text' => $expected_text, - ]; - - $sanitizer = new AMP_Iframe_Sanitizer( - $dom, - [ 'validation_error_callback' => 'AMP_Validation_Manager::add_validation_error' ] - ); - - $sanitizer->remove_invalid_child( $child ); - $this->assertNull( $parent->firstChild ); - $this->assertCount( 1, AMP_Validation_Manager::$validation_results ); - $actual_text = AMP_Validation_Manager::$validation_results[0]['error']['text']; - $this->assertEquals( - $expected_text, - $actual_text, - 'Actual text: ' . wp_json_encode( $actual_text ) - ); - - $this->assertEquals( - [ - 'error' => $expected_error, - 'sanitized' => true, - ], - AMP_Validation_Manager::$validation_results[0] - ); - } - - /** - * Tests remove_invalid_child. - * - * @covers ::remove_invalid_child() - * @covers ::is_exempt_from_validation() - */ - public function test_remove_invalid_child_dev_mode() { - $id = 'target'; - $html = sprintf( '
        ', esc_attr( $id ) ); - - // Ensure element is not removed when it and document are in dev mode. - $dom = AMP_DOM_Utils::get_dom_from_content( $html ); - $dom->documentElement->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $element = $dom->getElementById( $id ); - $element->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $sanitizer = new AMP_Audio_Sanitizer( $dom ); - $this->assertFalse( $sanitizer->remove_invalid_child( $element ) ); - $this->assertNotEmpty( $element->parentNode ); - - // Ensure invalid element when it has dev-mode attribute but document does not. - $dom = AMP_DOM_Utils::get_dom_from_content( $html ); - $element = $dom->getElementById( $id ); - $element->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $sanitizer = new AMP_Audio_Sanitizer( $dom ); - $this->assertTrue( $sanitizer->remove_invalid_child( $element ) ); - $this->assertEmpty( $element->parentNode ); - - // Ensure element is removed when document is in dev mode but the element lacks the attribute. - $dom = AMP_DOM_Utils::get_dom_from_content( $html ); - $dom->documentElement->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $element = $dom->getElementById( $id ); - $sanitizer = new AMP_Audio_Sanitizer( $dom ); - $this->assertTrue( $sanitizer->remove_invalid_child( $element ) ); - $this->assertEmpty( $element->parentNode ); - } - - /** - * Tests remove_invalid_child and should_sanitize_validation_error. - * - * @covers ::remove_invalid_attribute() - * @covers ::should_sanitize_validation_error() - * @covers ::prepare_validation_error() - */ - public function test_remove_invalid_attribute() { - $that = $this; - - // Test sanitizing. - $dom = AMP_DOM_Utils::get_dom_from_content( '' ); - $sanitizer = new AMP_Video_Sanitizer( - $dom, - [ - 'validation_error_callback' => static function( $error, $context ) use ( $that ) { - $that->assertEquals( - [ - 'node_name' => 'onload', - 'parent_name' => 'amp-video', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'element_attributes' => - [ - 'id' => 'bar', - 'onload' => 'someFunc()', - ], - 'type' => AMP_Validation_Error_Taxonomy::JS_ERROR_TYPE, - 'node_type' => XML_ATTRIBUTE_NODE, - ], - $error - ); - $that->assertInstanceOf( 'DOMAttr', $context['node'] ); - $that->assertEquals( 'onload', $context['node']->nodeName ); - return true; - }, - ] - ); - $element = $dom->getElementsByTagName( 'amp-video' )->item( 0 ); - $this->assertTrue( $sanitizer->remove_invalid_attribute( $element, 'onload' ) ); - $this->assertFalse( $element->hasAttribute( 'onload' ) ); - - // Test not sanitizing. - $dom = AMP_DOM_Utils::get_dom_from_content( '' ); - $sanitizer = new AMP_Video_Sanitizer( - $dom, - [ - 'validation_error_callback' => static function( $error, $context ) use ( $that ) { - $that->assertEquals( - [ - 'node_name' => 'onload', - 'parent_name' => 'amp-video', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'element_attributes' => - [ - 'id' => 'bar', - 'onload' => 'someFunc()', - ], - 'type' => AMP_Validation_Error_Taxonomy::JS_ERROR_TYPE, - 'node_type' => XML_ATTRIBUTE_NODE, - ], - $error - ); - $that->assertInstanceOf( 'DOMAttr', $context['node'] ); - $that->assertEquals( 'onload', $context['node']->nodeName ); - return false; - }, - ] - ); - $element = $dom->getElementsByTagName( 'amp-video' )->item( 0 ); - $this->assertFalse( $sanitizer->remove_invalid_attribute( $element, 'onload' ) ); - $this->assertTrue( $element->hasAttribute( 'onload' ) ); - } - - /** - * Tests remove_invalid_attribute in dev mode. - * - * @covers ::remove_invalid_attribute() - * @covers ::is_exempt_from_validation() - */ - public function test_remove_invalid_attribute_dev_mode() { - $id = 'target'; - $attr = 'data-bad'; - $html = sprintf( '
        ', esc_attr( $id ), esc_attr( $attr ) ); - - // Ensure element is not removed when it and document are in dev mode. - $dom = AMP_DOM_Utils::get_dom_from_content( $html ); - $dom->documentElement->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $element = $dom->getElementById( $id ); - $element->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $sanitizer = new AMP_Audio_Sanitizer( $dom ); - $this->assertFalse( $sanitizer->remove_invalid_attribute( $element, $attr ) ); - $this->assertNotEmpty( $element->parentNode ); - - // Ensure invalid element when it has dev-mode attribute but document does not. - $dom = AMP_DOM_Utils::get_dom_from_content( $html ); - $element = $dom->getElementById( $id ); - $element->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $sanitizer = new AMP_Audio_Sanitizer( $dom ); - $this->assertTrue( $sanitizer->remove_invalid_attribute( $element, $attr ) ); - $this->assertFalse( $element->hasAttribute( $attr ) ); - - // Ensure element is removed when document is in dev mode but the element lacks the attribute. - $dom = AMP_DOM_Utils::get_dom_from_content( $html ); - $dom->documentElement->setAttribute( AMP_Rule_Spec::DEV_MODE_ATTRIBUTE, '' ); - $element = $dom->getElementById( $id ); - $sanitizer = new AMP_Audio_Sanitizer( $dom ); - $this->assertTrue( $sanitizer->remove_invalid_attribute( $element, $attr ) ); - $this->assertFalse( $element->hasAttribute( $attr ) ); - } - - /** @covers ::remove_invalid_attribute() */ - public function test_remove_invalid_attribute_with_validation_exemptions() { - // When no exemption attributes are present, the attribute gets removed. - $dom = Document::fromHtml( '
        ' ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( AMP_Base_Sanitizer::class, [ $dom ] ); - $this->assertTrue( $sanitizer->remove_invalid_attribute( $el, 'id' ) ); - $this->assertFalse( $el->getAttributeNode( 'id' ) ); - - // When PX-verified attribute is present, the attribute does not get removed. - $dom = Document::fromHtml( sprintf( '
        ', ValidationExemption::AMP_UNVALIDATED_ATTRS_ATTRIBUTE ) ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( AMP_Base_Sanitizer::class, [ $dom ] ); - $this->assertFalse( $sanitizer->remove_invalid_attribute( $el, 'id' ) ); - $this->assertInstanceOf( DOMAttr::class, $el->getAttributeNode( 'id' ) ); - - // When AMP-unvalidated attribute is present, the attribute does not get removed. - $dom = Document::fromHtml( sprintf( '
        ', ValidationExemption::AMP_UNVALIDATED_ATTRS_ATTRIBUTE ) ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( AMP_Base_Sanitizer::class, [ $dom ] ); - $this->assertFalse( $sanitizer->remove_invalid_attribute( $el, 'id' ) ); - $this->assertInstanceOf( DOMAttr::class, $el->getAttributeNode( 'id' ) ); - - // Ensure that attribute is marked as being AMP-unvalidated if validation callback prevents removal. - $dom = Document::fromHtml( '
        ' ); - $el = $dom->getElementById( 'el' ); - $sanitizer = $this->getMockForAbstractClass( - AMP_Base_Sanitizer::class, - [ - $dom, - [ - 'validation_error_callback' => '__return_false', - ], - ] - ); - $this->assertFalse( $sanitizer->remove_invalid_attribute( $el, 'id' ) ); - $this->assertInstanceOf( DOMAttr::class, $el->getAttributeNode( 'id' ) ); - $this->assertEquals( 'id', $el->getAttribute( ValidationExemption::AMP_UNVALIDATED_ATTRS_ATTRIBUTE ) ); - } - - /** - * Tests get_data_amp_attributes. - * - * @covers ::get_data_amp_attributes() - */ - public function test_get_data_amp_attributes() { - $tag = 'figure'; - $dom_document = new Document( '1.0', 'utf-8' ); - $figure = $dom_document->createElement( $tag ); - $amp_img = $dom_document->createElement( 'amp-img' ); - $figure->appendChild( $amp_img ); - $figure->setAttribute( 'data-amp-noloading', 'true' ); - $figure->setAttribute( 'data-amp-layout', 'fixed' ); - - $sanitizer = new StubSanitizer( new Document(), [] ); - $amp_args = $sanitizer->get_data_amp_attributes( $amp_img ); - - $expected_args = [ - 'layout' => 'fixed', - 'noloading' => 'true', - ]; - - $this->assertEquals( $expected_args, $amp_args ); - } - - /** - * Tests set_data_amp_attributes. - * - * @covers ::filter_data_amp_attributes() - */ - public function test_filter_data_amp_attributes() { - $amp_data = [ - 'noloading' => true, - 'invalid' => 123, - ]; - $attributes = [ - 'width' => 100, - ]; - $sanitizer = new StubSanitizer( new Document(), [] ); - $attributes = $sanitizer->filter_data_amp_attributes( $attributes, $amp_data ); - - $expected = [ - 'width' => 100, - 'data-amp-noloading' => '', - ]; - $this->assertEquals( $expected, $attributes ); - } - - /** - * Tests set_attachment_layout_attributes. - * - * @covers ::filter_attachment_layout_attributes() - */ - public function test_filter_attachment_layout_attributes() { - $sanitizer = new StubSanitizer( new Document(), [] ); - $tag = 'figure'; - $dom_document = new Document( '1.0', 'utf-8' ); - $figure = $dom_document->createElement( $tag ); - $amp_img = $dom_document->createElement( 'amp-img' ); - $layout = 'fixed-height'; - $figure->appendChild( $amp_img ); - $attributes = [ - 'src' => '', - ]; - - $attributes = $sanitizer->filter_attachment_layout_attributes( $amp_img, $attributes, $layout ); - $expected_atts = [ - 'src' => '', - 'height' => 400, - 'width' => 'auto', - ]; - $this->assertEquals( $expected_atts, $attributes ); - - $parent_style = $figure->getAttribute( 'style' ); - $expected_style = 'height: 400px; width: auto;'; - $this->assertEquals( $expected_style, $parent_style ); - } -} diff --git a/tests/php/test-class-amp-block-sanitizer.php b/tests/php/test-class-amp-block-sanitizer.php deleted file mode 100644 index 48485d3c32a..00000000000 --- a/tests/php/test-class-amp-block-sanitizer.php +++ /dev/null @@ -1,74 +0,0 @@ - [ - '

        Lorem Ipsum Demet Delorit.

        ', - '

        Lorem Ipsum Demet Delorit.

        ', - ], - - 'more_than_one_child' => [ - '
        ', - '
        ', - ], - - 'no_wp_block_embed' => [ - '
        ', - '
        ', - ], - - 'data_amp_noloading' => [ - '
        ', - '
        ', - ], - - 'data_amp_layout_fill' => [ - '
        ', - '
        ', - ], - - 'responsive_layout' => [ - '
        ', - '
        ', - ], - - 'intrinsic_layout' => [ - '
        ', - '
        ', - ], - ]; - } - - /** - * Test sanitizer. - * - * @dataProvider get_data - * @param string $source Source. - * @param string $expected Expected. - */ - public function test_sanitizer( $source, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Block_Sanitizer( $dom ); - $sanitizer->sanitize(); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $content = preg_replace( '/(?<=>)\s+(?=<)/', '', $content ); - $this->assertEquals( $expected, $content ); - } -} diff --git a/tests/php/test-class-amp-cli-validation-command.php b/tests/php/test-class-amp-cli-validation-command.php deleted file mode 100644 index 6ae7c09fcc2..00000000000 --- a/tests/php/test-class-amp-cli-validation-command.php +++ /dev/null @@ -1,87 +0,0 @@ -validation = $this->injector->make( ValidationCommand::class ); - $this->add_validate_response_mocking_filter(); - } - - /** - * Test validate_urls. - * - * @covers ::validate_urls() - * @covers \AmpProject\AmpWP\Validation\ScannableURLProvider::set_limit_per_type() - */ - public function test_validate_urls() { - $number_of_posts = 20; - $number_of_terms = 30; - $posts = []; - $post_permalinks = []; - $terms = []; - - $this->validation = $this->injector->make( ValidationCommand::class ); - $this->get_private_property( $this->validation, 'scannable_url_provider' )->set_limit_per_type( 100 ); - - for ( $i = 0; $i < $number_of_posts; $i++ ) { - $post_id = self::factory()->post->create(); - $posts[] = $post_id; - $post_permalinks[] = get_permalink( $post_id ); - } - $this->call_private_method( $this->validation, 'validate_urls' ); - - // All of the posts created above should be present in $validated_urls. - $this->assertEmpty( array_diff( $post_permalinks, $this->get_validated_urls() ) ); - - $this->validation = $this->injector->make( ValidationCommand::class ); - $this->get_private_property( $this->validation, 'scannable_url_provider' )->set_limit_per_type( 100 ); - for ( $i = 0; $i < $number_of_terms; $i++ ) { - $terms[] = self::factory()->category->create(); - } - - // Terms need to be associated with a post in order to be returned in get_terms(). - wp_set_post_terms( $posts[0], $terms, 'category' ); - $this->call_private_method( $this->validation, 'validate_urls' ); - $expected_validated_urls = array_map( 'get_term_link', $terms ); - $actual_validated_urls = $this->get_validated_urls(); - - // All of the terms created above should be present in $validated_urls. - $this->assertEmpty( array_diff( $expected_validated_urls, $actual_validated_urls ) ); - $this->assertContains( home_url( '/' ), $this->get_validated_urls() ); - } -} diff --git a/tests/php/test-class-amp-comments-sanitizer.php b/tests/php/test-class-amp-comments-sanitizer.php deleted file mode 100644 index 810ec450831..00000000000 --- a/tests/php/test-class-amp-comments-sanitizer.php +++ /dev/null @@ -1,338 +0,0 @@ -post->create_and_get(); - - $GLOBALS['wp_scripts'] = null; - } - - public function tear_down() { - $GLOBALS['wp_scripts'] = null; - - parent::tear_down(); - } - - /** - * Test AMP_Comments_Sanitizer::sanitize. - * - * @covers ::sanitize() - */ - public function test_sanitize_incorrect_action() { - $dom = Document::fromHtmlFragment( - '' - ); - update_option( 'thread_comments', '1' ); - $sanitizer = new AMP_Comments_Sanitizer( $dom ); - $sanitizer->sanitize(); - $this->assertFalse( $dom->getElementsByTagName( Tag::FORM )->item( 0 )->hasAttribute( Attribute::ON ) ); - } - - /** - * @covers ::sanitize() - * @covers ::ampify_threaded_comments() - */ - public function test_ampify_threaded_comments_without_threading() { - update_option( 'thread_comments', '' ); - setup_postdata( get_the_ID() ); - $dom = $this->get_document_with_comments( get_the_ID() ); - $this->assertNull( $dom->getElementById( 'comment-reply-js' ) ); - $sanitizer = new AMP_Comments_Sanitizer( $dom ); - - $sanitizer->sanitize(); - $commentform = $dom->getElementById( 'commentform' ); - $this->assertInstanceOf( Element::class, $commentform ); - $this->assertFalse( $commentform->hasAttribute( Attribute::ON ) ); - $this->assertNull( $dom->getElementById( 'ampCommentThreading' ) ); - $this->assertNull( $dom->getElementById( 'comment-reply-js' ) ); - } - - /** @return array */ - public function get_data_to_test_ampify_threaded_comments_always_and_conditionally() { - return [ - 'never' => [ - 'ampify_comment_threading' => 'never', - 'comments_form_has_action_xhr' => false, - 'expect_ampify_comment_threading' => false, - 'comment_reply_script_present' => true, - ], - 'always' => [ - 'ampify_comment_threading' => 'always', - 'comments_form_has_action_xhr' => true, - 'expect_ampify_comment_threading' => true, - 'comment_reply_script_present' => true, - ], - 'always_without_script' => [ - 'ampify_comment_threading' => 'always', - 'comments_form_has_action_xhr' => true, - 'expect_ampify_comment_threading' => true, - 'comment_reply_script_present' => false, - ], - 'conditionally_no' => [ - 'ampify_comment_threading' => 'conditionally', - 'comments_form_has_action_xhr' => false, - 'expect_ampify_comment_threading' => false, - 'comment_reply_script_present' => true, - ], - 'conditionally_yes' => [ - 'ampify_comment_threading' => 'conditionally', - 'comments_form_has_action_xhr' => true, - 'expect_ampify_comment_threading' => true, - 'comment_reply_script_present' => true, - ], - ]; - } - - /** - * @dataProvider get_data_to_test_ampify_threaded_comments_always_and_conditionally - * - * @covers ::sanitize() - * @covers ::ampify_threaded_comments() - * @covers ::prepare_native_comment_reply() - * @covers ::get_comment_reply_script() - */ - public function test_ampify_threaded_comments( $ampify_comment_threading, $comments_form_has_action_xhr, $expect_ampify_comment_threading, $comment_reply_script_present ) { - if ( version_compare( get_bloginfo( 'version' ), '5.2', '<' ) ) { - $this->markTestSkipped( 'Skipping because the script ID attribute was added in WP 5.2.' ); - } - - update_option( 'thread_comments', '1' ); - setup_postdata( get_the_ID() ); - $dom = $this->get_document_with_comments( get_the_ID(), false, $comment_reply_script_present ); - - $comment_form = $dom->getElementById( 'commentform' ); - $this->assertInstanceOf( Element::class, $comment_form ); - - if ( $comments_form_has_action_xhr ) { - $comment_form->setAttribute( - Attribute::ACTION_XHR, - $comment_form->getAttribute( Attribute::ACTION ) - ); - $comment_form->removeAttribute( Attribute::ACTION ); - } - - $comments_sanitizer = new AMP_Comments_Sanitizer( - $dom, - [ - 'ampify_comment_threading' => $ampify_comment_threading, - ] - ); - $style_sanitizer = new AMP_Style_Sanitizer( $dom ); - - /** @var AMP_Base_Sanitizer[] $sanitizers */ - $sanitizers = [ - AMP_Comments_Sanitizer::class => $comments_sanitizer, - AMP_Style_Sanitizer::class => $style_sanitizer, - ]; - - // Ensure initial state. - $this->assertFalse( $comment_form->hasAttribute( Attribute::ON ) ); - $script = $dom->getElementById( 'comment-reply-js' ); - if ( $comment_reply_script_present ) { - $this->assertInstanceOf( Element::class, $script ); - $this->assertInstanceOf( Element::class, $script->parentNode ); - $this->assertFalse( ValidationExemption::is_px_verified_for_node( $script ) ); - } else { - $this->assertNull( $script ); - } - - // Sanitize. - foreach ( $sanitizers as $sanitizer ) { - $sanitizer->init( $sanitizers ); - } - $comments_sanitizer->sanitize(); - - if ( ! $expect_ampify_comment_threading ) { - $this->assertEquals( - $comments_form_has_action_xhr, - $comment_form->hasAttribute( Attribute::ON ) - ); - $this->assertInstanceOf( Element::class, $script->parentNode ); - $this->assertTrue( ValidationExemption::is_px_verified_for_node( $script ) ); - $this->assertTrue( $script->hasAttribute( Attribute::DEFER ) ); - $this->assertNull( $dom->getElementById( 'ampCommentThreading' ) ); - - $this->assertFalse( $style_sanitizer->get_arg( 'transform_important_qualifiers' ) ); - } else { - if ( $comment_reply_script_present ) { - $this->assertNull( $script->parentNode ); - } - - $json_script = $dom->xpath->query( '//amp-state[ @id = "ampCommentThreading" ]/script[ @type = "application/json" ]' )->item( 0 ); - $this->assertInstanceOf( Element::class, $json_script, 'Expected ampCommentThreading amp-state to be present.' ); - $this->assertEquals( - [ - 'replyTo' => '', - 'commentParent' => '0', - ], - json_decode( $json_script->textContent, true ) - ); - - $comment_parent_input = $dom->getElementById( 'comment_parent' ); - $this->assertInstanceOf( Element::class, $comment_parent_input ); - $this->assertEquals( '0', $comment_parent_input->getAttribute( Attribute::VALUE ) ); - $this->assertEquals( - 'ampCommentThreading.commentParent', - $comment_parent_input->getAttribute( Amp::BIND_DATA_ATTR_PREFIX . 'value' ) - ); - - $this->assertEquals( - $comment_form->getAttribute( Attribute::ON ), - 'submit-success:commentform.clear,AMP.setState({ampCommentThreading: {"replyTo":"","commentParent":"0"}})' - ); - - $reply_heading_element = $dom->getElementById( 'reply-title' ); - $this->assertInstanceOf( Element::class, $reply_heading_element ); - $span = $reply_heading_element->firstChild; - $this->assertInstanceOf( Element::class, $span ); - $this->assertTrue( $span->hasAttribute( Amp::BIND_DATA_ATTR_PREFIX . 'text' ) ); - - $comment_reply_links = $dom->xpath->query( '//a[ @data-commentid and @data-postid and @data-replyto and @data-respondelement and contains( @class, "comment-reply-link" ) ]' ); - $this->assertGreaterThan( 0, $comment_reply_links->length ); - foreach ( $comment_reply_links as $comment_reply_link ) { - /** @var Element $comment_reply_link */ - $this->assertStringStartsWith( '#', $comment_reply_link->getAttribute( Attribute::HREF ) ); - $this->assertStringContainsString( 'comment.focus', $comment_reply_link->getAttribute( Attribute::ON ) ); - $this->assertStringContainsString( 'AMP.setState', $comment_reply_link->getAttribute( Attribute::ON ) ); - } - - $cancel_comment_reply_link = $dom->getElementById( 'cancel-comment-reply-link' ); - $this->assertInstanceOf( Element::class, $cancel_comment_reply_link ); - - $this->assertFalse( $cancel_comment_reply_link->hasAttribute( Attribute::STYLE ) ); - $this->assertTrue( $cancel_comment_reply_link->hasAttribute( Attribute::HIDDEN ) ); - $this->assertTrue( $cancel_comment_reply_link->hasAttribute( Amp::BIND_DATA_ATTR_PREFIX . Attribute::HIDDEN ) ); - $this->assertStringContainsString( - 'tap:AMP.setState', - $cancel_comment_reply_link->getAttribute( Attribute::ON ) - ); - - $this->assertTrue( $style_sanitizer->get_arg( 'transform_important_qualifiers' ) ); - } - } - - /** - * Test AMP_Comments_Sanitizer::add_amp_live_list_comment_attributes. - * - * @covers ::sanitize() - * @covers ::add_amp_live_list_comment_attributes() - */ - public function test_add_amp_live_list_comment_attributes() { - $dom = $this->get_document_with_comments( get_the_ID(), true ); - $sanitizer = new AMP_Comments_Sanitizer( - $dom, - [ - 'comments_live_list' => true, - ] - ); - - $sanitizer->sanitize(); - - $this->assertEquals( 1, $dom->getElementsByTagName( Extension::LIVE_LIST )->length ); - - $comments_elements = $dom->xpath->query( '//li[ starts-with( @id, "comment-" ) ]' ); - $this->assertGreaterThan( 0, $comments_elements->length ); - - foreach ( $comments_elements as $comment_element ) { - /** @var Element $comment_element */ - - $comment_id = (int) str_replace( 'comment-', '', $comment_element->getAttribute( 'id' ) ); - - $comment_object = get_comment( $comment_id ); - $this->assertInstanceOf( WP_Comment::class, $comment_object ); - - if ( $comment_object->comment_parent ) { - $this->assertFalse( $comment_element->hasAttribute( 'data-sort-time' ) ); - $this->assertFalse( $comment_element->hasAttribute( 'data-update-time' ) ); - } else { - $this->assertTrue( $comment_element->hasAttribute( 'data-sort-time' ) ); - $this->assertTrue( $comment_element->hasAttribute( 'data-update-time' ) ); - - $this->assertEquals( strtotime( $comment_object->comment_date ), $comment_element->getAttribute( 'data-sort-time' ) ); - - $update_time = strtotime( $comment_object->comment_date ); - $children = $comment_object->get_children( - [ - 'format' => 'flat', - 'hierarchical' => 'flat', - 'orderby' => 'none', - ] - ); - foreach ( $children as $child_comment ) { - $update_time = max( strtotime( $child_comment->comment_date ), $update_time ); - } - - $this->assertEquals( $update_time, $comment_element->getAttribute( 'data-update-time' ) ); - } - } - } - - /** - * Get document with comments and comment form. - * - * @param int $post_id Post ID. - * @param bool $add_live_list Add live list. - * @param bool $print_comment_reply_script Whether to print the comment reply script. - * @return Document - */ - protected function get_document_with_comments( $post_id, $add_live_list = false, $print_comment_reply_script = true ) { - /** @var WP_Comment[] $comments */ - $parent_comments = self::factory()->comment->create_post_comments( $post_id, 2 ); - $reply_comments = self::factory()->comment->create_post_comments( - $post_id, - 2, - [ 'comment_parent' => $parent_comments[0] ] - ); - $comments = array_merge( $parent_comments, $reply_comments ); - setup_postdata( $post_id ); - - ob_start(); - if ( $add_live_list ) { - echo ''; - } - printf( '
          ', $add_live_list ? 'items' : '' ); - wp_list_comments( [], array_map( 'get_comment', $comments ) ); - echo '
        '; - if ( $add_live_list ) { - echo '
        '; - } - comment_form(); - if ( get_option( 'thread_comments' ) && $print_comment_reply_script ) { - wp_print_scripts( [ 'comment-reply' ] ); - } - $html = ob_get_clean(); - - return Document::fromHtmlFragment( $html ); - } -} diff --git a/tests/php/test-class-amp-content-sanitizer.php b/tests/php/test-class-amp-content-sanitizer.php deleted file mode 100644 index c3b2ef49246..00000000000 --- a/tests/php/test-class-amp-content-sanitizer.php +++ /dev/null @@ -1,88 +0,0 @@ -'; - $document = AMP_DOM_Utils::get_dom_from_content( $source_html ); - - $sanitizers = amp_get_content_sanitizers(); - $sanitize_results = AMP_Content_Sanitizer::sanitize_document( - $document, - $sanitizers, - [] - ); - - $this->assertEqualSets( [ 'scripts', 'styles', 'stylesheets', 'sanitizers' ], array_keys( $sanitize_results ) ); - $this->assertEquals( - [ 'amp-video' => true ], - $sanitize_results['scripts'] - ); - $this->assertEquals( - [ '.amp-wp-9f6e771:not(#_#_#_#_#_){outline:solid 1px red}' ], - $sanitize_results['stylesheets'] - ); - $this->assertEmpty( $sanitize_results['styles'] ); - $this->assertIsArray( $sanitize_results['sanitizers'] ); - $this->assertEqualSets( array_keys( $sanitizers ), array_keys( $sanitize_results['sanitizers'] ) ); - $this->assertEquals( 1, $document->getElementsByTagName( 'amp-video' )->length ); - foreach ( array_keys( $sanitizers ) as $sanitizer_class ) { - $this->assertInstanceOf( $sanitizer_class, $sanitize_results['sanitizers'][ $sanitizer_class ] ); - } - } - - /** - * Test sanitize no-op. - * - * @covers \AMP_Content_Sanitizer::sanitize() - */ - public function test_sanitize_noop() { - $source_html = 'Hello'; - $expected_return = [ 'Hello', [], [] ]; - - $actual_return = AMP_Content_Sanitizer::sanitize( $source_html, [ StubSanitizer::class => [] ] ); - - $this->assertEquals( $expected_return, $actual_return ); - } - - /** - * Test sanitize with all sanitizers. - * - * @covers \AMP_Content_Sanitizer::sanitize() - */ - public function test_sanitize_all() { - $source_html = ''; - $expected_return = [ - 'https://example.com/foo.mp4', - [ 'amp-video' => true ], - [ '.amp-wp-9f6e771:not(#_#_#_#_#_){outline:solid 1px red}' ], - ]; - - $actual_return = AMP_Content_Sanitizer::sanitize( - $source_html, - amp_get_content_sanitizers(), - [ 'return_styles' => false ] - ); - - $this->assertEquals( $expected_return, $actual_return ); - } -} diff --git a/tests/php/test-class-amp-core-block-handler.php b/tests/php/test-class-amp-core-block-handler.php deleted file mode 100644 index 3da340b2ece..00000000000 --- a/tests/php/test-class-amp-core-block-handler.php +++ /dev/null @@ -1,926 +0,0 @@ -markTestIncomplete( 'Files needed for testing missing.' ); - } - if ( version_compare( get_bloginfo( 'version' ), '5.0', '<' ) ) { - $this->markTestSkipped( 'Missing required render_block filter.' ); - } - $this->prevent_block_pre_render(); - } - - /** - * Tear down. - */ - public function tear_down() { - if ( did_action( 'add_attachment' ) ) { - $this->remove_added_uploads(); - } - - global $wp_scripts, $wp_styles; - $wp_scripts = null; - $wp_styles = null; - - parent::tear_down(); - } - - /** - * Get video attachment ID. - * - * @return int|WP_Error ID or error. - */ - protected function get_video_attachment_id() { - $temp_file = trailingslashit( get_temp_dir() ) . 'core-block-handler-test-' . wp_generate_uuid4() . '.mp4'; - copy( DIR_TESTDATA . '/uploads/small-video.mp4', $temp_file ); - $attachment_id = self::factory()->attachment->create_upload_object( $temp_file ); - - // Remove the file extension from the post_title media_handle_upload(). - $attachment = get_post( $attachment_id, ARRAY_A ); - $attachment['post_title'] = str_replace( '.mp4', '', $attachment['post_title'] ); - $attachment['post_name'] = str_replace( '-mp4', '', $attachment['post_name'] ); - wp_update_post( wp_slash( $attachment ) ); - - return $attachment_id; - } - - /** - * Test register_embed(). - * - * @covers AMP_Core_Block_Handler::register_embed() - * @covers AMP_Core_Block_Handler::unregister_embed() - * @covers AMP_Core_Block_Handler::filter_rendered_block() - * @covers AMP_Core_Block_Handler::ampify_archives_block() - * @covers AMP_Core_Block_Handler::ampify_categories_block() - */ - public function test_register_and_unregister_embed() { - $handler = new AMP_Core_Block_Handler(); - $handler->unregister_embed(); // Make sure we are on the initial clean state. - - $categories_block = ''; - $archives_block = ''; - - $handler->register_embed(); - $rendered = do_blocks( $categories_block ); - $this->assertStringContainsString( 'assertStringNotContainsString( 'onchange', $rendered ); - $this->assertStringContainsString( 'on="change', $rendered ); - if ( WP_Block_Type_Registry::get_instance()->is_registered( 'core/archives' ) ) { - $rendered = do_blocks( $archives_block ); - $this->assertStringContainsString( 'assertStringNotContainsString( 'onchange', $rendered ); - $this->assertStringContainsString( 'on="change', $rendered ); - } - - $handler->unregister_embed(); - $rendered = do_blocks( $categories_block ); - $this->assertStringContainsString( 'assertStringContainsString( 'onchange', $rendered ); - $this->assertStringNotContainsString( 'on="change', $rendered ); - if ( WP_Block_Type_Registry::get_instance()->is_registered( 'core/archives' ) ) { - $rendered = do_blocks( $archives_block ); - $this->assertStringContainsString( 'assertStringContainsString( 'onchange', $rendered ); - $this->assertStringNotContainsString( 'on="change', $rendered ); - } - } - - /** - * Test that placeholder blocks don't result in validation errors. - * - * @covers \AMP_Core_Block_Handler::filter_rendered_block() - */ - public function test_placeholder_blocks() { - $handler = new AMP_Core_Block_Handler(); - $handler->unregister_embed(); // Make sure we are on the initial clean state. - $handler->register_embed(); - - $audio_placeholder_block = "\n
        \n"; - $audio_populated_block = "\n
        \n"; - $this->assertEmpty( apply_filters( 'the_content', $audio_placeholder_block ) ); - $this->assertNotEmpty( apply_filters( 'the_content', $audio_populated_block ) ); - - $image_placeholder_block = "\n
        \"\"/
        \n"; - $image_populated_block = "\n
        \"\"/
        \n"; - $this->assertEmpty( apply_filters( 'the_content', $image_placeholder_block ) ); - $this->assertNotEmpty( apply_filters( 'the_content', $image_populated_block ) ); - } - - /** - * Test that video width/height attributes are added. - * - * @covers \AMP_Core_Block_Handler::ampify_video_block() - */ - public function test_ampify_video_block() { - $attachment_id = $this->get_video_attachment_id(); - - $post_id = self::factory()->post->create( - [ - 'post_title' => 'Video', - 'post_content' => sprintf( - "\n
        \n", - $attachment_id, - wp_get_attachment_url( $attachment_id ) - ), - ] - ); - - $handler = new AMP_Core_Block_Handler(); - $handler->unregister_embed(); // Make sure we are on the initial clean state. - $handler->register_embed(); - - $content = apply_filters( 'the_content', get_post( $post_id )->post_content ); - - $this->assertStringContainsString( 'width="560" height="320" style="aspect-ratio:560/320"', $content ); - } - - /** - * Check that no transformation is made when external video (not yet anyway). - * - * @link https://github.com/ampproject/amp-wp/issues/5233 - * @covers \AMP_Core_Block_Handler::ampify_video_block() - */ - public function test_ampify_video_block_without_attachment() { - $post_id = self::factory()->post->create( - [ - 'post_title' => 'Video', - 'post_content' => '
        ', - ] - ); - - $handler = new AMP_Core_Block_Handler(); - $handler->unregister_embed(); // Make sure we are on the initial clean state. - $handler->register_embed(); - - $content = apply_filters( 'the_content', get_post( $post_id )->post_content ); - - $this->assertStringContainsString( '
        '; - $toggle = ''; - $head = ''; - - $amp_state = ''; - $amp_get_container_attrs = function( $class = '', $toggle_class = 'toggled-on' ) { - if ( empty( $toggle_class ) ) { - return ''; - } - return ' data-amp-bind-class=""' . $class . '" + ( navMenuToggledOn ? " ' . $toggle_class . '" : \'\' )"'; - }; - $amp_get_toggle_attrs = function( $class = '', $toggle_class = 'toggled-on' ) { // phpcs:ignore Generic.Formatting.MultipleStatementAlignment.NotSameWarning -- Sniff has a bug. - return ' on="tap:AMP.setState({ navMenuToggledOn: ! navMenuToggledOn })" aria-expanded="false" data-amp-bind-aria-expanded="navMenuToggledOn ? \'true\' : \'false\'"' . ( ! empty( $toggle_class ) ? ' data-amp-bind-class=""' . $class . '" + ( navMenuToggledOn ? " ' . $toggle_class . '" : \'\' )"' : '' ); - }; - - return [ - 'container_before_toggle' => [ - '' . $container . $toggle . '', - '' . $head . '' . $amp_state . str_replace( '>
        ', $amp_get_container_attrs( 'nav-menu-wrapper' ) . '>
        ', $container ) . str_replace( '>Toggle', $amp_get_toggle_attrs() . '>Toggle', $toggle ) . '', - [ - 'nav_container_id' => $container_id, - 'menu_button_id' => $toggle_id, - 'nav_container_toggle_class' => 'toggled-on', - 'menu_button_toggle_class' => 'toggled-on', - ], - ], - 'toggle_before_container' => [ - '' . $toggle . $container . '', - '' . $head . '' . str_replace( '>Toggle', $amp_get_toggle_attrs() . '>Toggle', $toggle ) . $amp_state . str_replace( '>', $amp_get_container_attrs( 'nav-menu-wrapper' ) . '>', $container ) . '', - [ - 'nav_container_id' => $container_id, - 'menu_button_id' => $toggle_id, - 'nav_container_toggle_class' => 'toggled-on', - 'menu_button_toggle_class' => 'toggled-on', - ], - ], - 'container_is_body' => [ - '' . $container . $toggle . '', - '' . $head . '' . $amp_state . $container . str_replace( '>Toggle', $amp_get_toggle_attrs( '', '' ) . '>Toggle', $toggle ) . '', - [ - 'nav_container_xpath' => '//body', - 'menu_button_id' => $toggle_id, - 'nav_container_toggle_class' => 'nav-menu-toggled-on', - ], - ], - 'container_is_html' => [ - '' . $container . $toggle . '', - '' . $head . '' . $amp_state . $container . str_replace( '>Toggle', $amp_get_toggle_attrs( '', '' ) . '>Toggle', $toggle ) . '', - [ - 'nav_container_xpath' => '//html', - 'menu_button_id' => $toggle_id, - 'nav_container_toggle_class' => 'nav-menu-toggled-on', - ], - ], - 'no_container_provided' => [ - '' . $container . $toggle . '', - '' . $head . '' . $container . '', - [ - 'menu_button_id' => $toggle_id, - 'nav_container_toggle_class' => 'toggled-on', - ], - ], - 'no_arguments_provided' => [ - '' . $container . $toggle . '', - '' . $head . '' . $container . $toggle . '', - [], - ], - ]; - } - - /** - * Tests the content converted by the sanitizer. - * - * @param string $source Content. - * @param string $expected Expected content. - * @param array $args Theme support arguments for 'nav_menu_toggle'. - * - * @dataProvider data_converter - * @covers AMP_Nav_Menu_Toggle_Sanitizer::sanitize() - * @covers AMP_Nav_Menu_Toggle_Sanitizer::get_nav_container() - * @covers AMP_Nav_Menu_Toggle_Sanitizer::get_menu_button() - */ - public function test_converter( $source, $expected, $args = [] ) { - $dom = Document::fromHtml( $source, Options::DEFAULTS ); - $sanitizer = new AMP_Nav_Menu_Toggle_Sanitizer( $dom, $args ); - - $sanitizer->sanitize(); - - $content = $dom->saveHTML( $dom->documentElement ); - - $this->assertEquals( $expected, $content ); - } -} diff --git a/tests/php/test-class-amp-object-sanitizer.php b/tests/php/test-class-amp-object-sanitizer.php deleted file mode 100644 index 506c787a567..00000000000 --- a/tests/php/test-class-amp-object-sanitizer.php +++ /dev/null @@ -1,106 +0,0 @@ - [ - '

        Hello World.

        ', - '

        Hello World.

        ', - ], - - 'object element with non-PDF content type' => [ - '', - '', - ], - - 'object element with PDF content type' => [ - '', - '', - ], - - 'two object elements with PDF content type' => [ - '', - '', - ], - - 'GB file block with PDF content type' => [ - '
        ', - '
        ', - ], - - 'object element with PDF content type and title' => [ - '', - '', - ], - - 'object element with PDF content type and height' => [ - '', - '', - ], - ]; - } - - /** - * @covers ::sanitize() - * @covers ::sanitize_pdf() - * @dataProvider get_data() - */ - public function test_sanitize( $source, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Object_Sanitizer( $dom ); - $sanitizer->sanitize(); - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - $this->assertEquals( $expected, $content ); - } - - public function get_scripts_data() { - return [ - 'not converted' => [ - '

        Hello World.

        ', - [], - ], - 'converted' => [ - '', - [ 'amp-google-document-embed' => true ], - ], - ]; - } - - /** - * @covers ::get_scripts() - * @dataProvider get_scripts_data - */ - public function test_get_scripts( $source, $expected ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $sanitizer = new AMP_Object_Sanitizer( $dom ); - $sanitizer->sanitize(); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $sanitizer->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-class-amp-options-manager.php b/tests/php/test-class-amp-options-manager.php deleted file mode 100644 index 319fbf8bdc9..00000000000 --- a/tests/php/test-class-amp-options-manager.php +++ /dev/null @@ -1,742 +0,0 @@ -was_wp_using_ext_object_cache = $GLOBALS['_wp_using_ext_object_cache']; - delete_option( AMP_Options_Manager::OPTION_NAME ); // Make sure default reader mode option does not override theme support being added. - remove_theme_support( 'amp' ); - $GLOBALS['wp_settings_errors'] = []; - - $this->register_core_themes(); - } - - /** - * After a test method runs, reset any state in WordPress the test method might have changed. - */ - public function tear_down() { - $GLOBALS['_wp_using_ext_object_cache'] = $this->was_wp_using_ext_object_cache; - unregister_post_type( 'foo' ); - unregister_post_type( 'book' ); - - global $current_screen; - $current_screen = null; - - foreach ( get_post_types() as $post_type ) { - remove_post_type_support( $post_type, 'amp' ); - } - - $this->restore_theme_directories(); - $GLOBALS['wp_the_query'] = $GLOBALS['wp_query']; // This is missing in core. - - parent::tear_down(); - } - - /** - * Test constants. - */ - public function test_constants() { - $this->assertEquals( 'amp-options', AMP_Options_Manager::OPTION_NAME ); - } - - /** - * Tests the init method. - * - * @covers AMP_Options_Manager::init() - */ - public function test_init() { - AMP_Options_Manager::init(); - $this->assertEquals( 10, has_action( 'admin_notices', [ AMP_Options_Manager::class, 'render_php_css_parser_conflict_notice' ] ) ); - $this->assertEquals( 10, has_action( 'admin_notices', [ AMP_Options_Manager::class, 'insecure_connection_notice' ] ) ); - $this->assertEquals( 10, has_action( 'admin_notices', [ AMP_Options_Manager::class, 'reader_theme_fallback_notice' ] ) ); - } - - /** - * Test register_settings. - * - * @covers AMP_Options_Manager::register_settings() - */ - public function test_register_settings() { - AMP_Options_Manager::register_settings(); - AMP_Options_Manager::init(); - $registered_settings = get_registered_settings(); - $this->assertArrayHasKey( AMP_Options_Manager::OPTION_NAME, $registered_settings ); - $this->assertEquals( 'array', $registered_settings[ AMP_Options_Manager::OPTION_NAME ]['type'] ); - } - - /** - * Test get_options. - * - * @covers AMP_Options_Manager::get_options() - * @covers AMP_Options_Manager::get_option() - * @covers AMP_Options_Manager::update_option() - * @covers AMP_Options_Manager::validate_options() - */ - public function test_get_and_set_options() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - wp_using_ext_object_cache( true ); // turn on external object cache flag. - AMP_Options_Manager::register_settings(); // Adds validate_options as filter. - delete_option( AMP_Options_Manager::OPTION_NAME ); - $this->assertEquals( - [ - Option::THEME_SUPPORT => AMP_Theme_Support::READER_MODE_SLUG, - Option::SUPPORTED_POST_TYPES => [ 'post', 'page' ], - Option::ANALYTICS => [], - Option::ALL_TEMPLATES_SUPPORTED => true, - Option::SUPPORTED_TEMPLATES => [ 'is_singular' ], - Option::SUPPRESSED_PLUGINS => [], - Option::VERSION => AMP__VERSION, - Option::MOBILE_REDIRECT => true, - Option::READER_THEME => 'legacy', - Option::PLUGIN_CONFIGURED => false, - Option::PAIRED_URL_STRUCTURE => Option::PAIRED_URL_STRUCTURE_QUERY_VAR, - Option::LATE_DEFINED_SLUG => null, - Option::DELETE_DATA_AT_UNINSTALL => true, - Sandboxing::OPTION_ENABLED => false, - Sandboxing::OPTION_LEVEL => 1, - ], - AMP_Options_Manager::get_options() - ); - $this->assertSame( false, AMP_Options_Manager::get_option( 'foo' ) ); - $this->assertSame( 'default', AMP_Options_Manager::get_option( 'foo', 'default' ) ); - - // Test supported_post_types validation. - AMP_Options_Manager::update_option( - Option::SUPPORTED_POST_TYPES, - [ 'post' ] - ); - $this->assertSame( - [ 'post' ], - AMP_Options_Manager::get_option( Option::SUPPORTED_POST_TYPES ) - ); - - // Test supported_templates validation. - AMP_Options_Manager::update_option( - Option::SUPPORTED_TEMPLATES, - [ - 'is_search', - 'is_category', - ] - ); - $this->assertSame( - [ - 'is_search', - 'is_category', - ], - AMP_Options_Manager::get_option( Option::SUPPORTED_TEMPLATES ) - ); - - // Test analytics validation with missing fields. - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - 'bad' => [], - ] - ); - $this->assertEmpty( AMP_Options_Manager::get_option( Option::ANALYTICS ) ); - - // Test bad analytics JSON entries are skipped. - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - 'abcdefghijkl' => [ - 'type' => 'foo', - 'config' => '{"good":true}', - ], - 'mnopqrstuvwx' => [ - 'type' => 'bar', - 'config' => '{"bad":true', - ], - 'mshvad9sdasa' => [ - 'type' => 'baz', - ], - ] - ); - $updated_entries = AMP_Options_Manager::get_option( Option::ANALYTICS ); - $this->assertEquals( - [ - 'abcdefghijkl' => [ - 'type' => 'foo', - 'config' => '{"good":true}', - ], - ], - $updated_entries - ); - - // Confirm format of entry ID. - $entries = AMP_Options_Manager::get_option( Option::ANALYTICS ); - $id = current( array_keys( $entries ) ); - $this->assertArrayHasKey( $id, $entries ); - $this->assertEquals( 'foo', $entries[ $id ]['type'] ); - $this->assertEquals( '{"good":true}', $entries[ $id ]['config'] ); - - // Confirm adding another entry works. - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - 'abcdefghijkl' => [ - 'type' => 'foo', - 'config' => '{"good":true}', - ], - 'mnopqrstuvwx' => [ - 'type' => 'bar', - 'config' => '{"good":true}', - ], - ] - ); - $entries = AMP_Options_Manager::get_option( Option::ANALYTICS ); - $this->assertCount( 2, AMP_Options_Manager::get_option( Option::ANALYTICS ) ); - $this->assertArrayHasKey( $id, $entries ); - - // Confirm updating an entry works. - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - $id => [ - 'id' => $id, - 'type' => 'foo', - 'config' => '{"very_good":true}', - ], - ] - ); - $entries = AMP_Options_Manager::get_option( Option::ANALYTICS ); - $this->assertEquals( 'foo', $entries[ $id ]['type'] ); - $this->assertEquals( '{"very_good":true}', $entries[ $id ]['config'] ); - - // Confirm deleting an entry works. - AMP_Options_Manager::update_option( - Option::ANALYTICS, - [ - 'new-entry' => [ - 'type' => 'bar', - 'config' => '{"good":true}', - ], - ] - ); - $entries = AMP_Options_Manager::get_option( Option::ANALYTICS ); - $this->assertCount( 1, $entries ); - $this->assertArrayNotHasKey( $id, $entries ); - } - - /** - * Test get_options for toggling the default value of plugin_configured. - * - * @covers AMP_Options_Manager::get_option() - * @covers AMP_Options_Manager::get_options() - */ - public function test_get_options_changing_plugin_configured_default() { - // Ensure plugin_configured is false when existing option is absent. - delete_option( AMP_Options_Manager::OPTION_NAME ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::PLUGIN_CONFIGURED ) ); - - // Ensure plugin_configured is true when existing option is absent from an old version. - update_option( AMP_Options_Manager::OPTION_NAME, [ Option::VERSION => '1.5.2' ] ); - $this->assertTrue( AMP_Options_Manager::get_option( Option::PLUGIN_CONFIGURED ) ); - - // Ensure plugin_configured is true when explicitly set as such in the DB. - update_option( - AMP_Options_Manager::OPTION_NAME, - [ - Option::VERSION => AMP__VERSION, - Option::PLUGIN_CONFIGURED => false, - Option::DELETE_DATA_AT_UNINSTALL => false, - ] - ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::PLUGIN_CONFIGURED ) ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::DELETE_DATA_AT_UNINSTALL ) ); - - // Ensure plugin_configured is false when explicitly set as such in the DB. - update_option( - AMP_Options_Manager::OPTION_NAME, - [ - Option::VERSION => AMP__VERSION, - Option::PLUGIN_CONFIGURED => true, - Option::DELETE_DATA_AT_UNINSTALL => true, - ] - ); - $this->assertTrue( AMP_Options_Manager::get_option( Option::PLUGIN_CONFIGURED ) ); - $this->assertTrue( AMP_Options_Manager::get_option( Option::DELETE_DATA_AT_UNINSTALL ) ); - } - - /** @return array */ - public function get_data_for_testing_get_options_default_template_mode() { - return [ - 'core_theme' => [ - 'twentytwenty', - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - null, - ], - 'child_of_core' => [ - 'child-of-core', - AMP_Theme_Support::READER_MODE_SLUG, - null, - ], - 'custom_theme' => [ - 'twentytwenty', - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - [], - ], - ]; - } - - /** - * Test the expected default mode when various themes are active. - * - * @dataProvider get_data_for_testing_get_options_default_template_mode - * - * @covers AMP_Options_Manager::get_options() - * @param string $theme Theme. - * @param string $expected_mode Expected mode. - * @param null|array $added_theme_support Added theme support (or not if null). - */ - public function test_get_options_default_template_mode( $theme, $expected_mode, $added_theme_support ) { - $theme_dir = basename( dirname( AMP__DIR__ ) ) . '/' . basename( AMP__DIR__ ) . '/tests/php/data/themes'; - register_theme_directory( $theme_dir ); - - delete_option( AMP_Options_Manager::OPTION_NAME ); - remove_theme_support( 'amp' ); - switch_theme( $theme ); - if ( is_array( $added_theme_support ) ) { - add_theme_support( 'amp', $added_theme_support ); - } - AMP_Core_Theme_Sanitizer::extend_theme_support(); - $this->assertEquals( $expected_mode, AMP_Options_Manager::get_option( Option::THEME_SUPPORT ) ); - } - - /** - * Test get_options when supported_post_types option is list of post types and when post type support is added for default values. - * - * @covers AMP_Options_Manager::get_options() - */ - public function test_get_options_migration_supported_post_types_defaults() { - foreach ( get_post_types() as $post_type ) { - remove_post_type_support( $post_type, 'amp' ); - } - - register_post_type( - 'book', - [ - 'public' => true, - 'supports' => [ 'amp' ], - ] - ); - - // Make sure the post type support get migrated. - delete_option( AMP_Options_Manager::OPTION_NAME ); - $this->assertEquals( - [ - 'post', // Enabled by default. - 'page', // Enabled by default. - 'book', - ], - AMP_Options_Manager::get_option( Option::SUPPORTED_POST_TYPES ) - ); - } - - /** @return array */ - public function get_data_for_testing_supported_post_types_options_migration() { - return [ - 'reader_with_all_templates' => [ - [ - 'theme_support' => 'reader', - 'all_templates_supported' => true, - 'supported_post_types' => [ 'post' ], - ], - [ 'post', 'book' ], - ], - 'reader_without_all_templates' => [ - [ - 'theme_support' => 'reader', - 'all_templates_supported' => false, - 'supported_post_types' => [ 'post' ], - ], - [ 'post', 'book' ], - ], - 'transitional__with_all_templates' => [ - [ - 'theme_support' => 'transitional', - 'all_templates_supported' => true, - 'supported_post_types' => [ 'post' ], - ], - [ 'post', 'page', 'book', 'attachment' ], - ], - 'transitional_without_all_templates' => [ - [ - 'theme_support' => 'transitional', - 'all_templates_supported' => false, - 'supported_post_types' => [ 'post' ], - ], - [ 'post', 'book' ], - ], - ]; - } - - /** - * Test get_options when supported_post_types option is list of post types when upgrading from an old version. - * - * @dataProvider get_data_for_testing_supported_post_types_options_migration - * - * @param array $existing_options Existing options. - * @param array $expected_supported_post_types Expected supported post types. - * @covers AMP_Options_Manager::get_options() - */ - public function test_get_options_migration_supported_post_types_from_upgrade( $existing_options, $expected_supported_post_types ) { - global $wpdb; - foreach ( get_post_types() as $post_type ) { - remove_post_type_support( $post_type, 'amp' ); - } - - register_post_type( - 'book', - [ - 'public' => true, - 'supports' => [ 'amp' ], - ] - ); - - delete_option( AMP_Options_Manager::OPTION_NAME ); - $wpdb->insert( - $wpdb->options, - [ - 'option_name' => AMP_Options_Manager::OPTION_NAME, - 'option_value' => serialize( // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize - array_merge( - [ - 'supported_templates' => [ 'is_singular' ], - 'version' => '1.5.5', - ], - $existing_options - ) - ), - ] - ); - wp_cache_flush(); - - $this->assertEqualSets( - $expected_supported_post_types, - array_unique( AMP_Options_Manager::get_option( Option::SUPPORTED_POST_TYPES ) ) - ); - } - - /** - * Test get_options when all_templates_supported theme support is used. - * - * @covers AMP_Options_Manager::get_options() - */ - public function test_get_options_migration_all_templates_supported_defaults() { - delete_option( AMP_Options_Manager::OPTION_NAME ); - add_theme_support( 'amp', [ 'templates_supported' => 'all' ] ); - $this->assertTrue( AMP_Options_Manager::get_option( Option::ALL_TEMPLATES_SUPPORTED ) ); - - delete_option( AMP_Options_Manager::OPTION_NAME ); - add_theme_support( - 'amp', - [ - 'templates_supported' => [ - 'is_search' => true, - 'is_archive' => false, - ], - ] - ); - $this->assertFalse( AMP_Options_Manager::get_option( Option::ALL_TEMPLATES_SUPPORTED ) ); - $this->assertEquals( - [ - 'is_singular', - 'is_search', - ], - AMP_Options_Manager::get_option( Option::SUPPORTED_TEMPLATES ) - ); - } - - /** - * Test that get_options() will migrate options properly when there is theme support and post type support flags. - * - * @covers AMP_Options_Manager::get_options() - */ - public function test_get_options_migration_from_old_version_selective_templates_forced() { - $options = [ - 'theme_support' => 'transitional', - 'supported_post_types' => [ - 'post', - ], - 'analytics' => [], - 'all_templates_supported' => false, - 'supported_templates' => [ - 'is_singular', - 'is_404', - 'is_category', - ], - 'version' => '1.5.5', - ]; - update_option( AMP_Options_Manager::OPTION_NAME, $options ); - - $this->assertEquals( $options, get_option( AMP_Options_Manager::OPTION_NAME ) ); - - add_post_type_support( 'page', 'amp' ); - add_theme_support( - 'amp', - [ - 'templates_supported' => [ - 'is_singular' => true, - 'is_404' => false, - 'is_date' => true, - ], - ] - ); - $migrated_options = AMP_Options_Manager::get_options(); - - $this->assertFalse( $migrated_options[ Option::ALL_TEMPLATES_SUPPORTED ] ); - $this->assertEqualSets( - [ - 'is_singular', - 'is_date', - 'is_category', - ], - array_unique( $migrated_options[ Option::SUPPORTED_TEMPLATES ] ) - ); - $this->assertEquals( - [ - 'post', - 'page', - ], - $migrated_options[ Option::SUPPORTED_POST_TYPES ] - ); - - // Now verify that the templates_supported=>all theme support flag is also migrated. - update_option( AMP_Options_Manager::OPTION_NAME, $options ); - add_theme_support( - 'amp', - [ 'templates_supported' => 'all' ] - ); - $migrated_options = AMP_Options_Manager::get_options(); - $this->assertTrue( $migrated_options[ Option::ALL_TEMPLATES_SUPPORTED ] ); - $this->assertEqualSets( - [ - 'post', - 'page', - 'attachment', - ], - array_unique( $migrated_options[ Option::SUPPORTED_POST_TYPES ] ) - ); - } - - /** - * Test get_options when supported_templates option is list of templates and when theme support is used. - * - * @covers AMP_Options_Manager::get_options() - */ - public function test_get_options_migration_supported_templates() { - // Make sure the theme support get migrated to DB option. - delete_option( AMP_Options_Manager::OPTION_NAME ); - add_theme_support( - 'amp', - [ - 'templates_supported' => [ - 'is_archive' => true, - 'is_search' => false, - 'is_404' => false, - 'is_singular' => true, - ], - ] - ); - $this->assertEqualSets( - [ - 'is_archive', - 'is_singular', - ], - array_unique( AMP_Options_Manager::get_option( Option::SUPPORTED_TEMPLATES ) ) - ); - } - - /** - * Tests the update_options method. - * - * @covers AMP_Options_Manager::update_options - */ - public function test_update_options() { - // Confirm updating multiple entries at once works. - AMP_Options_Manager::update_options( - [ - Option::THEME_SUPPORT => 'reader', - Option::READER_THEME => 'twentysixteen', - ] - ); - - $this->assertEquals( 'reader', AMP_Options_Manager::get_option( Option::THEME_SUPPORT ) ); - $this->assertEquals( 'twentysixteen', AMP_Options_Manager::get_option( Option::READER_THEME ) ); - } - - public function get_test_get_options_defaults_data() { - return [ - 'reader' => [ - null, - AMP_Theme_Support::READER_MODE_SLUG, - ], - 'transitional_without_template_dir' => [ - [ - 'paired' => true, - ], - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'transitional_implied_by_template_dir' => [ - [ - 'template_dir' => 'amp', - ], - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'standard_paired_false' => [ - [ - 'paired' => false, - ], - AMP_Theme_Support::STANDARD_MODE_SLUG, - ], - 'transitional_no_args' => [ - [], - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'standard_via_native' => [ - null, - AMP_Theme_Support::STANDARD_MODE_SLUG, - [ - Option::THEME_SUPPORT => 'native', - ], - ], - 'standard_via_paired' => [ - null, - AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - [ - Option::THEME_SUPPORT => 'paired', - ], - ], - 'reader_mode_persists_non_paired' => [ - [ - 'paired' => false, - ], - AMP_Theme_Support::READER_MODE_SLUG, - [ - Option::THEME_SUPPORT => 'disabled', - ], - ], - 'reader_mode_persists_paired' => [ - [ - 'paired' => true, - ], - AMP_Theme_Support::READER_MODE_SLUG, - [ - Option::THEME_SUPPORT => 'disabled', - ], - ], - ]; - } - - /** - * Test get_options defaults. - * - * @dataProvider get_test_get_options_defaults_data - * @covers AMP_Options_Manager::get_options() - * @covers AMP_Options_Manager::get_option() - * - * @param array|null $args Theme support args. - * @param string $expected_mode Expected mode. - * @param array $initial_option Initial option in DB. - */ - public function test_get_options_theme_support_defaults( $args, $expected_mode, $initial_option = [] ) { - update_option( AMP_Options_Manager::OPTION_NAME, $initial_option ); - if ( isset( $args ) ) { - add_theme_support( 'amp', $args ); - } - $this->assertEquals( $expected_mode, AMP_Options_Manager::get_option( Option::THEME_SUPPORT ) ); - } - - /** @covers AMP_Options_Manager::render_php_css_parser_conflict_notice() */ - public function test_render_php_css_parser_conflict_notice() { - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'render_php_css_parser_conflict_notice' ] ) ); - - set_current_screen( 'themes' ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'render_php_css_parser_conflict_notice' ] ) ); - - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'render_php_css_parser_conflict_notice' ] ) ); - } - - /** @covers AMP_Options_Manager::insecure_connection_notice() */ - public function test_insecure_connection_notice() { - $_SERVER['HTTPS'] = false; - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'insecure_connection_notice' ] ) ); - - set_current_screen( 'themes' ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'insecure_connection_notice' ] ) ); - - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertStringContainsString( 'notice-warning', get_echo( [ 'AMP_Options_Manager', 'insecure_connection_notice' ] ) ); - - $_SERVER['HTTPS'] = 'on'; - $set_https_url = static function ( $url ) { - return set_url_scheme( $url, 'https' ); - }; - add_filter( 'home_url', $set_https_url ); - add_filter( 'site_url', $set_https_url ); - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'insecure_connection_notice' ] ) ); - } - - /** @covers AMP_Options_Manager::reader_theme_fallback_notice() */ - public function test_reader_theme_fallback_notice() { - $admin_user = self::factory()->user->create( [ 'role' => 'administrator' ] ); - wp_set_current_user( $admin_user ); - AMP_Options_Manager::update_options( - [ - Option::THEME_SUPPORT => 'reader', - Option::READER_THEME => 'foobar', - ] - ); - - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'reader_theme_fallback_notice' ] ) ); - - set_current_screen( 'index' ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'reader_theme_fallback_notice' ] ) ); - - set_current_screen( 'themes' ); - $this->assertStringContainsString( 'notice-warning', get_echo( [ 'AMP_Options_Manager', 'reader_theme_fallback_notice' ] ) ); - - set_current_screen( 'toplevel_page_' . AMP_Options_Manager::OPTION_NAME ); - $this->assertStringContainsString( 'notice-warning', get_echo( [ 'AMP_Options_Manager', 'reader_theme_fallback_notice' ] ) ); - - AMP_Options_Manager::update_option( Option::READER_THEME, ReaderThemes::DEFAULT_READER_THEME ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'reader_theme_fallback_notice' ] ) ); - - AMP_Options_Manager::update_option( Option::READER_THEME, 'foobar' ); - wp_set_current_user( 0 ); - $this->assertEmpty( get_echo( [ 'AMP_Options_Manager', 'reader_theme_fallback_notice' ] ) ); - } -} diff --git a/tests/php/test-class-amp-playlist-embed-handler.php b/tests/php/test-class-amp-playlist-embed-handler.php deleted file mode 100644 index 35e14017a1a..00000000000 --- a/tests/php/test-class-amp-playlist-embed-handler.php +++ /dev/null @@ -1,347 +0,0 @@ -prevent_block_pre_render(); - $this->instance = new AMP_Playlist_Embed_Handler(); - } - - /** - * Tear down test. - * - * @global WP_Styles $wp_styles - */ - public function tear_down() { - global $wp_styles; - $wp_styles = null; - - AMP_Playlist_Embed_Handler::$playlist_id = 0; - - parent::tear_down(); - } - - /** - * Test register_embed. - * - * @covers AMP_Playlist_Embed_Handler::register_embed() - */ - public function test_register_embed() { - global $shortcode_tags; - $removed_shortcode = 'wp_playlist_shortcode'; - add_shortcode( 'playlist', $removed_shortcode ); - $this->instance->register_embed(); - $this->assertInstanceOf( '\\AMP_Playlist_Embed_Handler', $shortcode_tags[ AMP_Playlist_Embed_Handler::SHORTCODE ][0] ); - $this->assertEquals( 'shortcode', $shortcode_tags[ AMP_Playlist_Embed_Handler::SHORTCODE ][1] ); - $this->assertEquals( $removed_shortcode, $this->instance->removed_shortcode_callback ); - $this->instance->unregister_embed(); - } - - /** - * Test unregister_embed. - * - * @covers AMP_Playlist_Embed_Handler::unregister_embed() - */ - public function test_unregister_embed() { - global $shortcode_tags; - $expected_removed_shortcode = 'wp_playlist_shortcode'; - $this->instance->removed_shortcode_callback = $expected_removed_shortcode; - $this->instance->unregister_embed(); - $this->assertEquals( $expected_removed_shortcode, $shortcode_tags[ AMP_Playlist_Embed_Handler::SHORTCODE ] ); - } - - /** - * Test styling. - * - * @covers AMP_Playlist_Embed_Handler::enqueue_styles() - */ - public function test_styling() { - global $post; - $playlist_shortcode = 'amp-playlist-shortcode'; - $this->instance->register_embed(); - $this->assertNotContains( 'wp-mediaelement', wp_styles()->queue ); - $this->assertNotContains( $playlist_shortcode, wp_styles()->queue ); - - $post = self::factory()->post->create_and_get(); - $post->post_content = '[playlist ids="5,3"]'; - $this->instance->enqueue_styles(); - $style = wp_styles()->registered[ $playlist_shortcode ]; - $this->assertContains( $playlist_shortcode, wp_styles()->queue ); - $this->assertEquals( [ 'wp-mediaelement' ], $style->deps ); - $this->assertEquals( $playlist_shortcode, $style->handle ); - $this->assertEquals( amp_get_asset_url( 'css/amp-playlist-shortcode.css' ), $style->src ); - $this->assertEquals( AMP__VERSION, $style->ver ); - } - - /** - * Test shortcode. - * - * @covers AMP_Playlist_Embed_Handler::shortcode() - * @covers AMP_Playlist_Embed_Handler::video_playlist() - */ - public function test_shortcode() { - $attr = $this->get_attributes( 'video' ); - $playlist = $this->instance->shortcode( $attr ); - $this->assertStringContainsString( 'assertStringContainsString( 'assertStringContainsString( $this->file_1, $playlist ); - $this->assertStringContainsString( $this->file_2, $playlist ); - } - - /** - * Test video_playlist. - * - * @covers AMP_Playlist_Embed_Handler::video_playlist() - */ - public function test_video_playlist() { - $attr = $this->get_attributes( 'video' ); - $data = $this->instance->get_data( $attr ); - $playlist = $this->instance->video_playlist( $data ); - $this->assertStringContainsString( 'assertStringContainsString( 'assertStringContainsString( $this->file_1, $playlist ); - $this->assertStringContainsString( $this->file_2, $playlist ); - $this->assertStringContainsString( '[src]="wpPlaylist1[wpPlaylist1.selectedIndex].videoUrl"', $playlist ); - $this->assertStringContainsString( 'on="tap:AMP.setState({"wpPlaylist1":{"selectedIndex":0}})"', $playlist ); - } - - /** - * Test get_thumb_dimensions. - * - * @covers AMP_Playlist_Embed_Handler::get_thumb_dimensions() - */ - public function test_get_thumb_dimensions() { - $dimensions = [ - 'height' => 60, - 'width' => 60, - ]; - $track = [ - 'thumb' => $dimensions, - ]; - $this->assertEquals( $dimensions, $this->instance->get_thumb_dimensions( $track ) ); - - $dimensions = [ - 'height' => 68, - 'width' => 59, - ]; - $track = [ - 'thumb' => $dimensions, - ]; - $this->assertEquals( $dimensions, $this->instance->get_thumb_dimensions( $track ) ); - - $dimensions = [ - 'height' => 70, - 'width' => 80.5, - ]; - $expected_dimensions = [ - 'height' => 52, - 'width' => 60, - ]; - $track = [ - 'thumb' => $dimensions, - ]; - $this->assertEquals( $expected_dimensions, $this->instance->get_thumb_dimensions( $track ) ); - - $dimensions = [ - 'width' => 80.5, - ]; - $track = [ - 'thumb' => $dimensions, - ]; - $expected_dimensions = [ - 'height' => 48, - 'width' => 60, - ]; - $this->assertEquals( $expected_dimensions, $this->instance->get_thumb_dimensions( $track ) ); - - $track = [ - 'thumb' => [], - ]; - $expected_dimensions = [ - 'height' => AMP_Playlist_Embed_Handler::DEFAULT_THUMB_HEIGHT, - 'width' => AMP_Playlist_Embed_Handler::DEFAULT_THUMB_WIDTH, - ]; - $this->assertEquals( $expected_dimensions, $this->instance->get_thumb_dimensions( $track ) ); - } - - /** - * Test audio_playlist. - * - * Logic for creating the videos copied from Tests_Media. - * - * @covers AMP_Playlist_Embed_Handler::audio_playlist() - */ - public function test_audio_playlist() { - $attr = $this->get_attributes( 'audio' ); - $playlist = $this->instance->audio_playlist( [] ); - $this->assertEquals( '', $playlist ); - - $data = $this->instance->get_data( $attr ); - $playlist = $this->instance->audio_playlist( $data ); - $this->assertStringContainsString( 'assertStringContainsString( 'assertStringContainsString( $this->file_1, $playlist ); - $this->assertStringContainsString( $this->file_2, $playlist ); - $this->assertStringContainsString( 'tap:AMP.setState({"wpPlaylist1":{"selectedIndex":0}})"', $playlist ); - } - - /** - * Test tracks. - * - * @covers AMP_Playlist_Embed_Handler::print_tracks() - */ - public function test_tracks() { - $type = 'video'; - $attr = $this->get_attributes( $type ); - $data = $this->instance->get_data( $attr ); - $state_id = 'fooId1'; - $expected_on = 'tap:AMP.setState({"' . $state_id . '":{"selectedIndex":0}})'; - - $tracks = get_echo( [ $this->instance, 'print_tracks' ], [ $state_id, $data['tracks'] ] ); - $this->assertStringContainsString( '
        ', $tracks ); - $this->assertStringContainsString( $state_id, $tracks ); - $this->assertStringContainsString( $expected_on, $tracks ); - - $attr = $this->get_attributes( $type ); - $data = $this->instance->get_data( $attr ); - $expected_on = 'tap:AMP.setState({"' . $state_id . '":{"selectedIndex":0}})'; - - $tracks = get_echo( [ $this->instance, 'print_tracks' ], [ $state_id, $data['tracks'] ] ); - $this->assertStringContainsString( $expected_on, $tracks ); - } - - /** - * Test get_data. - * - * @covers AMP_Playlist_Embed_Handler::get_data() - */ - public function test_get_data() { - $type = 'audio'; - $data = $this->instance->get_data( $this->get_attributes( $type ) ); - $this->assertEquals( $type, $data['type'] ); - $this->assertStringContainsString( $this->file_1, $data['tracks'][0]['src'] ); - $this->assertStringContainsString( $this->file_2, $data['tracks'][1]['src'] ); - } - - /** - * Test get_title. - * - * @covers AMP_Playlist_Embed_Handler::get_data() - */ - public function test_get_title() { - $caption = 'Example caption'; - $title = 'Media Title'; - $track = [ - 'caption' => $caption, - ]; - - $this->assertEquals( $caption, $this->instance->get_title( $track ) ); - - $track = [ - 'title' => $title, - ]; - $this->assertEquals( $title, $this->instance->get_title( $track ) ); - - $track = [ - 'caption' => $caption, - 'title' => $title, - ]; - $this->assertEquals( $caption, $this->instance->get_title( $track ) ); - $this->assertEquals( null, $this->instance->get_title( [] ) ); - } - - /** - * Gets the shortcode attributes. - * - * @param string $type The type of shortcode attributes: 'audio' or 'video'. - * @return array $attrs The shortcode attributes. - */ - public function get_attributes( $type ) { - if ( 'audio' === $type ) { - $this->file_1 = 'example-audio-1.mp3'; - $this->file_2 = 'example-audio-2.mp3'; - $mime_type = 'audio/mp3'; - } elseif ( 'video' === $type ) { - $this->file_1 = 'example-video-1.mp4'; - $this->file_2 = 'example-video-2.mkv'; - $mime_type = 'video/mp4'; - } else { - return; - } - - $files = [ - $this->file_1, - $this->file_2, - ]; - $ids = $this->get_file_ids( $files, $mime_type ); - return [ - 'ids' => implode( ',', $ids ), - 'type' => $type, - ]; - } - - /** - * Gets test file IDs. - * - * @param array $files The file names to create. - * @param string $mime_type The type of file. - * @return array $ids The IDs of the test files. - */ - public function get_file_ids( $files, $mime_type ) { - $ids = []; - foreach ( $files as $file ) { - $ids[] = self::factory()->attachment->create_object( - $file, - 0, - [ - 'post_mime_type' => $mime_type, - 'post_type' => 'attachment', - ] - ); - } - return $ids; - } -} diff --git a/tests/php/test-class-amp-post-type-support.php b/tests/php/test-class-amp-post-type-support.php deleted file mode 100644 index cc729e06fb3..00000000000 --- a/tests/php/test-class-amp-post-type-support.php +++ /dev/null @@ -1,162 +0,0 @@ - 'Book', - 'publicly_queryable' => true, - ] - ); - register_post_type( - 'car', - [ - 'label' => 'Car', - 'public' => false, - 'publicly_queryable' => true, - ] - ); - register_post_type( - 'secret', - [ - 'label' => 'Secret', - 'publicly_queryable' => false, - ] - ); - register_post_type( - 'secret_book', - [ - 'label' => 'Secret book', - 'public' => true, - 'publicly_queryable' => false, - ] - ); - - $this->assertEqualSets( - [ - 'post', - 'page', - 'car', - 'attachment', - 'book', - ], - AMP_Post_Type_Support::get_eligible_post_types() - ); - - add_filter( - 'amp_supportable_post_types', - static function ( $post_types ) { - $post_types[] = 'secret'; - return array_diff( $post_types, [ 'attachment' ] ); - } - ); - - $this->assertEqualSets( - [ - 'post', - 'page', - 'car', - 'secret', - 'book', - ], - AMP_Post_Type_Support::get_eligible_post_types() - ); - - } - - /** - * Test get_eligible_post_types. - * - * @covers AMP_Post_Type_Support::get_eligible_post_types() - */ - public function test_get_eligible_post_types_with_filter() { - - if ( version_compare( get_bloginfo( 'version' ), '5.9', '<' ) ) { - $this->markTestSkipped( 'Requires WordPress 5.9 or greater than that.' ); - } - - register_post_type( - 'non_amp_book', - [ - 'label' => 'Non AMP book', - 'public' => true, - ] - ); - $is_post_type_viewable_callback = static function ( $is_viewable, $post_type ) { - - return 'non_amp_book' === $post_type->name ? false : $is_viewable; - }; - - add_filter( 'is_post_type_viewable', $is_post_type_viewable_callback, 10, 2 ); - - $this->assertNotContains( 'non_amp_book', AMP_Post_Type_Support::get_eligible_post_types() ); - - remove_filter( 'is_post_type_viewable', $is_post_type_viewable_callback ); - } - - /** - * Return an error code if a given post does not have AMP support. - * - * @covers AMP_Post_Type_Support::get_support_errors() - */ - public function test_get_support_error() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - register_post_type( - 'book', - [ - 'label' => 'Book', - 'public' => true, - ] - ); - - // Post type support. - $book_id = self::factory()->post->create( [ 'post_type' => 'book' ] ); - $this->assertEquals( [ 'post-type-support' ], AMP_Post_Type_Support::get_support_errors( $book_id ) ); - $supported_post_types = array_merge( - AMP_Options_Manager::get_option( Option::SUPPORTED_POST_TYPES ), - [ 'book' ] - ); - AMP_Options_Manager::update_option( Option::SUPPORTED_POST_TYPES, $supported_post_types ); - $this->assertEmpty( AMP_Post_Type_Support::get_support_errors( $book_id ) ); - - // Skip-post. - add_filter( 'amp_skip_post', '__return_true' ); - $this->assertEquals( [ 'skip-post' ], AMP_Post_Type_Support::get_support_errors( $book_id ) ); - remove_filter( 'amp_skip_post', '__return_true' ); - $this->assertEmpty( AMP_Post_Type_Support::get_support_errors( $book_id ) ); - - // Invalid post. - $this->assertEquals( [ 'invalid-post' ], AMP_Post_Type_Support::get_support_errors( null ) ); - } -} diff --git a/tests/php/test-class-amp-reader-themes-rest-controller.php b/tests/php/test-class-amp-reader-themes-rest-controller.php deleted file mode 100644 index aa964d183d8..00000000000 --- a/tests/php/test-class-amp-reader-themes-rest-controller.php +++ /dev/null @@ -1,171 +0,0 @@ -controller = new AMP_Reader_Theme_REST_Controller( new ReaderThemes() ); - $this->add_reader_themes_request_filter(); - } - - /** - * Tests AMP_Reader_Theme_REST_Controller::register_routes. - * - * @covers ::register_routes - */ - public function test_register_routes() { - $this->controller->register_routes(); - - $this->assertContains( 'amp/v1', rest_get_server()->get_namespaces() ); - $this->assertContains( '/amp/v1/reader-themes', array_keys( rest_get_server()->get_routes( 'amp/v1' ) ) ); - } - - /** - * Tests AMP_Reader_Theme_REST_Controller::get_items. - * - * @covers ::get_items - */ - public function test_get_items() { - $data = $this->controller->get_items( new WP_REST_Request( 'GET', 'amp/v1' ) )->data; - - $actual_reader_themes = wp_list_pluck( $data, 'slug' ); - $expected_reader_themes = [ - 'twentytwentyone', - 'twentytwenty', - 'twentynineteen', - 'twentyseventeen', - 'twentysixteen', - 'twentyfifteen', - 'twentyfourteen', - 'twentythirteen', - 'twentytwelve', - 'twentyeleven', - 'legacy', - ]; - - foreach ( $expected_reader_themes as $expected_reader_theme ) { - $this->assertContains( $expected_reader_theme, $actual_reader_themes ); - } - - $filter = static function() { - return [ - [ - 'name' => 'My theme', - 'slug' => 'my-theme', - 'screenshot_url' => '', - ], - ]; - }; - - // Test that only the filtered and AMP Legacy themes are returned. - $this->controller = new AMP_Reader_Theme_REST_Controller( new ReaderThemes() ); - add_filter( 'amp_reader_themes', $filter ); - - $data = $this->controller->get_items( new WP_REST_Request( 'GET', 'amp/v1' ) )->data; - - $this->assertEquals( [ 'my-theme', 'legacy' ], wp_list_pluck( $data, 'slug' ) ); - remove_filter( 'amp_reader_themes', $filter ); - } - - /** - * Test the REST Response headers when themes_api was successful. - * - * @covers ::get_items - */ - public function test_get_items_header_with_themes_api_success() { - $response = $this->controller->get_items( new WP_REST_Request( 'GET', 'amp/v1' ) ); - $this->assertEquals( [], $response->get_headers() ); - } - - /** - * Tests the REST response headers when themes_api fails. - * - * @covers ::get_items - */ - public function test_get_items_header_with_themes_api_failure() { - add_filter( 'themes_api_result', '__return_null' ); - - $response = $this->controller->get_items( new WP_REST_Request( 'GET', 'amp/v1' ) ); - $this->assertEquals( - [ 'X-AMP-Theme-API-Error' => 'The request for reader themes from WordPress.org resulted in an invalid response. Check your Site Health to confirm that your site can communicate with WordPress.org. Otherwise, please try again later or contact your host.' ], - $response->get_headers() - ); - } - - /** - * Tests the REST response headers when themes_api contains an empty themes array. - * - * @covers ::get_items - */ - public function test_get_items_header_with_themes_api_empty_array() { - $filter_cb = static function() { - return (object) [ 'themes' => [] ]; - }; - add_filter( 'themes_api_result', $filter_cb ); - - $response = $this->controller->get_items( new WP_REST_Request( 'GET', 'amp/v1' ) ); - $this->assertEquals( - [ 'X-AMP-Theme-API-Error' => 'The default reader themes cannot be displayed because a plugin appears to be overriding the themes response from WordPress.org.' ], - $response->get_headers() - ); - - } - - /** - * Test that an error is stored in state when themes_api returns an error. - * - * @covers ::get_items - */ - public function test_themes_api_remote_wp_error() { - $filter_cb = static function() { - return new WP_Error( - 'amp_test_error', - 'Test message' - ); - }; - add_filter( 'themes_api_result', $filter_cb ); - - $response = $this->controller->get_items( new WP_REST_Request( 'GET', 'amp/v1' ) ); - $headers = $response->get_headers(); - $this->assertArrayHasKey( 'X-AMP-Theme-API-Error', $headers ); - $this->assertStringStartsWith( 'The request for reader themes from WordPress.org resulted in an invalid response. Check your Site Health to confirm that your site can communicate with WordPress.org. Otherwise, please try again later or contact your host.', $headers['X-AMP-Theme-API-Error'] ); - - if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) { - $this->assertStringContainsString( 'Test message', $headers['X-AMP-Theme-API-Error'] ); - $this->assertStringContainsString( 'amp_test_error', $headers['X-AMP-Theme-API-Error'] ); - } - } -} diff --git a/tests/php/test-class-amp-schema-org-metadata.php b/tests/php/test-class-amp-schema-org-metadata.php deleted file mode 100644 index 6ddedfc975d..00000000000 --- a/tests/php/test-class-amp-schema-org-metadata.php +++ /dev/null @@ -1,91 +0,0 @@ - [ - '', - 1, - ], - 'schema_org_present' => [ - wp_json_encode( [ '@context' => 'http://schema.org' ] ), - 1, - ], - 'schema_org_output_not_escaped' => [ - '{"@context":"http://schema.org"', - 1, - ], - 'schema_org_another_key' => [ - wp_json_encode( [ '@anothercontext' => 'https://schema.org' ] ), - 1, - ], - ]; - } - - /** - * Test the transform method. - * - * @dataProvider get_schema_script_data - * - * @covers ::transform - * - * @param string $json JSON data. - * @param int $expected Expected count of valid JSON+LD schema. - */ - public function test_transform( $json, $expected ) { - $html = 'Test'; - $dom = Document::fromHtml( sprintf( $html, $json ), Options::DEFAULTS ); - $configuration = new AmpSchemaOrgMetadataConfiguration( - [ - AmpSchemaOrgMetadataConfiguration::METADATA => [ - '@context' => 'http://schema.org', - 'publisher' => [ - '@type' => 'Organization', - 'name' => 'Acme', - ], - ], - ] - ); - $transformer = new AmpSchemaOrgMetadata( $configuration ); - $errors = new ErrorCollection(); - $transformer->transform( $dom, $errors ); - $this->assertEquals( $expected, substr_count( $dom->saveHTML(), 'schema.org' ) ); - } - - /** - * Test that an empty metadata array configuration does not produce the schema.org meta script. - * - * @covers ::transform - */ - public function test_empty_metadata_configuration() { - $dom = new Document(); - $transformer = new AmpSchemaOrgMetadata( new AmpSchemaOrgMetadataConfiguration() ); - $transformer->transform( $dom, new ErrorCollection() ); - - $xpath_query = '//script[ @type = "application/ld+json" ]'; - $this->assertEquals( 0, $dom->xpath->query( $xpath_query )->length ); - } -} diff --git a/tests/php/test-class-amp-service-worker.php b/tests/php/test-class-amp-service-worker.php deleted file mode 100644 index a70c57818b7..00000000000 --- a/tests/php/test-class-amp-service-worker.php +++ /dev/null @@ -1,255 +0,0 @@ -markTestSkipped( 'PWA plugin not active.' ); - } - } - - /** - * Test default hooks in init. - * - * @covers \AMP_Service_Worker::init() - */ - public function test_default_init_hooks() { - remove_all_filters( 'query_vars' ); - remove_all_actions( 'parse_request' ); - remove_all_actions( 'wp' ); - remove_all_actions( 'wp_front_service_worker' ); - - AMP_Service_Worker::init(); - $this->assertSame( 10, has_filter( 'query_vars', [ 'AMP_Service_Worker', 'add_query_var' ] ) ); - $this->assertSame( 10, has_action( 'parse_request', [ 'AMP_Service_Worker', 'handle_service_worker_iframe_install' ] ) ); - $this->assertSame( 10, has_action( 'wp', [ 'AMP_Service_Worker', 'add_install_hooks' ] ) ); - - $this->assertSame( 10, has_action( 'wp_front_service_worker', [ 'AMP_Service_Worker', 'add_cdn_script_caching' ] ) ); - $this->assertFalse( has_action( 'wp_front_service_worker', [ 'AMP_Service_Worker', 'add_image_caching' ] ) ); - $this->assertFalse( has_action( 'wp_front_service_worker', [ 'AMP_Service_Worker', 'add_google_fonts_caching' ] ) ); - } - - /** - * Test unconditional hooks in init. - * - * @covers \AMP_Service_Worker::init() - */ - public function test_theme_support_hooks() { - remove_all_filters( 'query_vars' ); - remove_all_actions( 'parse_request' ); - remove_all_actions( 'wp' ); - remove_all_actions( 'wp_front_service_worker' ); - - add_theme_support( - 'amp', - [ - 'service_worker' => [ - 'cdn_script_caching' => false, - 'image_caching' => true, - 'google_fonts_caching' => true, - ], - ] - ); - - AMP_Service_Worker::init(); - $this->assertFalse( has_action( 'wp_front_service_worker', [ 'AMP_Service_Worker', 'add_cdn_script_caching' ] ) ); - $this->assertSame( 10, has_action( 'wp_front_service_worker', [ 'AMP_Service_Worker', 'add_image_caching' ] ) ); - $this->assertSame( 10, has_action( 'wp_front_service_worker', [ 'AMP_Service_Worker', 'add_google_fonts_caching' ] ) ); - } - - /** - * Test add_query_var(). - * - * @covers \AMP_Service_Worker::add_query_var() - */ - public function test_add_query_var() { - $query_vars = AMP_Service_Worker::add_query_var( [ 'foo' ] ); - $this->assertSame( 'foo', $query_vars[0] ); - $this->assertCount( 2, $query_vars ); - $this->assertIsString( $query_vars[1] ); - } - - /** - * Test add_cdn_script_caching(). - * - * @covers \AMP_Service_Worker::add_cdn_script_caching() - */ - public function test_add_cdn_script_caching() { - AMP_Service_Worker::add_cdn_script_caching( wp_service_workers()->get_registry() ); - $this->assertArrayHasKey( 'amp-cdn-runtime-caching', wp_service_workers()->get_registry()->registered ); - } - - /** - * Test add_image_caching(). - * - * @covers \AMP_Service_Worker::add_image_caching() - */ - public function test_add_image_caching() { - $before = wp_service_workers()->get_registry()->caching_routes()->get_all(); - AMP_Service_Worker::add_image_caching( wp_service_workers()->get_registry() ); - $after = wp_service_workers()->get_registry()->caching_routes()->get_all(); - - $this->assertCount( count( $before ) + 1, $after ); - } - - /** - * Test add_google_fonts_caching(). - * - * @covers \AMP_Service_Worker::add_google_fonts_caching() - */ - public function test_add_google_fonts_caching() { - if ( class_exists( 'WP_Service_Worker_Fonts_Integration' ) ) { - $this->markTestSkipped( 'WP_Service_Worker_Fonts_Integration is present.' ); - } - $before = wp_service_workers()->get_registry()->caching_routes()->get_all(); - AMP_Service_Worker::add_google_fonts_caching( wp_service_workers()->get_registry() ); - $after = wp_service_workers()->get_registry()->caching_routes()->get_all(); - $this->assertCount( count( $before ) + 2, $after ); - } - - /** - * Test get_precached_script_cdn_urls(). - * - * @covers \AMP_Service_Worker::get_precached_script_cdn_urls() - */ - public function test_get_precached_script_cdn_urls() { - $urls = AMP_Service_Worker::get_precached_script_cdn_urls(); - - $this->assertIndexedArrayContains( - [ - wp_scripts()->registered['amp-runtime']->src, - wp_scripts()->registered['amp-bind']->src, - wp_scripts()->registered['amp-form']->src, - wp_scripts()->registered['amp-install-serviceworker']->src, - ], - $urls - ); - - // Comments. - $this->assertNotContains( - wp_scripts()->registered['amp-live-list']->src, - $urls - ); - add_theme_support( - 'amp', - [ - 'comments_live_list' => true, - ] - ); - $this->assertContains( - wp_scripts()->registered['amp-live-list']->src, - AMP_Service_Worker::get_precached_script_cdn_urls() - ); - - // Analytics. - $this->assertNotContains( - wp_scripts()->registered['amp-analytics']->src, - $urls - ); - add_filter( - 'amp_analytics_entries', - static function () { - return [ - [ - 'type' => 'foo', - 'config' => '{}', - ], - ]; - } - ); - $this->assertContains( - wp_scripts()->registered['amp-analytics']->src, - AMP_Service_Worker::get_precached_script_cdn_urls() - ); - } - - /** - * Test add_install_hooks(). - * - * @covers \AMP_Service_Worker::add_install_hooks() - */ - public function test_add_install_hooks() { - remove_all_actions( 'amp_post_template_footer' ); - remove_all_actions( 'wp_footer' ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - - $post_id = self::factory()->post->create(); - $this->go_to( get_permalink( $post_id ) ); - - $this->assertFalse( amp_is_request() ); - AMP_Service_Worker::add_install_hooks(); - $this->assertFalse( has_action( 'amp_post_template_footer', [ 'AMP_Service_Worker', 'install_service_worker' ] ) ); - $this->assertFalse( has_action( 'wp_footer', [ 'AMP_Service_Worker', 'install_service_worker' ] ) ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->assertTrue( amp_is_request() ); - AMP_Service_Worker::add_install_hooks(); - $this->assertSame( 10, has_action( 'wp_footer', [ 'AMP_Service_Worker', 'install_service_worker' ] ) ); - $this->assertFalse( has_action( 'wp_print_scripts', [ 'AMP_Service_Worker', 'wp_print_service_workers' ] ) ); - } - - /** - * Test install_service_worker(). - * - * @covers \AMP_Service_Worker::install_service_worker() - */ - public function test_install_service_worker() { - $output = get_echo( [ 'AMP_Service_Worker', 'install_service_worker' ] ); - - $this->assertStringContainsString( 'go_to( home_url() ); - - // Now try to go to the iframe endpoint. - ob_start(); - $exception = null; - try { - $this->go_to( add_query_arg( AMP_Service_Worker::INSTALL_SERVICE_WORKER_IFRAME_QUERY_VAR, '1', home_url() ) ); - } catch ( Exception $e ) { - $exception = $e; - } - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 'exited', $exception->getMessage() ); - $output = ob_get_clean(); - $this->assertStringContainsString( ''; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - $this->assertEquals( $tag, AMP_Theme_Support::filter_admin_bar_script_loader_tag( $tag, 'example' ) ); - } - - /** - * Test init_admin_bar to ensure dashicons are not added to dev mode when directly enqueued. - * - * @covers \AMP_Theme_Support::init_admin_bar() - * @covers \AMP_Theme_Support::filter_admin_bar_style_loader_tag() - */ - public function test_init_admin_bar_for_directly_enqueued_dashicons() { - require_once ABSPATH . WPINC . '/class-wp-admin-bar.php'; - - global $wp_admin_bar; - $wp_admin_bar = new WP_Admin_Bar(); - $wp_admin_bar->initialize(); - AMP_Theme_Support::init_admin_bar(); - - // Enqueued directly. - wp_enqueue_style( 'dashicons' ); - - ob_start(); - wp_print_styles(); - $output = ob_get_clean(); - - $this->assertStringContainsString( 'assertStringNotContainsString( 'assertStringContainsString( 'initialize(); - AMP_Theme_Support::init_admin_bar(); - - // Enqueued indirectly. - wp_enqueue_style( 'my-font-pack', 'https://example.com/fonts', [ 'dashicons' ], '0.1' ); - - ob_start(); - wp_print_styles(); - $output = ob_get_clean(); - - $this->assertStringContainsString( 'assertStringNotContainsString( 'assertStringContainsString( ' - - - - - - - - - - - - xpath->query( '//script[ not( @type ) or @type = "text/javascript" ]' ); - $this->assertSame( 3, $scripts->length ); - foreach ( $scripts as $script ) { - $this->assertSame( 'head', $script->parentNode->nodeName ); - } - } - - /** - * Test removing AMP scripts that are not needed. - * - * @covers AMP_Theme_Support::ensure_required_markup() - */ - public function test_unneeded_scripts_get_removed() { - wp_styles(); // Needed after . - - wp(); - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - - // These should all get removed, unless used. - $required_usage_exempted = [ - 'amp-anim', - 'amp-ad', - 'amp-mustache', - 'amp-list', - 'amp-youtube', - 'amp-form', - 'amp-live-list', - ]; - - $conditionally_allowed_usage = [ - 'amp-carousel', - ]; - - // These also should get removed, unless used. - $required_usage_error = [ - 'amp-facebook-like', - 'amp-date-picker', - 'amp-call-tracking', - ]; - - // These should not get removed, ever. - $required_usage_none = [ - 'amp-bind', // And yet, see https://github.com/ampproject/amphtml/blob/eb05855/extensions/amp-bind/validator-amp-bind.protoascii#L25-L28 - 'amp-dynamic-css-classes', - 'amp-subscriptions', - 'amp-lightbox-gallery', - ]; - - ob_start(); - ?> - - - - - - - - - - - - xpath->query( '//script[ not( @amp-onerror ) and ( not( @type ) or @type = "text/javascript" ) ]' ) as $script ) { - $actual_script_srcs[] = $script->getAttribute( 'src' ); - } - - $expected_script_srcs = [ - wp_scripts()->registered['amp-runtime']->src, - ]; - foreach ( array_merge( $required_usage_none, $conditionally_allowed_usage ) as $handle ) { - $expected_script_srcs[] = wp_scripts()->registered[ $handle ]->src; - } - - $this->assertEqualSets( - array_map( 'basename', $expected_script_srcs ), - array_map( 'basename', $actual_script_srcs ) - ); - } - - /** - * Test removing duplicate scripts. - * - * @covers AMP_Theme_Support::prepare_response() - * @covers AMP_Theme_Support::ensure_required_markup() - */ - public function test_duplicate_scripts_are_removed() { - wp_styles(); // Needed after . - - wp(); - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - - // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript - ob_start(); - ?> - - - - - - - - - - - -
        -

        This browser does not support the video element.

        -
        -
        - - - - - false ] ); - - $dom = Document::fromHtml( $html, Options::DEFAULTS ); - - $script_srcs = []; - /** - * Script. - * - * @var DOMElement $script - */ - $scripts = $dom->xpath->query( '//script[ @src ]' ); - foreach ( $scripts as $script ) { - $script_srcs[] = $script->getAttribute( 'src' ); - } - - $this->assertCount( 2, $script_srcs ); - $this->assertEquals( - $script_srcs, - [ - 'https://cdn.ampproject.org/v0.js', - 'https://cdn.ampproject.org/v0/amp-video-0.1.js', - ] - ); - } - - /** - * Test dequeue_customize_preview_scripts. - * - * @covers AMP_Theme_Support::dequeue_customize_preview_scripts() - */ - public function test_dequeue_customize_preview_scripts() { - // Ensure AMP_Theme_Support::is_customize_preview_iframe() is true. - require_once ABSPATH . WPINC . '/class-wp-customize-manager.php'; - $GLOBALS['wp_customize'] = new WP_Customize_Manager( - [ - 'messenger_channel' => 'baz', - ] - ); - $GLOBALS['wp_customize']->start_previewing_theme(); - $customize_preview = 'customize-preview'; - $preview_style = 'example-preview-style'; - wp_enqueue_style( $preview_style, home_url( '/' ), [ $customize_preview ] ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion - AMP_Theme_Support::dequeue_customize_preview_scripts(); - $this->assertTrue( wp_style_is( $preview_style ) ); - $this->assertTrue( wp_style_is( $customize_preview ) ); - - wp_enqueue_style( $preview_style, home_url( '/' ), [ $customize_preview ] ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion - wp_enqueue_style( $customize_preview ); - // Ensure AMP_Theme_Support::is_customize_preview_iframe() is false. - $GLOBALS['wp_customize'] = new WP_Customize_Manager(); - AMP_Theme_Support::dequeue_customize_preview_scripts(); - $this->assertFalse( wp_style_is( $preview_style ) ); - $this->assertFalse( wp_style_is( $customize_preview ) ); - } - - /** - * Test start_output_buffering. - * - * @covers AMP_Theme_Support::start_output_buffering() - * @covers AMP_Theme_Support::is_output_buffering() - * @covers AMP_Theme_Support::finish_output_buffering() - */ - public function test_start_output_buffering() { - wp(); - if ( ! function_exists( 'newrelic_disable_autorum' ) ) { - - /** - * Define newrelic_disable_autorum to allow passing line. - */ - function newrelic_disable_autorum() { - return true; - } - } - - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - - $initial_ob_level = ob_get_level(); - AMP_Theme_Support::start_output_buffering(); - $this->assertEquals( $initial_ob_level + 1, ob_get_level() ); - ob_end_flush(); - $this->assertEquals( $initial_ob_level, ob_get_level() ); - } - - /** - * Test finish_output_buffering. - * - * @covers AMP_Theme_Support::finish_output_buffering() - * @covers AMP_Theme_Support::is_output_buffering() - */ - public function test_finish_output_buffering() { - wp_styles(); // Needed after . - - wp(); - add_filter( 'amp_validation_error_sanitized', '__return_true' ); - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - - $status = ob_get_status(); - $this->assertSame( 1, ob_get_level() ); - $this->assertEquals( 'default output handler', $status['name'] ); - $this->assertFalse( AMP_Theme_Support::is_output_buffering() ); - - // start first layer buffer. - ob_start(); - AMP_Theme_Support::start_output_buffering(); - $this->assertTrue( AMP_Theme_Support::is_output_buffering() ); - $this->assertSame( 3, ob_get_level() ); - - echo ''; - wp_footer(); - - // Additional nested output bufferings which aren't getting closed. - ob_start(); - echo 'foo'; - ob_start( - static function( $response ) { - return strtoupper( $response ); - } - ); - echo 'bar'; - - $this->assertTrue( AMP_Theme_Support::is_output_buffering() ); - while ( ob_get_level() > 2 ) { - ob_end_flush(); - } - $this->assertFalse( AMP_Theme_Support::is_output_buffering() ); - $output = ob_get_clean(); - $this->assertEquals( 1, ob_get_level() ); - - $this->assertStringContainsString( 'assertStringContainsString( 'foo', $output ); - $this->assertStringContainsString( 'BAR', $output ); - $this->assertStringContainsString( 'assertStringNotContainsString( ''; - $output = AMP_Theme_Support::filter_customize_partial_render( $partial ); - $this->assertStringContainsString( 'assertStringContainsString( '', $output ); - $this->assertStringNotContainsString( 'assertStringNotContainsString( 'set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - add_filter( - 'home_url', - static function ( $url ) { - return set_url_scheme( $url, 'https' ); - } - ); - - wp(); - - // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - $original_html = $this->get_original_html(); - - $this->set_private_property( AMP_Theme_Support::class, 'metadata', amp_get_schemaorg_metadata() ); - - $call_prepare_response = static function() use ( $original_html ) { - AMP_HTTP::$headers_sent = []; - AMP_Validation_Manager::$validation_results = []; - return AMP_Theme_Support::prepare_response( $original_html ); - }; - - $amp_finalize_dom_count = did_action( 'amp_finalize_dom' ); - add_action( - 'amp_finalize_dom', - function ( $dom, $effective_sandboxing_level ) { - $this->assertInstanceOf( Document::class, $dom ); - $this->assertIsInt( $effective_sandboxing_level ); - $this->assertSame( 3, $effective_sandboxing_level ); - }, - 10, - 2 - ); - - $sanitized_html = $call_prepare_response(); - - $this->assertSame( $amp_finalize_dom_count + 1, did_action( 'amp_finalize_dom' ) ); - - $this->assertStringNotContainsString( 'handle=', $sanitized_html ); - $this->assertEquals( 2, did_action( 'wp_print_scripts' ) ); - - $ordered_contains = [ - '', - '', - '', - '', - '', - '', - '', - '', - - '', - '', - '', - - '', - '', - '', - '', - - '', - '', - '', - - '##s', - - '', - '<link rel="canonical" href="', - '<script type="application/ld+json">{"@context"', - - '#<style amp-boilerplate(="")?>#', - '#<noscript><style amp-boilerplate(="")?>#', - '</head>', - ]; - - $last_position = -1; - $prev_ordered_contain = ''; - foreach ( $ordered_contains as $ordered_contain ) { - if ( '#' === substr( $ordered_contain, 0, 1 ) ) { - $this->assertEquals( 1, preg_match( $ordered_contain, $sanitized_html, $matches, PREG_OFFSET_CAPTURE ), "Failed to find: $ordered_contain" ); - $this->assertGreaterThan( $last_position, $matches[0][1], "'$ordered_contain' is not after '$prev_ordered_contain' in:\n$sanitized_html" ); - $last_position = $matches[0][1]; - } else { - $this_position = strpos( $sanitized_html, $ordered_contain ); - $this->assertNotFalse( $this_position, "Failed to find: $ordered_contain in:\n$sanitized_html" ); - $this->assertGreaterThan( $last_position, (int) $this_position, "'$ordered_contain' is not after '$prev_ordered_contain'" ); - $last_position = $this_position; - } - $prev_ordered_contain = $ordered_contain; - } - - $this->assertStringContainsString( '<noscript><img', $sanitized_html ); - $this->assertStringContainsString( '<amp-img', $sanitized_html ); - - $this->assertStringContainsString( '<noscript><audio', $sanitized_html ); - $this->assertStringContainsString( '<amp-audio', $sanitized_html ); - - $removed_nodes = []; - foreach ( AMP_Validation_Manager::$validation_results as $result ) { - if ( $result['sanitized'] && isset( $result['error']['node_name'] ) ) { - $node_name = $result['error']['node_name']; - if ( ! isset( $removed_nodes[ $node_name ] ) ) { - $removed_nodes[ $node_name ] = 0; - } - $removed_nodes[ $node_name ]++; - } - } - - $this->assertStringContainsString( '<button>no-onclick</button>', $sanitized_html ); - $this->assertCount( 5, AMP_Validation_Manager::$validation_results ); - $this->assertEquals( - [ - 'onclick' => 1, - 'handle' => 3, - 'script' => 1, - ], - $removed_nodes - ); - - // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - } - - /** - * Test prepare_response when dev mode is forced. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_in_forced_dev_mode() { - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - - add_filter( 'amp_dev_mode_enabled', '__return_true' ); - wp(); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $html = AMP_Theme_Support::prepare_response( $this->get_original_html() ); - $this->assertStringContainsString( '<html amp', $html ); - - wp_set_current_user( 0 ); - $html = AMP_Theme_Support::prepare_response( $this->get_original_html() ); - $this->assertStringNotContainsString( '<html amp', $html ); - } - - /** - * Test prepare_response when Bento is enabled. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_in_bento() { - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - - add_filter( 'amp_bento_enabled', '__return_true' ); - wp(); - - $html = AMP_Theme_Support::prepare_response( $this->get_original_html() ); - $this->assertStringContainsString( '<script ' . ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE . '>(self.AMP = self.AMP || []).push(function (AMP) { AMP.toggleExperiment("bento", true); });</script>', $html ); - $this->assertStringContainsString( 'amp-facebook-1.0', $html ); // As opposed to amp-facebook-page-0.1, since Bento is enabled. - } - - /** - * Test prepare_response when Bento is enabled and in dev mode. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_in_bento_with_dev_mode() { - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - - add_filter( 'amp_dev_mode_enabled', '__return_true' ); - add_filter( 'amp_bento_enabled', '__return_true' ); - wp(); - - $html = AMP_Theme_Support::prepare_response( $this->get_original_html() ); - $this->assertStringContainsString( '<script ' . ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE . ' data-ampdevmode>(self.AMP = self.AMP || []).push(function (AMP) { AMP.toggleExperiment("bento", true); });</script>', $html ); - $this->assertStringContainsString( 'amp-facebook-1.0', $html ); // As opposed to amp-facebook-page-0.1, since Bento is enabled. - } - - /** - * Test prepare_response when Bento is not enabled. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_without_bento() { - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - - wp(); - - $html = AMP_Theme_Support::prepare_response( $this->get_original_html() ); - $this->assertStringNotContainsString( 'AMP.toggleExperiment("bento", true);', $html ); - $this->assertStringContainsString( 'amp-facebook-page-0.1', $html ); // As opposed to amp-facebook-page-1.0, since Bento is not enabled. - } - - /** @return array */ - public function get_data_to_test_prepare_response_standard_mode_non_amp() { - return [ - 'without_amp_live_list' => [ false ], - 'with_amp_live_list' => [ true ], - ]; - } - - /** - * Test prepare_response for standard mode when some validation errors aren't auto-sanitized. - * - * @dataProvider get_data_to_test_prepare_response_standard_mode_non_amp - * @covers AMP_Theme_Support::prepare_response() - * @param bool $with_amp_live_list - */ - public function test_prepare_response_standard_mode_non_amp( $with_amp_live_list ) { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - add_filter( 'amp_dev_mode_enabled', '__return_false' ); - wp(); - $original_html = $this->get_original_html(); - if ( $with_amp_live_list ) { - $amp_live_list = ' - <amp-live-list id="live-list-2" data-poll-interval="20000" data-max-items-per-page="10"> - <div update class="slide" on="tap:live-list-2.update">new updates on live list 2</div> - <div items> - <div id="live-list-2-item-2" data-sort-time="1464281932879">world</div> - <div id="live-list-2-item-1" data-sort-time="1464281932878">hello</div> - </div> - </amp-live-list> - '; - $original_html = preg_replace( '#<body.*?>#', '$0' . $amp_live_list, $original_html ); - } - add_filter( 'amp_validation_error_sanitized', '__return_false' ); // For testing purpose only. This should not normally be done. - - $sanitized_html = AMP_Theme_Support::prepare_response( $original_html, [ ConfigurationArgument::ENABLE_OPTIMIZER => false ] ); - - $this->assertStringContainsString( '<html>', $sanitized_html, 'The AMP attribute is removed from the HTML element' ); - $this->assertStringContainsString( '<button onclick="alert', $sanitized_html, 'Invalid AMP is present in the response.' ); - if ( $with_amp_live_list ) { - $this->assertStringContainsString( 'document.write = function', $sanitized_html, 'Override of document.write() is present.' ); - } else { - $this->assertStringNotContainsString( 'document.write = function', $sanitized_html, 'Override of document.write() is present.' ); - } - } - - /** @return array */ - public function get_data_for_allowing_native_post_forms() { - return [ - 'keep_post_forms' => [ false ], - 'convert_post_forms' => [ true ], - ]; - } - - /** - * Test prepare_response when allowing post forms. - * - * @dataProvider get_data_for_allowing_native_post_forms - * @covers AMP_Theme_Support::prepare_response() - * @param bool $converted Whether the POST form should be converted to amp-form. - */ - public function test_prepare_response_when_allowing_native_post_forms( $converted ) { - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - - add_filter( - 'amp_content_sanitizers', - static function ( $sanitizers ) use ( $converted ) { - $sanitizers[ AMP_Form_Sanitizer::class ]['native_post_forms_allowed'] = $converted ? 'never' : 'always'; - return $sanitizers; - } - ); - - wp(); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - ob_start(); - ?> - <html amp> - <body> - <form action="https://example.com/" method="Post"> - <button type="submit">Submit!</button> - </form> - </body> - </html> - <?php - - $amp_finalize_dom_count = did_action( 'amp_finalize_dom' ); - add_action( - 'amp_finalize_dom', - function ( $dom, $effective_sandboxing_level ) use ( $converted ) { - $this->assertInstanceOf( Document::class, $dom ); - $this->assertIsInt( $effective_sandboxing_level ); - $this->assertSame( $converted ? 3 : 2, $effective_sandboxing_level ); - }, - 10, - 2 - ); - - $html = AMP_Theme_Support::prepare_response( ob_get_clean() ); - - $this->assertSame( $amp_finalize_dom_count + 1, did_action( 'amp_finalize_dom' ) ); - - $dom = Document::fromHtml( $html ); - - $this->assertEquals( $converted, $dom->documentElement->hasAttribute( Attribute::AMP ) ); - $this->assertEquals( - $converted, - $dom->xpath->query( '//script[ @custom-element = "amp-form" ]' )->length > 0 - ); - $form = $dom->getElementsByTagName( 'form' )->item( 0 ); - $this->assertInstanceOf( Element::class, $form ); - $this->assertEquals( 'post', strtolower( $form->getAttribute( Attribute::METHOD ) ) ); - $this->assertEquals( $converted, $form->hasAttribute( Attribute::ACTION_XHR ) ); - $this->assertEquals( ! $converted, $form->hasAttribute( Attribute::ACTION ) ); - $this->assertEquals( ! $converted, $form->hasAttribute( ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ) ); - } - - /** - * Test prepare_response when submitting form. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_for_submitted_form() { - AMP_HTTP::$purged_amp_query_vars[ AMP_HTTP::ACTION_XHR_CONVERTED_QUERY_VAR ] = true; - $_SERVER['REQUEST_METHOD'] = 'POST'; - - $response = AMP_Theme_Support::prepare_response( '<p>¡Tienes éxito!</p>' ); - $this->assertEquals( '{"status_code":200,"status_text":"OK"}', $response ); - - unset( AMP_HTTP::$purged_amp_query_vars[ AMP_HTTP::ACTION_XHR_CONVERTED_QUERY_VAR ] ); - unset( $_SERVER['REQUEST_METHOD'] ); - } - - /** - * Test prepare_response when validating a non-AMP page. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_for_validating_non_amp_page() { - $this->set_private_property( AMP_Validation_Manager::class, 'is_validate_request', true ); - - $response = AMP_Theme_Support::prepare_response( '' ); - $this->assertJson( $response ); - $this->assertStringContainsString( 'RENDERED_PAGE_NOT_AMP', $response ); - } - - /** @return array */ - public function get_data_to_test_prepare_response_for_validating_amp_page() { - return [ - 'no-store' => [ - 'args' => [ - AMP_Validation_Manager::VALIDATE_QUERY_VAR_NONCE => AMP_Validation_Manager::get_amp_validate_nonce(), - ], - ], - 'store' => [ - 'args' => [ - AMP_Validation_Manager::VALIDATE_QUERY_VAR_NONCE => AMP_Validation_Manager::get_amp_validate_nonce(), - AMP_Validation_Manager::VALIDATE_QUERY_VAR_CACHE => true, - ], - ], - 'store_but_omit_styleshets' => [ - 'args' => [ - AMP_Validation_Manager::VALIDATE_QUERY_VAR_NONCE => AMP_Validation_Manager::get_amp_validate_nonce(), - AMP_Validation_Manager::VALIDATE_QUERY_VAR_CACHE => true, - AMP_Validation_Manager::VALIDATE_QUERY_VAR_OMIT_STYLESHEETS => true, - ], - ], - ]; - } - - /** - * Test prepare_response when validating an AMP page. - * - * @dataProvider get_data_to_test_prepare_response_for_validating_amp_page - * @covers AMP_Theme_Support::prepare_response() - * @covers AMP_Validation_Manager::send_validate_response() - */ - public function test_prepare_response_for_validating_amp_page( $args ) { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->go_to( '/' ); - - $_GET[ AMP_Validation_Manager::VALIDATE_QUERY_VAR ] = $args; - AMP_Validation_Manager::init_validate_request(); - AMP_Theme_Support::finish_init(); - $response = AMP_Theme_Support::prepare_response( '<html amp><head><style>body{color:red}</style></head><body><amp-layout layout="bad"></amp-layout></body></html>' ); - $this->assertJson( $response ); - $data = json_decode( $response, true ); - $this->assertArrayHasKey( 'http_status_code', $data ); - $this->assertArrayHasKey( 'php_fatal_error', $data ); - $this->assertArrayHasKey( 'queried_object', $data ); - $this->assertArrayHasKey( 'url', $data ); - if ( ! empty( $args[ AMP_Validation_Manager::VALIDATE_QUERY_VAR_OMIT_STYLESHEETS ] ) ) { - $this->assertArrayNotHasKey( 'stylesheets', $data ); - } else { - $this->assertArrayHasKey( 'stylesheets', $data ); - } - $this->assertArrayHasKey( 'results', $data ); - $this->assertCount( 1, $data['results'] ); - $this->assertEquals( 'SPECIFIED_LAYOUT_INVALID', $data['results'][0]['error']['code'] ); - $this->assertTrue( $data['revalidated'] ); - - if ( ! empty( $args[ AMP_Validation_Manager::VALIDATE_QUERY_VAR_CACHE ] ) ) { - $this->assertArrayHasKey( 'validated_url_post', $data ); - $this->assertArrayHasKey( 'id', $data['validated_url_post'] ); - $this->assertArrayHasKey( 'edit_link', $data['validated_url_post'] ); - $this->assertEquals( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, get_post_type( $data['validated_url_post']['id'] ) ); - } else { - $this->assertArrayNotHasKey( 'validated_url_post', $data ); - } - } - - /** - * Initializes and returns the original HTML. - */ - private function get_original_html() { - // Remove ID attributes which were added in WP 5.5. - add_filter( - 'script_loader_tag', - static function ( $script ) { - return preg_replace( '/ id=(["\'])amp-.*?\1/', '', $script ); - } - ); - - // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - global $wp_widget_factory, $wp_scripts, $wp_styles; - $wp_scripts = null; - $wp_styles = null; - wp_scripts(); - wp_styles(); - - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - $wp_widget_factory->widgets = []; - wp_widgets_init(); - - $this->assertTrue( amp_is_request() ); - - add_action( - 'wp_enqueue_scripts', - static function() { - wp_enqueue_script( 'amp-list' ); - wp_enqueue_style( 'my-font', 'https://fonts.googleapis.com/css?family=Tangerine', [], null ); // phpcs:ignore - } - ); - - add_filter( - 'script_loader_tag', - static function( $tag, $handle ) { - if ( ! wp_scripts()->get_data( $handle, 'conditional' ) ) { - $tag = preg_replace( '/(?<=<script)/', " handle='$handle' ", $tag ); - } - return $tag; - }, - 10, - 2 - ); - - add_action( - 'wp_footer', - static function() { - wp_print_scripts( 'amp-mathml' ); - ?> - <amp-mathml layout="container" data-formula="\[x = {-b \pm \sqrt{b^2-4ac} \over 2a}.\]"></amp-mathml> - <?php - }, - 1 - ); - - add_filter( - 'get_site_icon_url', - static function() { - return home_url( '/favicon.png' ); - } - ); - - // Specify file paths for stylesheets not available in src. - foreach ( [ 'wp-block-library', 'wp-block-library-theme' ] as $src_style_handle ) { - if ( wp_style_is( $src_style_handle, 'registered' ) ) { - wp_styles()->registered[ $src_style_handle ]->src = amp_get_asset_url( 'css/amp-default.css' ); // A dummy path. - } - } - - // Do the same as add_theme_support( 'title-tag' ) but without triggering _doing_it_wrong(). - global $_wp_theme_features; - $_wp_theme_features['title-tag'] = []; - - ob_start(); - ?> - <!DOCTYPE html> - <html> - <head> - <?php wp_head(); ?> - <script data-head>document.write('Illegal');</script> - <script async custom-element="amp-dynamic-css-classes" src="https://cdn.ampproject.org/v0/amp-dynamic-css-classes-0.1.js"></script> - </head> - <body><!-- </body></html> --> - <div id="dynamic-id-0"></div> - <!-- 2nd image is needed for testing <noscript> as first is SSR'ed --> - <img width="100" height="100" src="https://example.com/hero.png"> - <img width="100" height="100" src="https://example.com/test.png"> - <audio src="https://example.com/audios/myaudio.mp3"></audio> - <amp-ad type="a9" - width="300" - height="250" - data-aax_size="300x250" - data-aax_pubname="test123" - data-aax_src="302"></amp-ad> - <amp-facebook-page width="340" height="130" layout="responsive" data-href="https://www.facebook.com/imdb/"></amp-facebook-page> - - <?php wp_footer(); ?> - - <button onclick="alert('Illegal');">no-onclick</button> - - <style>body { background: black; }</style> - - <amp-experiment> - <script type="application/json"> - { "aExperiment": {} } - </script> - </amp-experiment> - <amp-list src="https://example.com/list.json?RANDOM" width="100" height="100"></amp-list> - </body> - </html> - <!--comment-after-html--> - <div id="after-html"></div> - <!--comment-end-html--> - <?php - return trim( ob_get_clean() ); - // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet - } - - /** - * Test prepare_response for responses that do not trigger standard template actions. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_doing_template_actions() { - global $wp_actions; - wp(); - $this->set_template_mode( AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - - // JSON. - $input = '{"success":true}'; - $this->assertEquals( $input, AMP_Theme_Support::prepare_response( $input ) ); - - // Nothing, for redirect. - $input = ''; - $this->assertEquals( $input, AMP_Theme_Support::prepare_response( $input ) ); - - // HTML, but a fragment. - $input = '<ul><li>one</li><li>two</li><li>three</li></ul>'; - $this->assertEquals( $input, AMP_Theme_Support::prepare_response( $input ) ); - - // HTML, but still a fragment. - $input = '<html><header><h1>HellO!</h1></header></html>'; - $this->assertEquals( $input, AMP_Theme_Support::prepare_response( $input ) ); - - // HTML but no template actions triggered. - $input = '<html><head></head></html>'; - $this->assertEquals( $input, AMP_Theme_Support::prepare_response( $input ) ); - - // HTML with AMP attribute. - $input = '<html amp><head></head>Hello</html>'; - $output = AMP_Theme_Support::prepare_response( $input ); - $this->assertStringContainsString( '<html amp', $output ); - $this->assertStringContainsString( '<meta charset="utf-8">', $output ); - - // HTML with AMP emoji attribute. - $input = '<html ⚡><head></head>Hello</html>'; - $output = AMP_Theme_Support::prepare_response( $input ); - $this->assertStringContainsString( '<html amp', $output ); - $this->assertStringContainsString( '<meta charset="utf-8">', $output ); - - // HTML with alternative AMP emoji attribute. - $input = '<html lang="en-US" ⚡️ foo="" bar="baz"><head></head>Hello</html>'; - $output = AMP_Theme_Support::prepare_response( $input ); - $this->assertStringContainsString( '<html lang="en-US" amp', $output ); - $this->assertStringContainsString( '<meta charset="utf-8">', $output ); - - // HTML with doctype, comments, and whitespace before head. - $input = " <!--\nHello world!\n-->\n\n<!DOCTYPE html> <html\n\namp>\n<head profile='http://www.acme.com/profiles/core'></head><body>Hello</body></html>"; - $output = AMP_Theme_Support::prepare_response( $input ); - $this->assertStringContainsString( '<html amp', $output ); - $this->assertStringContainsString( '<meta charset="utf-8">', $output ); - - $get_do_action = static function ( $action ) { - return get_echo( 'do_action', [ $action ] ); - }; - foreach ( [ 'wp_head', 'wp_footer', 'amp_post_template_head', 'amp_post_template_footer' ] as $action ) { - $wp_actions = []; - wp_enqueue_scripts(); - $input = '<html><head></head>' . $get_do_action( $action ) . '</html>'; - $output = AMP_Theme_Support::prepare_response( $input ); - $this->assertStringContainsString( '<html amp', $output ); - $this->assertStringContainsString( '<meta charset="utf-8">', $output ); - } - } - - /** - * Test prepare_response for responses that throw an exception. - * - * @covers AMP_Theme_Support::prepare_response() - * @covers AMP_Theme_Support::render_error_page() - */ - public function test_prepare_response_throwing_exception() { - // Set up temporary capture of error log to test error log output. - $capture = tmpfile(); - $backup = ini_set( // phpcs:ignore WordPress.PHP.IniSet.Risky - 'error_log', - stream_get_meta_data( $capture )['uri'] - ); - - add_filter( - 'amp_enable_optimizer', - static function () { - throw new RuntimeException( 'FAILURE', 42 ); - } - ); - - if ( ! function_exists( 'newrelic_disable_autorum' ) ) { - - /** - * Define newrelic_disable_autorum to allow passing line. - */ - function newrelic_disable_autorum() { - return true; - } - } - - wp(); - $output = AMP_Theme_Support::finish_output_buffering( $this->get_original_html() ); - - // Verify that error log was properly populated. - $this->assertMatchesRegularExpression( - '/^\[[^\]]*\] A PHP error occurred while trying to prepare the AMP response\..*- FAILURE \(42\) \[RuntimeException\].*/', - stream_get_contents( $capture ) - ); - - // Reset error log back to initial settings. - ini_set( 'error_log', $backup ); // phpcs:ignore WordPress.PHP.IniSet.Risky - - $this->assertStringContainsString( 'Failed to prepare AMP page', $output ); - } - - /** - * Test prepare_response for responses that throw a fatal error. - * - * @covers AMP_Theme_Support::prepare_response() - * @covers AMP_Theme_Support::render_error_page() - */ - public function test_prepare_response_throwing_error() { - if ( PHP_MAJOR_VERSION < 7 ) { - $this->markTestSkipped( 'Requires PHP 7.' ); - } - - // Set up temporary capture of error log to test error log output. - $capture = tmpfile(); - $backup = ini_set( // phpcs:ignore WordPress.PHP.IniSet.Risky - 'error_log', - stream_get_meta_data( $capture )['uri'] - ); - - add_filter( - 'amp_enable_optimizer', - static function ( $enabled ) { - if ( AMP_Theme_Support::DOES_NOT_EXIST === true ) { // phpcs:ignore - $enabled = true; - } - return $enabled; - } - ); - - wp(); - $output = AMP_Theme_Support::finish_output_buffering( $this->get_original_html() ); - - // Verify that error log was properly populated. - $this->assertMatchesRegularExpression( - '/^\[[^\]]*\] A PHP error occurred while trying to prepare the AMP response\..*- (Undefined class constant \'DOES_NOT_EXIST\'|Undefined constant AMP_Theme_Support::DOES_NOT_EXIST) \(0\) \[Error\].*/', - stream_get_contents( $capture ) - ); - - // Reset error log back to initial settings. - ini_set( 'error_log', $backup ); // phpcs:ignore WordPress.PHP.IniSet.Risky - - $this->assertStringContainsString( 'Failed to prepare AMP page', $output ); - } - - /** - * Test prepare_response will cache redirects when validation errors happen. - * - * @covers AMP_Theme_Support::prepare_response() - */ - public function test_prepare_response_redirect() { - add_filter( 'amp_validation_error_sanitized', '__return_false', 100 ); - - add_theme_support( - AMP_Theme_Support::SLUG, - [ - AMP_Theme_Support::PAIRED_FLAG => true, - ] - ); - $this->go_to( home_url( '/?amp=1' ) ); - add_filter( - 'amp_content_sanitizers', - static function( $sanitizers ) { - $sanitizers[ AMP_Theme_Support_Sanitizer_Counter::class ] = []; - return $sanitizers; - } - ); - AMP_Theme_Support::init(); - AMP_Theme_Support::finish_init(); - $this->assertTrue( amp_is_request() ); - - ob_start(); - ?> - <html> - <head> - <?php wp_head(); ?> - </head> - <body> - <script>bad</script> - </body> - </html> - <?php - $original_html = trim( ob_get_clean() ); - - $redirects = []; - add_filter( - 'wp_redirect', - static function( $url ) use ( &$redirects ) { - array_unshift( $redirects, $url ); - return ''; - } - ); - - AMP_Theme_Support_Sanitizer_Counter::$count = 0; - AMP_Validation_Manager::reset_validation_results(); - $sanitized_html = AMP_Theme_Support::prepare_response( $original_html ); - $this->assertStringStartsWith( 'Redirecting', $sanitized_html ); - $this->assertCount( 1, $redirects ); - $this->assertEquals( add_query_arg( QueryVar::NOAMP, QueryVar::NOAMP_AVAILABLE, home_url( '/' ) ), $redirects[0] ); - $this->assertEquals( 1, AMP_Theme_Support_Sanitizer_Counter::$count ); - - AMP_Validation_Manager::reset_validation_results(); - $sanitized_html = AMP_Theme_Support::prepare_response( $original_html ); - $this->assertStringStartsWith( 'Redirecting', $sanitized_html ); - $this->assertCount( 2, $redirects ); - $this->assertEquals( add_query_arg( QueryVar::NOAMP, QueryVar::NOAMP_AVAILABLE, home_url( '/' ) ), $redirects[0] ); - $this->assertEquals( 2, AMP_Theme_Support_Sanitizer_Counter::$count, 'Expected sanitizer to be invoked again.' ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Validation_Manager::add_validation_error_sourcing(); - - AMP_Validation_Manager::reset_validation_results(); - $sanitized_html = AMP_Theme_Support::prepare_response( $original_html ); - $this->assertStringStartsWith( '<!DOCTYPE html>', $sanitized_html, 'Expected page instead of redirect since admin logged-in.' ); - $this->assertCount( 2, $redirects ); - $this->assertEquals( 3, AMP_Theme_Support_Sanitizer_Counter::$count, 'Expected sanitizer be invoked after validation changed.' ); - - AMP_Validation_Manager::reset_validation_results(); - $sanitized_html = AMP_Theme_Support::prepare_response( $original_html ); - $this->assertStringStartsWith( '<!DOCTYPE html>', $sanitized_html, 'Expected page instead of redirect since admin logged-in.' ); - $this->assertCount( 2, $redirects ); - $this->assertEquals( 4, AMP_Theme_Support_Sanitizer_Counter::$count, 'Expected sanitizer to be invoked again although validation results are cached.' ); - } - - /** - * Test enqueue_assets(). - * - * @covers AMP_Theme_Support::enqueue_assets() - */ - public function test_enqueue_assets() { - $style_slug = 'amp-default'; - wp_dequeue_style( $style_slug ); - AMP_Theme_Support::enqueue_assets(); - $this->assertContains( $style_slug, wp_styles()->queue ); - } - - /** - * Test AMP_Theme_Support::amend_header_image_with_video_header(). - * - * @see AMP_Theme_Support::amend_header_image_with_video_header() - */ - public function test_amend_header_image_with_video_header() { - $mock_image = '<img src="https://example.com/flower.jpeg">'; - - // If there's no theme support for 'custom-header', the callback should simply return the image. - $this->assertEquals( - $mock_image, - AMP_Theme_Support::amend_header_image_with_video_header( $mock_image ) - ); - - // If theme support is present, but there isn't a header video selected, the callback should again return the image. - add_theme_support( - 'custom-header', - [ - 'video' => true, - ] - ); - - // There's a YouTube URL as the header video. - set_theme_mod( 'external_header_video', 'https://www.youtube.com/watch?v=a8NScvBhVnc' ); - $this->assertEquals( - $mock_image . '<amp-youtube media="(min-width: 900px)" width="0" height="0" layout="responsive" autoplay loop id="wp-custom-header-video" data-videoid="a8NScvBhVnc" data-param-rel="0" data-param-showinfo="0" data-param-controls="0" data-param-iv_load_policy="3" data-param-modestbranding="1" data-param-playsinline="1" data-param-disablekb="1" data-param-fs="0"></amp-youtube><style>#wp-custom-header-video .amp-video-eq { display:none; }</style>', - AMP_Theme_Support::amend_header_image_with_video_header( $mock_image ) - ); - } -} - -// phpcs:disable Generic.Files.OneObjectStructurePerFile.MultipleFound - -/** - * Class AMP_Theme_Support_Sanitizer_Counter - */ -class AMP_Theme_Support_Sanitizer_Counter extends AMP_Base_Sanitizer { - - /** - * Count. - * - * @var int - */ - public static $count = 0; - - /** - * "Sanitize". - */ - public function sanitize() { - self::$count++; - } -} diff --git a/tests/php/test-class-amp-tiktok-embed-handler.php b/tests/php/test-class-amp-tiktok-embed-handler.php deleted file mode 100644 index 991948d88c0..00000000000 --- a/tests/php/test-class-amp-tiktok-embed-handler.php +++ /dev/null @@ -1,179 +0,0 @@ -<?php -/** - * Test TikTok embed. - * - * @package AMP. - */ - -use AmpProject\AmpWP\Tests\Helpers\MarkupComparison; -use AmpProject\AmpWP\Tests\Helpers\WithoutBlockPreRendering; -use AmpProject\AmpWP\Tests\TestCase; - -/** - * Class Test_AMP_TikTok_Embed_Handler - */ -class Test_AMP_TikTok_Embed_Handler extends TestCase { - - use MarkupComparison; - - use WithoutBlockPreRendering { - set_up as public prevent_block_pre_render; - } - - /** - * Set up. - */ - public function set_up() { - $this->prevent_block_pre_render(); - - // Mock the HTTP request. - add_filter( 'pre_http_request', [ $this, 'mock_http_request' ], 10, 3 ); - } - - /** - * After a test method runs, reset any state in WordPress the test method might have changed. - */ - public function tear_down() { - remove_filter( 'pre_http_request', [ $this, 'mock_http_request' ] ); - parent::tear_down(); - } - - /** - * Mock HTTP request. - * - * @param mixed $pre Whether to preempt an HTTP request's return value. Default false. - * @param mixed $r HTTP request arguments. - * @param string $url The request URL. - * @return array Response data. - */ - public function mock_http_request( $pre, $r, $url ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $pre; - } - - if ( false === strpos( $url, 'tiktok.com' ) ) { - return $pre; - } - - $body = '{"version":"1.0","type":"video","title":"Scramble up ur name & I’ll try to guess it😍❤️ #foryoupage #petsoftiktok #aesthetic","author_url":"https://www.tiktok.com/@scout2015","author_name":"Scout and Suki","width":"100%","height":"100%","html":"<blockquote class=\"tiktok-embed\" cite=\"https://www.tiktok.com/@scout2015/video/6718335390845095173\" data-video-id=\"6718335390845095173\" style=\"max-width: 605px;min-width: 325px;\" > <section> <a target=\"_blank\" title=\"@scout2015\" href=\"https://www.tiktok.com/@scout2015\">@scout2015</a> <p>Scramble up ur name & I’ll try to guess it😍❤️ <a title=\"foryoupage\" target=\"_blank\" href=\"https://www.tiktok.com/tag/foryoupage\">#foryoupage</a> <a title=\"PetsOfTikTok\" target=\"_blank\" href=\"https://www.tiktok.com/tag/PetsOfTikTok\">#petsoftiktok</a> <a title=\"aesthetic\" target=\"_blank\" href=\"https://www.tiktok.com/tag/aesthetic\">#aesthetic</a></p> <a target=\"_blank\" title=\"♬ original sound - tiff\" href=\"https://www.tiktok.com/music/original-sound-6689804660171082501\">♬ original sound - tiff</a> </section> </blockquote> <script async src=\"https://www.tiktok.com/embed.js\"></script>","thumbnail_width":720,"thumbnail_height":1280,"thumbnail_url":"https://p16-sign-va.tiktokcdn.com/obj/tos-maliva-p-0068/06kv6rfcesljdjr45ukb0000d844090v0200000a05?x-expires=1600473600&x-signature=UYga2liJB%2Bb8auK8ejCI%2FFRLTX0%3D","provider_url":"https://www.tiktok.com","provider_name":"TikTok"}'; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript - - return [ - 'body' => $body, - 'response' => [ - 'code' => 200, - 'message' => 'OK', - ], - ]; - } - - /** - * Get conversion data. - * - * @return array - */ - public function get_conversion_data() { - return [ - 'no_embed' => [ - '<p>Hello world.</p>', - '<p>Hello world.</p>' . PHP_EOL, - ], - - 'url_simple' => [ - 'https://www.tiktok.com/@scout2015/video/6718335390845095173' . PHP_EOL, - - ' - <amp-tiktok layout="fixed-height" height="755" width="auto" data-src="https://www.tiktok.com/@scout2015/video/6718335390845095173"> - <blockquote class="tiktok-embed" cite="https://www.tiktok.com/@scout2015/video/6718335390845095173" data-video-id="6718335390845095173" placeholder> - <section> <a target="_blank" title="@scout2015" href="https://www.tiktok.com/@scout2015">@scout2015</a> - <p>Scramble up ur name & I’ll try to guess it😍❤️ <a title="foryoupage" target="_blank" href="https://www.tiktok.com/tag/foryoupage">#foryoupage</a> <a title="PetsOfTikTok" target="_blank" href="https://www.tiktok.com/tag/PetsOfTikTok">#petsoftiktok</a> <a title="aesthetic" target="_blank" href="https://www.tiktok.com/tag/aesthetic">#aesthetic</a></p> - <p> <a target="_blank" title="♬ original sound - tiff" href="https://www.tiktok.com/music/original-sound-6689804660171082501">♬ original sound – tiff</a> </p></section> - </blockquote> - </amp-tiktok> - ', - ], - - 'tiktok-embed-code-with-wpautop' => [ - ' - <blockquote class="tiktok-embed" cite="https://www.tiktok.com/@countingprimes/video/6988237085899574533" data-video-id="6988237085899574533" style="max-width: 605px;min-width: 325px;" > <section> <a target="_blank" title="@countingprimes" href="https://www.tiktok.com/@countingprimes">@countingprimes</a> <p>You can now embed TikTok\'s in AMP</p> <a target="_blank" title="♬ original sound - countingprimes" href="https://www.tiktok.com/music/original-sound-6988236987325057798">♬ original sound - countingprimes</a> </section> </blockquote> <script async src="https://www.tiktok.com/embed.js"></script> - ', - ' - <amp-tiktok layout="fixed-height" height="719" width="auto" data-src="https://www.tiktok.com/@countingprimes/video/6988237085899574533"> - <blockquote class="tiktok-embed" cite="https://www.tiktok.com/@countingprimes/video/6988237085899574533" data-video-id="6988237085899574533" placeholder> - <section> - <a target="_blank" title="@countingprimes" href="https://www.tiktok.com/@countingprimes">@countingprimes</a> - <p>You can now embed TikTok’s in AMP</p> - <p> <a target="_blank" title="♬ original sound - countingprimes" href="https://www.tiktok.com/music/original-sound-6988236987325057798">♬ original sound – countingprimes</a> </p> - </section> - </blockquote> - </amp-tiktok> - ', - ], - - 'tiktok-embed-code-without-wpautop' => [ - ' - <!-- wp:html --> - <blockquote class="tiktok-embed" cite="https://www.tiktok.com/@countingprimes/video/6988237085899574533" data-video-id="6988237085899574533" style="max-width: 605px;min-width: 325px;" > <section> <a target="_blank" title="@countingprimes" href="https://www.tiktok.com/@countingprimes">@countingprimes</a> <p>You can now embed TikTok\'s in AMP</p> <a target="_blank" title="♬ original sound - countingprimes" href="https://www.tiktok.com/music/original-sound-6988236987325057798">♬ original sound - countingprimes</a> </section> </blockquote> <script async src="https://www.tiktok.com/embed.js"></script> - <!-- /wp:html --> - ', - ' - <amp-tiktok layout="fixed-height" height="719" width="auto" data-src="https://www.tiktok.com/@countingprimes/video/6988237085899574533"> - <blockquote class="tiktok-embed" cite="https://www.tiktok.com/@countingprimes/video/6988237085899574533" data-video-id="6988237085899574533" placeholder> - <section> - <a target="_blank" title="@countingprimes" href="https://www.tiktok.com/@countingprimes">@countingprimes</a> - <p>You can now embed TikTok’s in AMP</p> - <a target="_blank" title="♬ original sound - countingprimes" href="https://www.tiktok.com/music/original-sound-6988236987325057798">♬ original sound – countingprimes</a> - </section> - </blockquote> - </amp-tiktok> - ', - ], - - 'amp-tiktok-passthrough' => [ - ' - <!-- wp:html --> - <amp-tiktok width="300" height="800" layout="intrinsic"> - <blockquote class="tiktok-embed" cite="https://www.tiktok.com/@countingprimes/video/6988237085899574533" data-video-id="6988237085899574533" style="max-width: 605px;min-width: 325px;"> - <section> - <a target="_blank" title="@countingprimes" href="https://www.tiktok.com/@countingprimes">@countingprimes</a> - <p>You can now embed TikTok’s in AMP</p> - <a target="_blank" title="♬ original sound — countingprimes" href="https://www.tiktok.com/music/original-sound-6988236987325057798">♬ original sound — countingprimes</a> - </section> - </blockquote> - </amp-tiktok> - <!-- /wp:html --> - ', - - null, - ], - ]; - } - - /** - * Test conversion. - * - * @param string $source Source. - * @param string $expected Expected. - * @dataProvider get_conversion_data - */ - public function test_conversion( $source, $expected = null ) { - if ( version_compare( '5.4-alpha', get_bloginfo( 'version' ), '>' ) ) { - $this->markTestSkipped( 'The TikTok oEmbed provider is only available in 5.4-alpha and later' ); - } - if ( ! $expected ) { - $expected = $source; - } - - $expected = preg_replace( '/<!--.*?-->/s', '', $expected ); - - $embed = new AMP_TikTok_Embed_Handler(); - $embed->register_embed(); - - $filtered_content = apply_filters( 'the_content', $source ); - $dom = AMP_DOM_Utils::get_dom_from_content( $filtered_content ); - $embed->sanitize_raw_embeds( $dom ); - - $actual = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertSimilarMarkup( $expected, $actual ); - } -} diff --git a/tests/php/test-class-amp-wordpress-tv-embed-handler.php b/tests/php/test-class-amp-wordpress-tv-embed-handler.php deleted file mode 100644 index 8d9e7009998..00000000000 --- a/tests/php/test-class-amp-wordpress-tv-embed-handler.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Tests for AMP_WordPress_TV_Embed_Handler. - * - * @package AMP - * @since 1.4 - */ - -use AmpProject\AmpWP\Tests\Helpers\WithoutBlockPreRendering; -use AmpProject\AmpWP\Tests\TestCase; - -/** - * Tests for AMP_WordPress_TV_Embed_Handler. - * - * @package AMP - * @covers AMP_WordPress_TV_Embed_Handler - */ -class Test_AMP_WordPress_TV_Embed_Handler extends TestCase { - - use WithoutBlockPreRendering { - set_up as public prevent_block_pre_render; - } - - /** - * Set up. - */ - public function set_up() { - $this->prevent_block_pre_render(); - - add_filter( 'pre_http_request', [ $this, 'mock_http_request' ], 10, 3 ); - } - - /** - * Mock HTTP request. - * - * @param mixed $preempt Whether to preempt an HTTP request's return value. Default false. - * @param mixed $r HTTP request arguments. - * @param string $url The request URL. - * @return array Response data. - */ - public function mock_http_request( $preempt, $r, $url ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $preempt; - } - - if ( false === strpos( $url, 'wordpress.tv' ) ) { - return $preempt; - } - unset( $r ); - return [ - 'body' => '{"type":"video","version":"1.0","title":null,"width":500,"height":281,"html":"<iframe width=\'500\' height=\'281\' src=\'https:\\/\\/video.wordpress.com\\/embed\\/yFCmLMGL?hd=0\' frameborder=\'0\' allowfullscreen><\\/iframe><script src=\'https:\\/\\/v0.wordpress.com\\/js\\/next\\/videopress-iframe.js?m=1435166243\'></script>"}', // phpcs:ignore - 'headers' => [], - 'response' => [ - 'code' => 200, - 'message' => 'ok', - ], - 'cookies' => [], - 'http_response' => null, - ]; - } - - /** - * Test that the script tag that VideoPress adds is removed by the sanitizer. - * - * @covers AMP_WordPress_TV_Embed_Handler::filter_oembed_html() - */ - public function test_script_removal() { - $handler = new AMP_WordPress_TV_Embed_Handler(); - $handler->unregister_embed(); // Make sure we are on the initial clean state. - - $wordpress_tv_block = ' - <!-- wp:core-embed/wordpress-tv {"url":"https://wordpress.tv/2019/10/08/the-history-of-wordpress-in-four-minutes/","type":"video","providerNameSlug":"","className":"wp-embed-aspect-16-9 wp-has-aspect-ratio"} --> - <figure class="wp-block-embed-wordpress-tv wp-block-embed is-type-video wp-embed-aspect-16-9 wp-has-aspect-ratio"> - <div class="wp-block-embed__wrapper"> - https://wordpress.tv/2019/10/08/the-history-of-wordpress-in-four-minutes/ - </div> - </figure> - <!-- /wp:core-embed/wordpress-tv --> - '; - - $handler->register_embed(); - $rendered = apply_filters( 'the_content', $wordpress_tv_block ); - $this->assertStringContainsString( '<iframe', $rendered ); - $this->assertStringContainsString( 'video.wordpress.com/embed', $rendered ); - $this->assertStringNotContainsString( '<script', $rendered ); - } - - /** - * Gets the test data for test_filter_oembed_html(). - * - * @return array The test data. - */ - public function get_filter_oembed_data() { - $embed_without_script = '<p>Example Embed</p>'; - $embed_with_script = $embed_without_script . '<script>doThis();</script>'; - - return [ - 'wrong_embed_url_domain' => [ - $embed_without_script, - 'https://incorrect.com', - null, - ], - 'wrong_embed_url_wordpress_com' => [ - $embed_without_script, - 'https://wordpress.com/123', - null, - ], - 'wrong_embed_url_no_protocol' => [ - $embed_without_script, - '//wordpress.tv/', - null, - ], - 'correct_embed_url_http' => [ - $embed_with_script, - 'https://wordpress.tv/123', - $embed_without_script, - ], - 'correct_embed_url_https' => [ - $embed_with_script, - 'https://wordpress.tv/123', - $embed_without_script, - ], - 'correct_embed_url_no_script' => [ - $embed_without_script, - 'https://wordpress.tv/123', - null, - ], - 'correct_embed_url_text_script_not_tag' => [ - 'This is the script for the play', - 'https://wordpress.tv/123', - null, - ], - ]; - } - - /** - * Test filter_oembed_html - * - * @dataProvider get_filter_oembed_data - * @covers AMP_WordPress_TV_Embed_Handler::filter_oembed_html() - * - * @param mixed $cache The cached markup. - * @param string $url The URL of the embed. - * @param string $expected The expected return value. - */ - public function test_filter_oembed_html( $cache, $url, $expected ) { - if ( null === $expected ) { - $expected = $cache; - } - - $handler = new AMP_WordPress_TV_Embed_Handler(); - $this->assertEquals( - $expected, - $handler->filter_oembed_html( $cache, $url ) - ); - - } -} diff --git a/tests/php/test-class-amp-youtube-embed-handler.php b/tests/php/test-class-amp-youtube-embed-handler.php deleted file mode 100644 index 203c6e980dd..00000000000 --- a/tests/php/test-class-amp-youtube-embed-handler.php +++ /dev/null @@ -1,541 +0,0 @@ -<?php -/** - * Tests for AMP_YouTube_Embed_Handler. - * - * @package AMP - * @since 0.7 - */ - -use AmpProject\AmpWP\Tests\Helpers\MarkupComparison; -use AmpProject\AmpWP\Tests\Helpers\PrivateAccess; -use AmpProject\AmpWP\Tests\Helpers\WithoutBlockPreRendering; -use AmpProject\AmpWP\Tests\TestCase; - -/** - * Tests for AMP_YouTube_Embed_Handler. - * - * @coversDefaultClass \AMP_YouTube_Embed_Handler - */ -class Test_AMP_YouTube_Embed_Handler extends TestCase { - - use MarkupComparison; - use PrivateAccess; - use WithoutBlockPreRendering { - set_up as public prevent_block_pre_render; - } - - protected $youtube_video_id = 'kfVsfOSbJY0'; - - /** - * Response for YouTube oEmbed request. - * - * @see Test_AMP_YouTube_Embed_Handler::$youtube_video_id - * @var string - */ - protected $youtube_oembed_response = '{"height":281,"type":"video","author_name":"rebecca","thumbnail_url":"https:\/\/i.ytimg.com\/vi\/kfVsfOSbJY0\/hqdefault.jpg","provider_url":"https:\/\/www.youtube.com\/","title":"Rebecca Black - Friday","version":"1.0","width":500,"thumbnail_height":360,"html":"\u003ciframe width=\"500\" height=\"281\" src=\"https:\/\/www.youtube.com\/embed\/kfVsfOSbJY0?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen\u003e\u003c\/iframe\u003e","thumbnail_width":500,"provider_name":"YouTube","author_url":"https:\/\/www.youtube.com\/user\/rebecca"}'; - - /** - * An instance of this embed handler. - * - * @var AMP_YouTube_Embed_Handler - */ - public $handler; - - /** - * Set up each test. - */ - public function set_up() { - $this->prevent_block_pre_render(); - - $this->handler = new AMP_YouTube_Embed_Handler(); - - add_filter( 'pre_http_request', [ $this, 'mock_http_request' ], 10, 3 ); - } - - /** - * After a test method runs, reset any state in WordPress the test method might have changed. - */ - public function tear_down() { - remove_filter( 'pre_http_request', [ $this, 'mock_http_request' ] ); - parent::tear_down(); - } - - /** - * Mock HTTP request. - * - * @param mixed $preempt Whether to preempt an HTTP request's return value. Default false. - * @param mixed $r HTTP request arguments. - * @param string $url The request URL. - * @return array Response data. - */ - public function mock_http_request( $preempt, $r, $url ) { - if ( in_array( 'external-http', $_SERVER['argv'], true ) ) { - return $preempt; - } - - $host = wp_parse_url( $url, PHP_URL_HOST ); - - if ( ! in_array( $host, [ 'youtu.be', 'youtube.com', 'www.youtube.com' ], true ) ) { - return $preempt; - } - - /** - * The URL http://www.youtube.com/watch?v=kfVsfOSbJY0?hl=en&fs=1&w=425&h=349 is invalid as - * it has multiple query vars. Checking if `?v=kfVsfOSbJY0?hl=en` is in the URL should be a - * sufficient check when that URL is being mocked. - */ - if ( false !== strpos( $url, '%3Fv%3DkfVsfOSbJY0%3Fhl%3Den' ) ) { - return [ - 'body' => 'Bad Request', - 'response' => [ - 'code' => 400, - 'message' => 'Bad Request', - ], - ]; - } - - unset( $r ); - - return [ - 'body' => $this->youtube_oembed_response, - 'headers' => [], - 'response' => [ - 'code' => 200, - 'message' => 'ok', - ], - 'cookies' => [], - 'http_response' => null, - ]; - } - - /** - * @covers ::register_embed() - * @covers ::unregister_embed() - */ - public function test_register_and_unregister_embed() { - $embed = new AMP_YouTube_Embed_Handler(); - $embed->register_embed(); - $this->assertEquals( 10, has_filter( 'embed_oembed_html', [ $embed, 'filter_embed_oembed_html' ] ) ); - $this->assertEquals( PHP_INT_MAX, has_filter( 'wp_video_shortcode_override', [ $embed, 'video_override' ] ) ); - $embed->unregister_embed(); - $this->assertFalse( has_filter( 'embed_oembed_html', [ $embed, 'filter_embed_oembed_html' ] ) ); - $this->assertFalse( has_filter( 'wp_video_shortcode_override', [ $embed, 'video_override' ] ) ); - } - - /** - * Data provider for $this->test_sanitize_raw_embeds() - * - * @return string[][] - */ - public function sanitize_raw_embeds_data_provider() { - - return [ - 'youtube-embed' => [ - 'source' => '<iframe src="https://www.youtube.com/embed/q4xKvHANqjk?controls=0&autoplay=1&loop=1&modestbranding=1" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - 'expected' => '<amp-youtube layout="responsive" width="560" height="315" data-videoid="q4xKvHANqjk" data-param-controls="0" autoplay="1" loop="1" data-param-modestbranding="1" title="YouTube video player"><a placeholder="" href="https://www.youtube.com/watch?v=q4xKvHANqjk"><img src="https://i.ytimg.com/vi/q4xKvHANqjk/hqdefault.jpg" layout="fill" object-fit="cover" alt="YouTube video player"></a></amp-youtube>', - ], - 'youtube-start' => [ - 'source' => '<iframe src="https://www.youtube.com/embed/q4xKvHANqjk?controls=0&autoplay=1&loop=1&modestbranding=1&start=84" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - 'expected' => '<amp-youtube layout="responsive" width="560" height="315" data-videoid="q4xKvHANqjk" data-param-start="84" data-param-controls="0" autoplay="1" loop="1" data-param-modestbranding="1" title="YouTube video player"><a placeholder="" href="https://www.youtube.com/watch?v=q4xKvHANqjk#t=84"><img src="https://i.ytimg.com/vi/q4xKvHANqjk/hqdefault.jpg" layout="fill" object-fit="cover" alt="YouTube video player"></a></amp-youtube>', - ], - 'with_http' => [ - 'source' => '<iframe src="http://www.youtube.com/embed/q4xKvHANqjk?controls=0&autoplay=1&loop=1&modestbranding=1" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - 'expected' => '<amp-youtube layout="responsive" width="560" height="315" data-videoid="q4xKvHANqjk" data-param-controls="0" autoplay="1" loop="1" data-param-modestbranding="1" title="YouTube video player"><a placeholder="" href="https://www.youtube.com/watch?v=q4xKvHANqjk"><img src="https://i.ytimg.com/vi/q4xKvHANqjk/hqdefault.jpg" layout="fill" object-fit="cover" alt="YouTube video player"></a></amp-youtube>', - ], - 'short-url' => [ - 'source' => '<iframe src="https://youtu.be/kfVsfOSbJY0?controls=0&autoplay=1&loop=1&modestbranding=1" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - 'expected' => '<amp-youtube layout="responsive" width="560" height="315" data-videoid="kfVsfOSbJY0" data-param-controls="0" autoplay="1" loop="1" data-param-modestbranding="1" title="YouTube video player"><a placeholder="" href="https://www.youtube.com/watch?v=kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="YouTube video player"></a></amp-youtube>', - ], - 'live_streaming_channel' => [ - 'source' => '<iframe src="https://www.youtube.com/embed/live_stream?channel=UCkaNo2FUEWips2z4BkOHl6Q" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - 'expected' => '<amp-youtube layout="responsive" width="560" height="315" data-live-channelid="UCkaNo2FUEWips2z4BkOHl6Q" title="YouTube video player"></amp-youtube>', - ], - 'none-youtube' => [ - 'source' => '<iframe src="https://mysite.com/blog/youtube-iz-da-best" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - 'expected' => '<iframe src="https://mysite.com/blog/youtube-iz-da-best" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" width="560" height="315" frameborder="0"></iframe>', - ], - 'youtube-unknown' => [ - 'source' => '<iframe src="https://www.youtube.com/feed/library" title="YouTube Library" width="560" height="315"></iframe>', - 'expected' => '<iframe src="https://www.youtube.com/feed/library" title="YouTube Library" width="560" height="315"></iframe>', - ], - 'youtube-fixed-height' => [ - 'source' => '<iframe width="100%" height="315" src="https://www.youtube.com/embed/s52JNMT59s8"></iframe>', - 'expected' => '<amp-youtube layout="fixed-height" width="auto" height="315" data-videoid="s52JNMT59s8"><a placeholder="" href="https://www.youtube.com/watch?v=s52JNMT59s8"><img src="https://i.ytimg.com/vi/s52JNMT59s8/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube>', - ], - ]; - } - - /** - * @dataProvider sanitize_raw_embeds_data_provider - * - * @covers ::sanitize_raw_embeds() - * @covers ::get_amp_component() - * @covers ::get_placeholder_element() - * @covers ::prepare_attributes() - * @covers ::amend_fixed_height_layout() - */ - public function test_sanitize_raw_embeds( $source, $expected ) { - - $embed = new AMP_YouTube_Embed_Handler(); - $embed->register_embed(); - - $dom = AMP_DOM_Utils::get_dom_from_content( $source ); - $embed->sanitize_raw_embeds( $dom ); - - $layout_sanitizer = new AMP_Layout_Sanitizer( $dom ); - $layout_sanitizer->sanitize(); - - $content = AMP_DOM_Utils::get_content_from_dom( $dom ); - - $this->assertEqualMarkup( $expected, $content ); - } - - /** - * Test video_override(). - * - * @covers ::register_embed() - * @covers ::video_override() - * @covers ::render() - * @covers ::get_placeholder_markup() - * @covers ::amend_fixed_height_layout() - */ - public function test_video_override() { - remove_all_filters( 'wp_video_shortcode_override' ); - $this->handler->register_embed(); - $youtube_id = 'XOY3ZUO6P0k'; - $youtube_src = 'https://youtu.be/' . $youtube_id; - $attr_youtube = [ - 'src' => $youtube_src, - ]; - - $youtube_shortcode = $this->handler->video_override( '', $attr_youtube ); - $this->assertEqualMarkup( - '<amp-youtube layout="responsive" width="600" height="338" data-videoid="XOY3ZUO6P0k"><a placeholder href="https://youtu.be/XOY3ZUO6P0k"><img src="https://i.ytimg.com/vi/XOY3ZUO6P0k/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube>', - $youtube_shortcode - ); - - // Test when wp_video_shortcode_override filter has already overridden the markup. - $youtube_shortcode = $this->handler->video_override( "<iframe width=\"200\" height=\"100\" src=\"$youtube_src\"></iframe>", $attr_youtube ); - $this->assertEqualMarkup( - '<amp-youtube layout="responsive" width="200" height="100" data-videoid="XOY3ZUO6P0k"><a placeholder href="https://youtu.be/XOY3ZUO6P0k"><img src="https://i.ytimg.com/vi/XOY3ZUO6P0k/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube>', - $youtube_shortcode - ); - - // Test 100% width in video shortcode. - $youtube_shortcode = $this->handler->video_override( - '', - array_merge( - $attr_youtube, - [ - 'width' => '100%', - 'height' => '315', - ] - ) - ); - $this->assertEqualMarkup( - '<amp-youtube layout="fixed-height" width="auto" height="315" data-videoid="XOY3ZUO6P0k"><a placeholder href="https://youtu.be/XOY3ZUO6P0k"><img src="https://i.ytimg.com/vi/XOY3ZUO6P0k/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube>', - $youtube_shortcode - ); - - $vimeo_id = '64086087'; - $vimeo_src = 'https://vimeo.com/' . $vimeo_id; - $attr_vimeo = [ - 'src' => $vimeo_src, - ]; - $vimeo_shortcode = $this->handler->video_override( '', $attr_vimeo ); - $this->assertEquals( '', $vimeo_shortcode ); - - $daily_motion_id = 'x6bacgf'; - $daily_motion_src = 'http://www.dailymotion.com/video/' . $daily_motion_id; - $attr_daily_motion = [ - 'src' => $daily_motion_src, - ]; - $daily_motion_shortcode = $this->handler->video_override( '', $attr_daily_motion ); - $this->assertEquals( '', $daily_motion_shortcode ); - $no_attributes = $this->handler->video_override( '', [] ); - $this->assertEquals( '', $no_attributes ); - remove_all_filters( 'wp_video_shortcode_override' ); - } - - /** @return array */ - public function get_conversion_data() { - return [ - 'no_embed' => [ - '<p>Hello world.</p>', - '<p>Hello world.</p>' . PHP_EOL, - ], - - 'url_simple' => [ - 'https://www.youtube.com/watch?v=kfVsfOSbJY0' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" title="Rebecca Black - Friday"><a placeholder href="https://www.youtube.com/watch?v=kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0"><a placeholder href="https://www.youtube.com/watch?v=kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'url_short' => [ - 'https://youtu.be/kfVsfOSbJY0' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" title="Rebecca Black - Friday"><a placeholder href="https://youtu.be/kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0"><a placeholder href="https://youtu.be/kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'url_with_querystring' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0&hl=en&fs=1&w=425&h=349' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-hl="en" data-param-fs="1" title="Rebecca Black - Friday"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0&hl=en&fs=1&w=425&h=349"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-hl="en" data-param-fs="1"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0&hl=en&fs=1&w=425&h=349"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - // Several reports of invalid URLs that have multiple `?` in the URL. - 'url_with_querystring_and_extra_?' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0?hl=en&fs=1&w=425&h=349' . PHP_EOL, - '<p>http://www.youtube.com/watch?v=kfVsfOSbJY0?hl=en&fs=1&w=425&h=349</p>' . PHP_EOL, - ], - - 'embed_url' => [ - 'https://www.youtube.com/embed/kfVsfOSbJY0' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" title="Rebecca Black - Friday"><a placeholder href="https://youtube.com/watch?v=kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0"><a placeholder href="https://youtube.com/watch?v=kfVsfOSbJY0"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'with_start_time' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m10s' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="70" title="Rebecca Black - Friday"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m10s"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="70"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m10s"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'with_start_time_2' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0#t=62' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="62" title="Rebecca Black - Friday"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=62"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="62"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=62"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'with_start_time_3' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0#t=62s' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="62" title="Rebecca Black - Friday"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=62s"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="62"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=62s"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'with_start_time_4' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="60" title="Rebecca Black - Friday"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="60"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - - 'with_start_time_5' => [ - 'http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m2' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="62" title="Rebecca Black - Friday"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m2"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover" alt="Rebecca Black - Friday"></a></amp-youtube></p>' . PHP_EOL, - '<p><amp-youtube layout="responsive" width="500" height="281" data-videoid="kfVsfOSbJY0" data-param-start="62"><a placeholder href="http://www.youtube.com/watch?v=kfVsfOSbJY0#t=1m2"><img src="https://i.ytimg.com/vi/kfVsfOSbJY0/hqdefault.jpg" layout="fill" object-fit="cover"></a></amp-youtube></p>' . PHP_EOL, - ], - ]; - } - - /** - * @dataProvider get_conversion_data - * @covers ::register_embed() - * @covers ::filter_embed_oembed_html() - * @covers ::render() - * @covers ::get_placeholder_markup() - */ - public function test__conversion( $source, $expected, $fallback_for_expected = null ) { - $this->handler->register_embed(); - - // Make actual output consistent between WP 5.4 and 5.5. - add_filter( 'wp_lazy_loading_enabled', '__return_false' ); - - $filtered_content = apply_filters( 'the_content', $source ); - - if ( - version_compare( strtok( get_bloginfo( 'version' ), '-' ), '5.1', '<' ) - && null !== $fallback_for_expected - ) { - $this->assertEqualMarkup( $fallback_for_expected, $filtered_content ); - } else { - $this->assertEqualMarkup( $expected, $filtered_content ); - } - } - - /** - * Gets the test data for test_get_video_id_from_url(). - * - * @return array The test data. - */ - public function get_video_id_data() { - return [ - 'basic_url' => [ - 'https://www.youtube.com/watch?v=XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'mobile_url' => [ - 'https://m.youtube.com/watch?v=XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'short_url' => [ - 'https://youtu.be/XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'url_with_underscore' => [ - 'https://www.youtube.com/watch?v=CMrv_D78oxY', - 'CMrv_D78oxY', - ], - 'short_url_with_underscore' => [ - 'https://youtu.be/CMrv_D78oxY', - 'CMrv_D78oxY', - ], - 'url_with_hyphen' => [ - 'https://www.youtube.com/watch?v=xo68-iWaKv8', - 'xo68-iWaKv8', - ], - 'url_with_hyphen_and_query_string' => [ - 'https://www.youtube.com/watch?v=xo68-iWaKv8&w=800&h=400', - 'xo68-iWaKv8', - ], - 'url_with_hyphen_and_query_string_dimensions_before_id' => [ - 'https://www.youtube.com/watch?w=800&h=400&v=xo68-iWaKv8', - 'xo68-iWaKv8', - ], - 'embed_url' => [ - 'http://www.youtube.com/embed/XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'embed_url_ending_in_query_param' => [ - 'http://www.youtube.com/embed/XOY3ZUO6P0k?rel=0', - 'XOY3ZUO6P0k', - ], - 'v_segment_url' => [ - 'http://youtube.com/v/XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'e_segment_url' => [ - 'http://youtube.com/e/XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'vi_segment_url' => [ - 'http://youtube.com/vi/XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'vi_query_param_url' => [ - 'http://youtube.com/?vi=XOY3ZUO6P0k', - 'XOY3ZUO6P0k', - ], - 'nocookie_url' => [ - '//www.youtube-nocookie.com/embed/XOY3ZUO6P0k?rel=0', - 'XOY3ZUO6P0k', - ], - 'account_url' => [ - 'https://www.youtube.com/account', - false, - ], - 'account_url_followed_by_segment' => [ - 'https://www.youtube.com/account/johnsmith', - false, - ], - 'playlist_url' => [ - 'https://www.youtube.com/playlist?list=PLCra4VPr-3frJzAd-lVYo3-34wu0Eax_u', - false, - ], - 'false_because_no_id' => [ - 'http://youtube.com/?wrong=XOY3ZUO6P0k', - false, - ], - 'live_streaming_channel' => [ - 'https://www.youtube.com/embed/live_stream?channel=UCkaNo2FUEWips2z4BkOHl6Q', - false, - ], - ]; - } - - /** - * Tests get_video_id_from_url. - * - * @dataProvider get_video_id_data - * @covers ::get_video_id_from_url() - * - * @param string $url The URL to test. - * @param string|false $expected The expected result. - * @throws ReflectionException If a reflection of the object is not possible. - */ - public function test_get_video_id_from_url( $url, $expected ) { - $this->assertEquals( - $expected, - $this->call_private_method( $this->handler, 'get_video_id_from_url', [ $url ] ) - ); - } - - /** - * Gets the test data for test_get_start_time_from_url(). - * - * @return array The test data. - */ - public function get_start_time_data() { - - return [ - 'empty_because_no_start_data' => [ - 'http://youtube.com/?wrong=XOY3ZUO6P0k', - 0, - ], - 'data_in_query_string' => [ - 'http://www.youtube.com/watch?v=0zM3nApSvMg&start=90', - 90, - ], - 'data_in_fragment' => [ - 'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s', - 10, - ], - 'data_in_fragment_with_minutes' => [ - 'http://www.youtube.com/watch?v=0zM3nApSvMg#t=1m10s', - 70, - ], - ]; - } - - /** - * Tests get_start_time_from_url. - * - * @dataProvider get_start_time_data - * @covers ::get_start_time_from_url() - * - * @param string $url The URL to test. - * @param string|false $expected The expected result. - * - * @throws ReflectionException If a reflection of the object is not possible. - */ - public function test_get_start_time_from_url( $url, $expected ) { - - $this->assertEquals( - $expected, - $this->call_private_method( $this->handler, 'get_start_time_from_url', [ $url ] ) - ); - } - - /** @return array */ - public function get_scripts_data() { - return [ - 'not_converted' => [ - '<p>Hello World.</p>', - [], - ], - 'converted' => [ - 'https://www.youtube.com/watch?v=kfVsfOSbJY0' . PHP_EOL, - [ 'amp-youtube' => true ], - ], - ]; - } - - /** - * @dataProvider get_scripts_data - * @covers ::register_embed() - * @covers ::get_scripts() - */ - public function test__get_scripts( $source, $expected ) { - $this->handler->register_embed(); - $source = apply_filters( 'the_content', $source ); - - $validating_sanitizer = new AMP_Tag_And_Attribute_Sanitizer( AMP_DOM_Utils::get_dom_from_content( $source ) ); - $validating_sanitizer->sanitize(); - - $scripts = array_merge( - $this->handler->get_scripts(), - $validating_sanitizer->get_scripts() - ); - - $this->assertEquals( $expected, $scripts ); - } -} diff --git a/tests/php/test-dom-element-list.php b/tests/php/test-dom-element-list.php deleted file mode 100644 index d0e8e6888d7..00000000000 --- a/tests/php/test-dom-element-list.php +++ /dev/null @@ -1,119 +0,0 @@ -<?php -/** - * Tests for ElementList and CaptionedSlide classes. - * - * @package AMP - */ - -use AmpProject\Dom\Document; -use AmpProject\AmpWP\Dom\ElementList; -use AmpProject\AmpWP\Component\CaptionedSlide; -use AmpProject\AmpWP\Tests\TestCase; - -/** - * Tests for AMP carousel and slide classes. - * - * @covers AmpProject\AmpWP\Dom\ElementList - * @covers AmpProject\AmpWP\Component\CaptionedSlide - */ -class Test_DOM_Element_List extends TestCase { - - /** - * Gets the data to test adding images. - * - * @return array[] An associative array, including the images and the expected count. - */ - public function get_dom_element_list_data() { - $dom = new Document(); - return [ - 'no_image' => [ - [], - 0, - ], - '1_image' => [ - [ AMP_DOM_Utils::create_node( $dom, 'amp-img', [] ) ], - 1, - ], - '4_images' => [ - [ - AMP_DOM_Utils::create_node( $dom, 'amp-img', [] ), - AMP_DOM_Utils::create_node( $dom, 'amp-img', [] ), - AMP_DOM_Utils::create_node( $dom, 'amp-img', [] ), - AMP_DOM_Utils::create_node( $dom, 'amp-img', [] ), - ], - 4, - ], - ]; - } - - /** - * Test adding images and counting them. - * - * @dataProvider get_dom_element_list_data - * @covers AmpProject\AmpWP\Dom\ElementList::add() - * @covers AmpProject\AmpWP\Dom\ElementList::count() - * - * @param DOMElement[] $images The images to add. - * @param string $expected_count The expected count after adding the images. - */ - public function test_dom_element_list_add( $images, $expected_count ) { - $dom_element_list = new ElementList(); - foreach ( $images as $image ) { - $dom_element_list = $dom_element_list->add( $image, null ); - } - - $this->assertEquals( $expected_count, $dom_element_list->count() ); - } - - /** - * Test the iteration of the images. - * - * @dataProvider get_dom_element_list_data - * @covers AmpProject\AmpWP\Dom\ElementList::add() - * @covers AmpProject\AmpWP\Dom\ElementList::getIterator() - * - * @param DOMElement[] $images The images to add. - * @param string $expected_count The expected count after adding the images. - */ - public function test_dom_element_list_get_iterator( $images, $expected_count ) { - $dom_element_list = new ElementList(); - foreach ( $images as $image ) { - $dom_element_list = $dom_element_list->add( $image ); - } - - $iteration_count = 0; - foreach ( $dom_element_list as $dom_element_list_image ) { - unset( $dom_element_list_image ); - $iteration_count++; - } - - $this->assertEquals( $expected_count, $iteration_count ); - } - - /** - * Test get_caption. - * - * @covers \AmpProject\AmpWP\Component\CaptionedSlide::get_caption_element() - */ - public function test_get_caption() { - $dom = new Document(); - - $image_node = AMP_DOM_Utils::create_node( $dom, 'amp-img', [] ); - $caption_element = AMP_DOM_Utils::create_node( $dom, 'span', [] ); - $caption_element->appendChild( new DOMText( 'This is a caption' ) ); - - $captioned_image = new CaptionedSlide( $image_node, $caption_element ); - $this->assertEquals( $caption_element, $captioned_image->get_caption_element() ); - } - - /** - * Test get_slide_element. - * - * @covers \AmpProject\AmpWP\Component\CaptionedSlide::get_slide_element() - */ - public function test_get_slide_element() { - $image_node = AMP_DOM_Utils::create_node( new Document(), 'amp-img', [] ); - $amp_image = new CaptionedSlide( $image_node, new DOMElement( 'foo' ) ); - $this->assertEquals( $image_node, $amp_image->get_slide_element() ); - } -} diff --git a/tests/php/test-includes-admin-functions.php b/tests/php/test-includes-admin-functions.php deleted file mode 100644 index 9a358f9328e..00000000000 --- a/tests/php/test-includes-admin-functions.php +++ /dev/null @@ -1,251 +0,0 @@ -<?php -/** - * Test admin include functions in includes/admin/functions.php - * - * @package AMP - */ - -use AmpProject\AmpWP\Admin\ReaderThemes; -use AmpProject\AmpWP\Option; -use AmpProject\AmpWP\Tests\Helpers\LoadsCoreThemes; -use AmpProject\AmpWP\Tests\TestCase; - -/** - * Class Test_AMP_Admin_Includes_Functions - */ -class Test_AMP_Admin_Includes_Functions extends TestCase { - - use LoadsCoreThemes; - - public function set_up() { - parent::set_up(); - remove_all_actions( 'amp_init' ); - remove_all_actions( 'admin_menu' ); - remove_all_actions( 'customize_register' ); - - $this->register_core_themes(); - } - - public function tear_down() { - $this->restore_theme_directories(); - - unset( - $GLOBALS['submenu'], - $GLOBALS['menu'] - ); - - parent::tear_down(); - } - - /** @covers ::amp_init_customizer() */ - public function test_amp_init_customizer_legacy_reader() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::READER_THEME, ReaderThemes::DEFAULT_READER_THEME ); - amp_init_customizer(); - $this->assertTrue( amp_is_legacy() ); - $this->assertEquals( 500, has_action( 'customize_register', [ AMP_Template_Customizer::class, 'init' ] ) ); - $this->assertEquals( 10, has_action( 'amp_init', [ AMP_Customizer_Design_Settings::class, 'init' ] ) ); - $this->assertEquals( 10, has_action( 'admin_menu', 'amp_add_customizer_link' ) ); - } - - /** @covers ::amp_init_customizer() */ - public function test_amp_init_customizer_modern_reader() { - switch_theme( 'twentytwenty' ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::READER_THEME, 'twentyseventeen' ); - $this->assertFalse( amp_is_legacy() ); - amp_init_customizer(); - $this->assertEquals( 500, has_action( 'customize_register', [ 'AMP_Template_Customizer', 'init' ] ) ); - $this->assertFalse( has_action( 'amp_init', [ 'AMP_Customizer_Design_Settings', 'init' ] ) ); - $this->assertEquals( 10, has_action( 'admin_menu', 'amp_add_customizer_link' ) ); - } - - /** @covers ::amp_init_customizer() */ - public function test_amp_init_customizer_canonical() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - amp_init_customizer(); - $this->assertTrue( amp_is_canonical() ); - $this->assertFalse( amp_is_legacy() ); - $this->assertEquals( 500, has_action( 'customize_register', [ 'AMP_Template_Customizer', 'init' ] ) ); - $this->assertFalse( has_action( 'amp_init', [ 'AMP_Customizer_Design_Settings', 'init' ] ) ); - $this->assertFalse( has_action( 'admin_menu', 'amp_add_customizer_link' ) ); - } - - /** @covers ::amp_admin_get_preview_permalink() */ - public function test_amp_admin_get_preview_permalink() { - // No posts exist yet. - $this->assertNull( amp_admin_get_preview_permalink() ); - - $page_id = self::factory()->post->create( - [ - 'post_type' => 'page', - 'post_date' => '2020-01-01', - ] - ); - $post_id = self::factory()->post->create( - [ - 'post_type' => 'post', - 'post_date' => '2021-01-01', - ] - ); - - // Default case. - $this->assertEquals( amp_get_permalink( $post_id ), amp_admin_get_preview_permalink() ); - - // Only get a page if it is the only supported post type. - AMP_Options_Manager::update_option( Option::SUPPORTED_POST_TYPES, [ 'page' ] ); - add_filter( - 'amp_customizer_post_type', - static function () { - return 'page'; - } - ); - $this->assertEquals( amp_get_permalink( $page_id ), amp_admin_get_preview_permalink() ); - - // Nothing returned if supported post types exist. - AMP_Options_Manager::update_option( Option::SUPPORTED_POST_TYPES, [ 'book' ] ); - $this->assertNull( amp_admin_get_preview_permalink() ); - - // If is_singular is not a supported template, then no URL will be returned (currently). - AMP_Options_Manager::update_options( - [ - Option::THEME_SUPPORT => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - Option::SUPPORTED_POST_TYPES => [ 'post', 'page' ], - Option::SUPPORTED_TEMPLATES => [ 'is_archive' ], - Option::ALL_TEMPLATES_SUPPORTED => false, - ] - ); - $this->assertNull( amp_admin_get_preview_permalink() ); - } - - /** @return array */ - public function get_data_for_test_amp_get_customizer_url() { - return [ - 'legacy_reader' => [ - 'options' => [ - Option::THEME_SUPPORT => AMP_Theme_Support::READER_MODE_SLUG, - Option::READER_THEME => ReaderThemes::DEFAULT_READER_THEME, - ], - 'assert' => function () { - $this->assertTrue( amp_is_legacy() ); - $this->assertEquals( 'customize.php?amp_preview=1&autofocus[panel]=amp_panel', amp_get_customizer_url() ); - - add_filter( 'amp_customizer_is_enabled', '__return_false' ); - $this->assertEquals( '', amp_get_customizer_url() ); - }, - ], - 'reader_theme' => [ - 'options' => function () { - $theme = current( - array_filter( - wp_get_themes(), - static function ( WP_Theme $theme ) { - return 0 === strpos( $theme->get_stylesheet(), 'twenty' ); - } - ) - ); - if ( ! $theme instanceof WP_Theme ) { - $this->markTestSkipped( 'Lacking theme being installed.' ); - } - - return [ - Option::THEME_SUPPORT => AMP_Theme_Support::READER_MODE_SLUG, - Option::READER_THEME => $theme->get_stylesheet(), - ]; - }, - 'assert' => function () { - $this->assertFalse( amp_is_legacy() ); - $this->assertEquals( 'customize.php?amp_preview=1&=1', amp_get_customizer_url() ); - }, - ], - 'transitional' => [ - 'options' => [ - Option::THEME_SUPPORT => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - ], - 'assert' => function () { - $this->assertEquals( '', amp_get_customizer_url() ); - }, - ], - ]; - } - - /** - * @dataProvider get_data_for_test_amp_get_customizer_url - * @covers ::amp_get_customizer_url() - * - * @param array|Closure $options Options or callback to get the options. - * @param Closure $assert Assert. - */ - public function test_amp_get_customizer_url( $options, $assert ) { - if ( $options instanceof Closure ) { - $options = $options(); - } - AMP_Options_Manager::update_options( $options ); - $assert(); - } - - /** @covers ::amp_add_customizer_link() */ - public function test_amp_add_customizer_link_legacy() { - global $submenu; - $submenu = []; - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - $this->assertTrue( amp_is_legacy() ); - amp_add_customizer_link(); - - $this->assertArrayHasKey( 'themes.php', $submenu ); - $this->assertEquals( 'AMP', $submenu['themes.php'][0][0] ); - } - - /** @covers ::amp_add_customizer_link() */ - public function test_amp_add_customizer_link_legacy_disabled() { - global $submenu; - $submenu = []; - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - $this->assertTrue( amp_is_legacy() ); - add_filter( 'amp_customizer_is_enabled', '__return_false' ); - amp_add_customizer_link(); - - $this->assertEmpty( $submenu ); - } - - /** @covers ::amp_add_customizer_link() */ - public function test_amp_add_customizer_link_reader_theme() { - global $submenu; - $submenu = []; - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::READER_THEME, 'twentyseventeen' ); - $this->assertFalse( amp_is_legacy() ); - add_filter( 'amp_customizer_is_enabled', '__return_false' ); // This will be ignored. - amp_add_customizer_link(); - - $this->assertArrayHasKey( 'themes.php', $submenu ); - $this->assertEquals( 'AMP', $submenu['themes.php'][0][0] ); - $this->assertEquals( 'customize.php?amp_preview=1&=1', $submenu['themes.php'][0][2] ); - } - - /** @covers ::amp_editor_core_blocks() */ - public function test_amp_editor_core_blocks() { - if ( ! function_exists( 'register_block_type' ) ) { - $this->markTestSkipped( 'Requires block editor.' ); - } - - remove_all_filters( 'wp_kses_allowed_html' ); - amp_editor_core_blocks(); - $this->assertTrue( has_filter( 'wp_kses_allowed_html' ) ); - } - - /** @covers ::amp_bootstrap_admin() */ - public function test_amp_bootstrap_admin() { - remove_all_actions( 'admin_enqueue_scripts' ); - remove_all_actions( 'post_submitbox_misc_actions' ); - amp_bootstrap_admin(); - $this->assertTrue( has_action( 'admin_enqueue_scripts' ) ); - $this->assertTrue( has_action( 'post_submitbox_misc_actions' ) ); - } -} diff --git a/tests/php/test-tag-and-attribute-sanitizer.php b/tests/php/test-tag-and-attribute-sanitizer.php deleted file mode 100644 index 803691ceaf1..00000000000 --- a/tests/php/test-tag-and-attribute-sanitizer.php +++ /dev/null @@ -1,4169 +0,0 @@ -<?php -/** - * Class AMP_Tag_And_Attribute_Sanitizer_Test - * - * @package AMP - */ - -use AmpProject\AmpWP\Dom\Options; -use AmpProject\AmpWP\Tests\Helpers\MarkupComparison; -use AmpProject\Dom\Document; -use AmpProject\AmpWP\Tests\TestCase; -use AmpProject\AmpWP\ValidationExemption; -use AmpProject\DevMode; - -// phpcs:disable WordPress.WP.EnqueuedResources - -/** - * Test AMP_Tag_And_Attribute_Sanitizer - * - * @covers AMP_Tag_And_Attribute_Sanitizer - */ -class AMP_Tag_And_Attribute_Sanitizer_Test extends TestCase { - - use MarkupComparison; - - /** - * Get data for testing sanitization in the body. - * - * @return array[] Each array item is a tuple containing pre-sanitized string, sanitized string, and scripts - * identified during sanitization. - */ - public function get_body_data() { - return [ - 'empty_doc' => [ - '', - '', - ], - - 'a-test' => [ - '<a on="tap:see-image-lightbox" role="button" class="button button-secondary play" tabindex="0">Show Image</a>', - ], - - 'a4a' => [ - '<amp-ad width="300" height="400" type="fake" data-use-a4a="true" data-vars-analytics-var="bar" src="fake_amp.json"><div placeholder=""></div><div fallback=""></div></amp-ad>', - null, // No change. - [ 'amp-ad' ], - ], - - 'ads' => [ - '<amp-ad width="300" height="250" type="a9" data-aax_size="300x250" data-aax_pubname="test123" data-aax_src="302"><div placeholder=""></div><div fallback=""></div></amp-ad>', - null, // No change. - [ 'amp-ad' ], - ], - - 'amp-app-banner-bad-ads' => [ - ' - <amp-app-banner layout="nodisplay" id="my-app-banner"> - <amp-img src="https://cdn-images-1.medium.com/max/50/1*JLegdtjFMNgqHgnxdd04fg.png" width="50" height="43" layout="fixed"></amp-img> - <div class="banner-text"><amp-ad width="300" height="250" type="a9" data-aax_size="300x250" data-aax_pubname="test123" data-aax_src="302"><div placeholder=""></div><div fallback=""></div></amp-ad></div> - <button open-button>View in app</button> - </amp-app-banner> - ', - ' - <amp-app-banner layout="nodisplay" id="my-app-banner"> - <amp-img src="https://cdn-images-1.medium.com/max/50/1*JLegdtjFMNgqHgnxdd04fg.png" width="50" height="43" layout="fixed"></amp-img> - <div class="banner-text"></div> - <button open-button>View in app</button> - </amp-app-banner> - ', - [ 'amp-app-banner' ], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG_ANCESTOR ], - ], - - 'amp-script-nested' => [ - '<amp-script layout="container" src="https://example.com/hello-world.js"><amp-script layout="container" src="https://example.com/goodbye-world.js"><button>Goodbye!</button></amp-script></amp-script>', - '<amp-script layout="container" src="https://example.com/hello-world.js"></amp-script>', - [ 'amp-script' ], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG_ANCESTOR ], - ], - - 'amp-script-intrinsic' => [ - ' - <amp-script src="https://example.com/hello-world.js" layout="intrinsic" width="200" height="123" sandbox="allow-forms"> - <button>Hello amp-script!</button> - </amp-script> - ', - null, - [ 'amp-script' ], - ], - - 'bad-svg-stop' => [ - '<stop offset="5%" stop-color="gold" />', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MANDATORY_TAG_ANCESTOR, - 'spec_names' => [ - 'lineargradient > stop', - 'radialgradient > stop', - ], - ], - ], - ], - - 'bad-noscript' => [ - '<noscript><noscript>hello</noscript></noscript>', - '<noscript></noscript>', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::WRONG_PARENT_TAG, - 'spec_name' => 'noscript enclosure for amp style tags', - 'required_parent_name' => 'head', - ], - ], - ], - - 'adsense' => [ - '<amp-ad width="300" height="250" type="adsense" data-ad-client="ca-pub-2005682797531342" data-ad-slot="7046626912"><div placeholder=""></div><div fallback=""></div></amp-ad>', - null, // No change. - [ 'amp-ad' ], - ], - - 'amp-3q-player' => [ - '<amp-3q-player data-id="c8dbe7f4-7f7f-11e6-a407-0cc47a188158" layout="responsive" width="480" height="270"></amp-3q-player>', - null, - [ 'amp-3q-player' ], - ], - - 'amp-ad' => [ - '<amp-ad width="300" height="250" type="foo" block-rtc always-serve-npa></amp-ad>', - null, // No change. - [ 'amp-ad' ], - ], - - 'amp-sticky-ad' => [ - '<amp-sticky-ad layout="nodisplay"><amp-ad width="320" height="50" type="doubleclick" data-slot="/35096353/amptesting/formats/sticky"></amp-ad></amp-sticky-ad>', - null, - [ 'amp-ad', 'amp-sticky-ad' ], - ], - - 'amp-sticky-ad-bad-children' => [ - '<amp-sticky-ad layout="nodisplay"><span>not allowed</span><amp-ad width="320" height="50" type="doubleclick" data-slot="/35096353/amptesting/formats/sticky"></amp-ad><i>not ok</i></amp-sticky-ad>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_FIRST_CHILD_TAG ], - ], - - 'amp-animation' => [ - '<amp-animation layout="nodisplay"><script type="application/json">{}</script></amp-animation>', - null, - [ 'amp-animation' ], - ], - - 'amp-call-tracking-ok' => [ - '<amp-call-tracking config="https://example.com/calltracking.json"><a href="tel:123456789">+1 (23) 456-789</a></amp-call-tracking>', - null, - [ 'amp-call-tracking' ], - ], - - 'amp-call-tracking-bad-children' => [ - '<amp-call-tracking config="https://example.com/calltracking.json"><b>bad</b>--and not great: <a href="tel:123456789">+1 (23) 456-789</a><i>more bad</i>not great</amp-call-tracking>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_CHILD_TAG ], - ], - - 'amp-call-tracking_disallowed_config' => [ - '<amp-call-tracking config="__amp_source_origin"><a href="tel:123456789">+1 (23) 456-789</a></amp-call-tracking>', - '', - [], // Important: This needs to be empty because the amp-call-tracking is stripped. - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::INVALID_DISALLOWED_VALUE_REGEX, - 'node_name' => 'config', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'node_name' => 'amp-call-tracking', - ], - ], - ], - - 'amp-embed' => [ - '<amp-embed type="taboola" width="400" height="300" layout="responsive"></amp-embed>', - null, // No change. - [ 'amp-ad' ], - ], - - 'amp-facebook-comments' => [ - '<amp-facebook-comments width="486" height="657" data-href="http://example.com/baz" layout="responsive" data-numposts="5"></amp-facebook-comments>', - null, // No change. - [ 'amp-facebook-comments' ], - ], - - 'amp-facebook-comments_bento' => [ - '<amp-facebook-comments width="486" height="657" data-href="http://example.com/baz" layout="responsive" data-numposts="5"></amp-facebook-comments>', - null, // No change. - [ 'amp-facebook' ], - [], - [ 'prefer_bento' => true ], - ], - - 'amp-facebook-comments_missing_required_attribute' => [ - '<amp-facebook-comments width="486" height="657" layout="responsive" data-numposts="5"></amp-facebook-comments>', - '', - [], // Empty because invalid. - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'attributes' => [ 'data-href' ], - ], - ], - ], - - 'amp-facebook-like' => [ - '<amp-facebook-like width="90" height="20" data-href="http://example.com/baz" layout="fixed" data-layout="button_count"></amp-facebook-like>', - null, // No change. - [ 'amp-facebook-like' ], - ], - - 'amp-facebook-like_bento' => [ - '<amp-facebook-like width="90" height="20" data-href="http://example.com/baz" layout="fixed" data-layout="button_count"></amp-facebook-like>', - null, // No change. - [ 'amp-facebook' ], - [], - [ 'prefer_bento' => true ], - ], - - 'amp-facebook-page' => [ - '<amp-facebook-page width="340" height="130" layout="responsive" data-href="https://www.facebook.com/imdb/"></amp-facebook-page>', - null, // No change. - [ 'amp-facebook-page' ], - ], - - 'amp-facebook-page_bento' => [ - '<amp-facebook-page width="340" height="130" layout="responsive" data-href="https://www.facebook.com/imdb/"></amp-facebook-page>', - null, // No change. - [ 'amp-facebook' ], - [], - [ 'prefer_bento' => true ], - ], - - 'amp-facebook-like_missing_required_attribute' => [ - '<amp-facebook-like width="90" height="20" layout="fixed" data-layout="button_count"></amp-facebook-like>', - '', - [], // Empty because invalid. - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'attributes' => [ 'data-href' ], - ], - ], - ], - - 'amp-fit-text' => [ - '<amp-fit-text width="300" height="200" layout="responsive">Lorem ipsum</amp-fit-text>', - null, // No change. - [ 'amp-fit-text' ], - ], - - 'amp-gist' => [ - '<amp-gist layout="fixed-height" data-gistid="a19" height="1613"></amp-gist>', - null, // No change. - [ 'amp-gist' ], - ], - - 'amp-gist_missing_mandatory_attribute' => [ - '<amp-gist layout="fixed-height" height="1613"></amp-gist>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'attributes' => [ 'data-gistid' ], - ], - ], - ], - - 'amp-iframe' => [ - '<amp-iframe width="600" height="200" sandbox="allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-presentation allow-same-origin allow-scripts allow-top-navigation-by-user-activation" layout="responsive" frameborder="0" src="https://www.example.com"></amp-iframe>', - null, // No change. - [ 'amp-iframe' ], - ], - - 'amp-iframe_incorrect_protocol' => [ - '<amp-iframe width="600" height="200" sandbox="allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-presentation allow-same-origin allow-scripts allow-top-navigation-by-user-activation" layout="responsive" frameborder="0" src="badprotocol://www.example.com"></amp-iframe>', - '', - [], - [ - AMP_Tag_And_Attribute_Sanitizer::INVALID_URL_PROTOCOL, - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MANDATORY_ONEOF_ATTR_MISSING, - 'mandatory_oneof_attrs' => [ 'src', 'srcdoc' ], - ], - ], - ], - - 'amp-ima-video' => [ - ' - <amp-ima-video width="640" height="360" data-tag="https://example.com/foo" layout="responsive" data-src="https://example.com/bar"> - <source src="https://example.com/foo.mp4" type="video/mp4"> - <source src="https://example.com/foo.webm" type="video/webm"> - <track label="English subtitles" kind="subtitles" srclang="en" src="https://example.com/subtitles.vtt"> - <script type="application/json">{"locale": "en","numRedirects": 4}</script> - </amp-ima-video> - ', - null, // No change. - [ 'amp-ima-video' ], - ], - - 'amp-ima-video_missing_required_attribute' => [ - '<amp-ima-video width="640" height="360" layout="responsive" data-src="https://example.com/bar"></amp-ima-video>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING ], - ], - - 'amp-imgur' => [ - '<amp-imgur data-imgur-id="54321" layout="responsive" width="540" height="663"></amp-imgur>', - null, // No change. - [ 'amp-imgur' ], - ], - - 'amp-install-serviceworker' => [ - '<amp-install-serviceworker src="https://www.emample.com/worker.js" data-iframe-src="https://www.example.com/serviceworker.html" layout="nodisplay"></amp-install-serviceworker>', - null, // No change. - [ 'amp-install-serviceworker' ], - ], - - 'amp-izlesene' => [ - '<amp-izlesene data-videoid="4321" layout="responsive" width="432" height="123"></amp-izlesene>', - null, // No change. - [ 'amp-izlesene' ], - ], - - 'amp-mathml' => [ - '<amp-mathml layout="container" inline data-formula="\[x = {-b \pm \sqrt{b^2-4ac} \over 2a}.\]"></amp-mathml>', - null, // No change. - [ 'amp-mathml' ], - ], - - 'amp-riddle-quiz' => [ - '<amp-riddle-quiz layout="responsive" width="600" height="400" data-riddle-id="25799"></amp-riddle-quiz>', - null, // No change. - [ 'amp-riddle-quiz' ], - ], - - 'amp-wistia-player' => [ - '<amp-wistia-player data-media-hashed-id="u8p9wq6mq8" width="512" height="360"></amp-wistia-player>', - null, // No change. - [ 'amp-wistia-player' ], - ], - - 'amp-byside-content' => [ - '<amp-byside-content data-webcare-id="D6604AE5D0" data-channel="" data-lang="pt" data-fid="" data-label="amp-number" layout="fixed" width="120" height="40"></amp-byside-content>', - null, // No change. - [ 'amp-byside-content' ], - ], - - 'amp-bind-macro' => [ - '<amp-bind-macro id="circleArea" arguments="radius" expression="3.14 * radius * radius"></amp-bind-macro>', - null, // No change. - [ 'amp-bind' ], - ], - - 'amp-list-load-more_no_mandatory_oneof' => [ - '<amp-list src="https://foo.com" width="400" height="800"><amp-list-load-more></amp-list-load-more></amp-list>', - '<amp-list src="https://foo.com" width="400" height="800"></amp-list>', - [ 'amp-list' ], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MANDATORY_ONEOF_ATTR_MISSING, - 'mandatory_oneof_attrs' => [ - 'load-more-button', - 'load-more-end', - 'load-more-failed', - 'load-more-loading', - ], - ], - ], - ], - - 'amp-nexxtv-player' => [ - '<amp-nexxtv-player data-mediaid="123ABC" data-client="4321" width="100" height="100"></amp-nexxtv-player>', - null, // No change. - [ 'amp-nexxtv-player' ], - ], - - 'amp-playbuzz' => [ - '<amp-playbuzz src="id-from-the-content-here" height="500" data-item-info="true" data-share-buttons="true" data-comments="true"></amp-playbuzz>', - null, // No change. - [ 'amp-playbuzz' ], - ], - - 'amp-playbuzz_no_src' => [ - '<amp-playbuzz height="500" data-item-info="true"></amp-playbuzz>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MANDATORY_ONEOF_ATTR_MISSING, - 'mandatory_oneof_attrs' => [ - 'data-item', - 'src', - ], - ], - ], - ], - - 'invalid_element_stripped' => [ - '<nonexistent><p>Foo text</p></nonexistent>', - '<p>Foo text</p>', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'nonexistent', - ], - ], - ], - - 'nested_invalid_elements_stripped' => [ - '<bad-details><bad-summary><p>Example Summary</p></bad-summary><p>Example expanded text</p></bad-details>', - '<p>Example Summary</p><p>Example expanded text</p>', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'bad-summary', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'bad-details', - ], - ], - ], - - 'amp-next-page-example' => [ - ' - <amp-next-page deep-parsing="false" max-pages="5"> - <script type="application/json"> - [ - { - "image": "https://example.com/image1.jpg", - "title": "This article shows first", - "url": "https://example.com/article1.amp.html" - } - ] - </script> - </amp-next-page> - ', - null, - [ 'amp-next-page' ], - ], - - 'amp-next-page-hide-and-replace' => [ - ' - <header class="my-header" next-page-hide> - <h2>Text here.</h2> - </header> - <div class="sticky" next-page-replace="sticky-123"> - <h2>The second sticky will replace me once you scroll past my page</h2> - </div> - ', - null, - [ 'amp-next-page' ], - ], - - // AMP-NEXT-PAGE > [separator]. - 'reference-point-amp-next-page-separator' => [ - '<amp-next-page src="https://example.com/config.json" xssi-prefix=")]}"><div separator><h1>Keep reading</h1></div></amp-next-page>', - null, - [ 'amp-next-page' ], - ], - - // AMP-NEXT-PAGE > [footer]. - 'reference-point-amp-next-page-footer' => [ - '<amp-next-page src="https://example.com/config.json"><div footer>The footer</div></amp-next-page>', - null, - [ 'amp-next-page' ], - ], - - // AMP-NEXT-PAGE > [recommendation-box]. - 'reference-point-amp-next-page-recommendation' => [ - ' - <amp-next-page src="https://example.com/config.json"> - <div recommendation-box class="my-custom-recommendation-box"> - Here are a few more articles: - <template type="amp-mustache"> - <div class="recommendation-box-content"> - {{#pages}} <span class="title">{{title}}</span> - <span class="url">{{url}}</span> - <span class="image">{{image}}</span> - {{/pages}} </div> - </template> - </div> - </amp-next-page> - ', - null, - [ 'amp-next-page', 'amp-mustache' ], - ], - - // amp-next-page extension .json configuration. - 'reference-point-amp-next-page-json-config' => [ - '<amp-next-page><script type="application/json">{"pages": []}</script></amp-next-page>', - null, - [ 'amp-next-page' ], - ], - - 'reference-point-amp-carousel-lightbox-exclude' => [ - '<amp-carousel width="400" height="300" layout="responsive" type="slides" lightbox=""><amp-img src="/awesome.png" width="300" height="300" lightbox=""></amp-img><amp-img src="/awesome.png" width="300" height="300" lightbox-exclude=""></amp-img></amp-carousel>', - null, - [ 'amp-carousel', 'amp-lightbox-gallery' ], - ], - - 'reference-point-lightbox-thumbnail-id' => [ - '<amp-img src="/awesome.png" width="300" height="300" lightbox lightbox-thumbnail-id="a"></amp-img>', - null, - [ 'amp-lightbox-gallery' ], - ], - - 'lightbox-with-amp-carousel' => [ - '<amp-carousel lightbox width="1600" height="900" layout="responsive" type="slides"><amp-img src="image1" width="200" height="100"></amp-img><amp-img src="image1" width="200" height="100"></amp-img><amp-img src="image1" width="200" height="100"></amp-img></amp-carousel>', - null, - [ 'amp-lightbox-gallery', 'amp-carousel' ], - ], - - 'reference-points-amp-live-list' => [ - '<amp-live-list id="my-live-list" data-poll-interval="15000" data-max-items-per-page="20"><button update on="tap:my-live-list.update">You have updates!</button><div items></div><div pagination></div></amp-live-list>', - null, - [ 'amp-live-list' ], - ], - - 'reference-points-amp-story' => call_user_func( - static function () { - $html = str_replace( - [ "\n", "\t" ], - '', - ' - <amp-story standalone entity="User" entity-logo-src="https://example.com/logo/1x1.png" entity-url="https://example.com/profile/user" live-story-disabled supports-landscape title="My Story" publisher="The AMP Team" publisher-logo-src="https://example.com/logo/1x1.png" poster-portrait-src="https://example.com/my-story/poster/3x4.jpg" poster-square-src="https://example.com/my-story/poster/1x1.jpg" poster-landscape-src="https://example.com/my-story/poster/4x3.jpg" background-audio="my.mp3"> - <amp-story-auto-analytics gtag-id="UA-ANALYTICS"></amp-story-auto-analytics> - <amp-story-page id="my-first-page" next-page-no-ad> - <amp-story-grid-layer template="fill" anchor="top" aspect-ratio="1:2" preset="2021-foreground"> - <amp-img id="object1" animate-in="rotate-in-left" src="https://example.ampproject.org/helloworld/bg1.jpg" width="900" height="1600"> - </amp-img> - <!-- Note: The viewbox attribute must currently be lower-case due to https://github.com/ampproject/amp-wp/issues/2045 --> - <svg viewbox="0 0 100 100"><circle cx="50" cy="50" r="50" /></svg> - </amp-story-grid-layer> - <amp-story-grid-layer template="vertical"> - <h1 animate-in="fly-in-left" animate-in-duration="0.5s" animate-in-delay="0.4s" animate-in-after="object1">Hello, amp-story!</h1> - <h2 scale-start="1.0" scale-end="200.1" translate-x="100px" translate-y="200px">Scaled</h2> - <amp-twitter width="375" height="472" layout="responsive" data-tweetid="885634330868850689"></amp-twitter> - <amp-twitter interactive width="375" height="472" layout="responsive" data-tweetid="885634330868850689"></amp-twitter> - <amp-video autoplay volume="0.5" loop width="720" height="960" poster="https://amp.dev/static/samples/img/story_video_dog_cover.jpg" layout="responsive" cache="google"> - <source src="https://amp.dev/static/samples/video/story_video_dog.mp4" type="video/mp4"> - </amp-video> - <amp-date-display datetime="2017-08-02T15:05:05.000" layout="fixed" width="360" height="20"><template type="amp-mustache"><div>{{dayName}} {{day}} {{monthName}} {{year}} {{hourTwoDigit}}:{{minuteTwoDigit}}:{{secondTwoDigit}}</div></template></amp-date-display> - </amp-story-grid-layer> - <amp-pixel src="https://example.com/tracker/foo" layout="nodisplay"></amp-pixel> - </amp-story-page> - <amp-story-page id="my-second-page"> - <amp-analytics config="https://example.com/analytics.account.config.json"></amp-analytics> - <amp-story-grid-layer template="fill"> - <amp-story-360 controls="gyroscope" layout="fixed" width="100" height="100" heading-start="-45" pitch-start="-20" heading-end="95" pitch-end="-10" scene-heading="0.00" scene-pitch="0.00" scene-roll="0.00" zoom-end="4" duration="30s"> - <amp-img src="img/panorama1.jpg" layout="fixed" width="200" height="100" crossorigin="anonymous" referrerpolicy="origin"></amp-img> - </amp-story-360> - </amp-story-grid-layer> - <amp-story-grid-layer template="thirds"> - <amp-img grid-area="bottom-third" src="https://example.ampproject.org/helloworld/bg2.gif" width="900" height="1600"> - </amp-img> - </amp-story-grid-layer> - <amp-story-grid-layer template="vertical"> - <h1 animate-in="drop" animate-in-delay="500ms" animate-in-duration="600ms">The End</h1> - <div class="amp-story-block-wrapper"> - <h1 animate-in="drop" animate-in-delay="1500ms" animate-in-duration="700ms">Afterward</h1> - </div> - <button class="baddie">bad</button> - </amp-story-grid-layer> - <amp-story-cta-layer> - <a href="https://example.com">Click me.</a> - <button>Hello</button> - </amp-story-cta-layer> - <amp-story-page-attachment layout="nodisplay" theme="dark" data-cta-text="Read more" data-title="My title" cta-image="https://example.com/image.png"> - <h1>My title</h1> - <p>Lots of interesting text with <a href="https://example.ampproject.org">links</a>!</p> - <p>More text and a YouTube video!</p> - <amp-youtube data-videoid="b4Vhdr8jtx0" layout="responsive" width="480" height="270"> - </amp-youtube> - <amp-video src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4" width="300" height="300" controls=""></amp-video> - <p>And a tweet!</p> - <amp-twitter data-tweetid="885634330868850689" layout="responsive" width="480" height="270"> - </amp-twitter> - </amp-story-page-attachment> - </amp-story-page> - <amp-story-page id="page1" auto-advance-after="video"> - <amp-story-grid-layer template="fill"> - <amp-video id="video" src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" poster="https://example.com/poster.jpg" width="1280" height="720" layout="responsive" autoplay captions-id="captions"> - <track kind="subtitles" src="https://example.com/captions.vtt" srclang="en" default> - </amp-video> - </amp-story-grid-layer> - <amp-story-grid-layer template="vertical" class="bottom"> - <div class="scrim"> - <amp-story-captions id="captions" layout="fixed-height" height="100"></amp-story-captions> - <div class="static-text">This element is always below captions and never overlaps.</div> - </div> - </amp-story-grid-layer> - </amp-story-page> - <amp-story-page id="interactive-poll"> - <amp-story-grid-layer template="fill"> - <amp-story-interactive-poll id="correct-poll" endpoint="https://webstoriesinteractivity-beta.web.app/api/v1" theme="dark" chip-style="shadow" class="nice-quiz" prompt-text="What country do you like the most?" option-1-text="France" option-1-confetti="🇺🇾" option-1-results-category="Dog" option-2-text="Spain" option-2-confetti="🇺🇾" option-2-results-category="Cat" option-3-text="Uruguay" option-3-confetti="🇺🇾" option-3-results-category="Bunny" option-4-text="Brazil" option-4-confetti="🇺🇾" option-4-results-category="Mouse"> - </amp-story-interactive-poll> - <amp-story-interactive-results prompt-text="Your level is" option-1-results-category="Beginner" option-1-image="beginner.png" option-1-results-threshold="1.0" option-2-results-category="Expet" option-2-image="expert.png" option-2-results-threshold="80"></amp-story-interactive-results> - </amp-story-grid-layer> - </amp-story-page> - <amp-story-page id="amp-story-interactive-binary-poll"> - <amp-story-grid-layer template="fill"> - <amp-story-interactive-binary-poll id="correct-binary-poll" endpoint="https://webstoriesinteractivity-beta.web.app/api/v1" theme="dark" class="cool-binary-poll" option-1-text="France" option-1-confetti="🇺🇾" option-2-text="Spain" option-2-confetti="🇺🇾"> - </amp-story-interactive-binary-poll> - </amp-story-grid-layer> - </amp-story-page> - <amp-story-page id="amp-story-interactive-quiz"> - <amp-story-grid-layer template="fill"> - <amp-story-interactive-quiz id="correct-quiz" endpoint="https://webstoriesinteractivity-beta.web.app/api/v1" theme="dark" chip-style="shadow" class="nice-quiz" prompt-text="Who won the first soccer world cup?" option-1-text="France" option-2-text="Spain" option-3-text="Uruguay" option-3-correct option-3-confetti="🇺🇾" option-4-text="Brazil"> - </amp-story-interactive-quiz> - </amp-story-grid-layer> - </amp-story-page> - <amp-story-page id="amp-story-interactive-results"> - <amp-story-grid-layer template="fill"> - <amp-story-interactive-results id="correct-results" theme="dark" class="nice-quiz" prompt-text="What country do you like the most?" option-1-text="France" option-1-results-category="Dog" option-1-image="./dog.png" option-2-text="Spain" option-2-results-category="Cat" option-2-image="./cat.png" option-3-text="Uruguay" option-3-results-category="Bunny" option-3-image="./bunny.png" option-4-text="Brazil" option-4-results-category="Mouse" option-4-image="./mouse.png"> - </amp-story-interactive-results> - </amp-story-grid-layer> - </amp-story-page> - <amp-story-page id="cover"> - <amp-story-grid-layer template="fill"> - <amp-story-panning-media layout="fill"> - <amp-img src="https://example.com/img.jpg" layout="fill"></amp-img> - </amp-story-panning-media> - </amp-story-grid-layer> - <amp-story-page-outlink layout="nodisplay" cta-image="https://example.com/img/logo.jpg" cta-accent-color="navy" cta-accent-element="background"> - <a href="https://www.google.com/search?q=why+do+cats+purr+so+loud" title="Link Description"></a> - </amp-story-page-outlink> - </amp-story-page> - <amp-story-social-share layout="nodisplay"> - <script type="application/json">{"shareProviders": ["facebook","whatsapp"]}</script> - </amp-story-social-share> - <amp-story-bookend src="bookendv1.json" layout="nodisplay"></amp-story-bookend> - <amp-analytics id="75a1fdc3143c" type="googleanalytics"><script type="application/json">{"vars":{"account":"UA-XXXXXX-1"},"triggers":{"trackPageview":{"on":"visible","request":"pageview"}}}</script></amp-analytics> - </amp-story> - ' - ); - - return [ - $html, - preg_replace( '#<\w+[^>]*>bad</\w+>#', '', $html ), - [ - 'amp-story', - 'amp-story-auto-analytics', - 'amp-analytics', - 'amp-story-360', - 'amp-twitter', - 'amp-youtube', - 'amp-video', - 'amp-story-interactive', - 'amp-story-panning-media', - 'amp-date-display', - 'amp-mustache', - 'amp-story-captions', - ], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_DESCENDANT_TAG, - 'node_name' => 'button', - 'spec_name' => 'amp-story-grid-layer', - ], - ], - ]; - } - ), - - 'amp_story_player' => [ - ' - <amp-story-player width="360" height="600" layout="intrinsic"> - <a href="https://www.example.com" class="story"> - <span class="title">A local’s guide to what to eat and do in New York City</span> - </a> - <a href="https://www.example.com2" class="story"> - <span class="title">A local’s guide to what to eat and do in Mexico City</span> - </a> - </amp-story-player> - ', - null, - [ 'amp-story-player' ], - ], - - 'amp_story_player_with_poster' => [ - ' - <amp-story-player layout="fixed" width="360" height="600"> - <a href="https://preview.amp.dev/documentation/examples/introduction/stories_in_amp/"> - <img src="https://amp.dev/static/samples/img/story_dog2_portrait.jpg" width="360" height="600" loading="lazy" data-amp-story-player-poster-img> - Stories in AMP - Hello World - </a> - </amp-story-player> - ', - null, - [ 'amp-story-player' ], - ], - - 'amp_story_360' => [ - ' - <amp-story-player width="360" height="600"> - <a href="https://www.example.com" class="story"> - <span class="title">A local’s guide to what to eat and do in New York City</span> - </a> - <a href="https://www.example.com2" class="story"> - <span class="title">A local’s guide to what to eat and do in Mexico City</span> - </a> - </amp-story-player> - ', - null, - [ 'amp-story-player' ], - ], - - 'reference-points-bad' => [ - '<div lightbox-thumbnail-id update items pagination separator option selected disabled>BAD REFERENCE POINTS</div>', - '<div>BAD REFERENCE POINTS</div>', - [], - array_fill( 0, 8, AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ), - ], - - 'amp-position-observer' => [ - '<amp-position-observer intersection-ratios="1" layout="nodisplay"></amp-position-observer>', - null, // No change. - [ 'amp-position-observer' ], - ], - - 'amp-twitter' => [ - '<amp-twitter width="321" height="543" layout="responsive" data-tweetid="98765" [data-tweetid]="somestate"></amp-twitter>', - '<amp-twitter width="321" height="543" layout="responsive" data-tweetid="98765" data-amp-bind-data-tweetid="somestate"></amp-twitter>', - [ 'amp-twitter', 'amp-bind' ], - ], - - 'amp-user-notification' => [ - '<amp-user-notification layout="nodisplay" id="amp-user-notification1" data-show-if-href="https://example.com/api/show?timestamp=TIMESTAMP" data-dismiss-href="https://example.com/api/echo/post">This site uses cookies to personalize content.<a class="btn" on="tap:amp-user-notification1.dismiss">I accept</a></amp-user-notification>', - '<amp-user-notification layout="nodisplay" id="amp-user-notification1" data-show-if-href="https://example.com/api/show?timestamp=TIMESTAMP" data-dismiss-href="https://example.com/api/echo/post">This site uses cookies to personalize content.<a class="btn" on="tap:amp-user-notification1.dismiss">I accept</a></amp-user-notification>', - [ 'amp-user-notification' ], - ], - - 'amp-user-notification-empty-dismiss-href' => [ - '<amp-user-notification layout="nodisplay" id="amp-user-notification1" data-show-if-href="" data-dismiss-href="">This site uses cookies to personalize content.<a class="btn" on="tap:amp-user-notification1.dismiss">I accept</a></amp-user-notification>', - '<amp-user-notification layout="nodisplay" id="amp-user-notification1">This site uses cookies to personalize content.<a class="btn" on="tap:amp-user-notification1.dismiss">I accept</a></amp-user-notification>', - [ 'amp-user-notification' ], - [ AMP_Tag_And_Attribute_Sanitizer::MISSING_URL, AMP_Tag_And_Attribute_Sanitizer::MISSING_URL ], - ], - - 'amp-video' => [ - '<amp-video width="432" height="987" layout="intrinsic" src="/video/location.mp4"></amp-video>', - null, // No change. - [ 'amp-video' ], - ], - - 'amp_video_children' => [ - '<amp-video width="432" height="987"><track kind="subtitles" src="https://example.com/sampleChapters.vtt" srclang="en"><source src="foo.webm" type="video/webm"><source src="foo.ogg" type="video/ogg"><div placeholder>Placeholder</div><span fallback>Fallback</span></amp-video>', - null, // No change. - [ 'amp-video' ], - ], - - 'amp_audio_children' => [ - '<amp-audio><track kind="subtitles" src="https://example.com/sampleChapters.vtt" srclang="en"><source src="foo.mp3" type="audio/mp3"><source src="foo.wav" type="audio/wav"><div placeholder>Placeholder</div><span fallback>Fallback</span></amp-audio>', - null, // No change. - [ 'amp-audio' ], - ], - - 'amp-vk' => [ - '<amp-vk width="500" height="300" data-embedtype="post" layout="responsive"></amp-vk>', - null, // No change. - [ 'amp-vk' ], - ], - - 'amp-apester-media' => [ - '<amp-apester-media height="444" data-apester-media-id="57a336dba187a2ca3005e826" layout="fixed-height"></amp-apester-media>', - '<amp-apester-media height="444" data-apester-media-id="57a336dba187a2ca3005e826" layout="fixed-height"></amp-apester-media>', - [ 'amp-apester-media' ], - ], - - 'button' => [ - '<button on="tap:AMP.setState(foo=\'foo\', isButtonDisabled=true, textClass=\'redBackground\', imgSrc=\'https://ampbyexample.com/img/Shetland_Sheepdog.jpg\', imgSize=200, imgAlt=\'Sheepdog\', videoSrc=\'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4\')">Click me</button>', - null, - ], - - 'brid-player' => [ - '<amp-brid-player data-dynamic="abc" data-partner="264" data-player="4144" data-video="13663" layout="responsive" width="480" height="270" dock></amp-brid-player>', - null, - [ 'amp-brid-player', 'amp-video-docking' ], - ], - - 'brightcove' => [ - '<amp-brightcove data-account="906043040001" data-video-id="1401169490001" data-player="180a5658-8be8-4f33-8eba-d562ab41b40c" layout="responsive" width="480" height="270"></amp-brightcove>', - '<amp-brightcove data-account="906043040001" data-video-id="1401169490001" data-player="180a5658-8be8-4f33-8eba-d562ab41b40c" layout="responsive" width="480" height="270"></amp-brightcove>', - [ 'amp-brightcove' ], - ], - - 'carousel_slides' => [ - '<amp-carousel width="400" height="300" layout="responsive" type="slides" controls=""><div>hello world</div><amp-img src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n" layout="fill"></amp-img><amp-img src="https://lh3.googleusercontent.com/5rcQ32ml8E5ONp9f9-Rf78IofLb9QjS5_0mqsY1zEFc=w400-h300-no-n" width="400" height="300" layout="responsive"></amp-img><amp-img src="https://lh3.googleusercontent.com/Z4gtm5Bkxyv21Z2PtbTf95Clb9AE4VTR6olbBKYrenM=w400-h300-no-n" width="400" height="300" layout="responsive"></amp-img><amp-soundcloud height="300" layout="fixed-height" data-trackid="243169232"></amp-soundcloud><amp-youtube data-videoid="mGENRKrdoGY" width="400" height="300"></amp-youtube><amp-anim src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no" width="400" height="300"><amp-img placeholder="" src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no-k" width="400" height="300"></amp-img></amp-anim><amp-audio src="https://ia801402.us.archive.org/16/items/EDIS-SRP-0197-06/EDIS-SRP-0197-06.mp3"></amp-audio><amp-brightcove data-account="906043040001" data-video-id="1401169490001" data-player="180a5658-8be8-4f33-8eba-d562ab41b40c" layout="responsive" width="480" height="270"></amp-brightcove><amp-vimeo data-videoid="27246366" width="500" height="281"></amp-vimeo><amp-dailymotion data-videoid="x3rdtfy" width="500" height="281"></amp-dailymotion><amp-vine data-vineid="MdKjXez002d" width="381" height="381" layout="responsive"></amp-vine><amp-video src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4" width="358" height="204" layout="responsive" controls=""></amp-video></amp-carousel><amp-carousel width="auto" height="300" controls=""><div>hello world</div><amp-img src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n" width="400" height="300"></amp-img><amp-img src="https://lh3.googleusercontent.com/5rcQ32ml8E5ONp9f9-Rf78IofLb9QjS5_0mqsY1zEFc=w400-h300-no-n" width="400" height="300"></amp-img><amp-img src="https://lh3.googleusercontent.com/Z4gtm5Bkxyv21Z2PtbTf95Clb9AE4VTR6olbBKYrenM=w400-h300-no-n" width="400" height="300"></amp-img><amp-soundcloud height="300" layout="fixed-height" data-trackid="243169232"></amp-soundcloud><amp-youtube data-videoid="mGENRKrdoGY" width="400" height="300"></amp-youtube><amp-anim src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no" width="400" height="300"><amp-img placeholder="" src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no-k" width="400" height="300"></amp-img></amp-anim><amp-audio src="https://ia801402.us.archive.org/16/items/EDIS-SRP-0197-06/EDIS-SRP-0197-06.mp3"></amp-audio><amp-brightcove data-account="906043040001" data-video-id="1401169490001" data-player="180a5658-8be8-4f33-8eba-d562ab41b40c" layout="responsive" width="300" height="300"></amp-brightcove><amp-vimeo data-videoid="27246366" width="300" height="300"></amp-vimeo><amp-dailymotion data-videoid="x3rdtfy" width="300" height="300"></amp-dailymotion><amp-vine data-vineid="MdKjXez002d" width="300" height="300"></amp-vine><amp-video src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4" width="300" height="300" controls=""></amp-video></amp-carousel>', - '<amp-carousel width="400" height="300" layout="responsive" type="slides" controls=""><div>hello world</div><amp-img src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n" layout="fill"></amp-img><amp-img src="https://lh3.googleusercontent.com/5rcQ32ml8E5ONp9f9-Rf78IofLb9QjS5_0mqsY1zEFc=w400-h300-no-n" width="400" height="300" layout="responsive"></amp-img><amp-img src="https://lh3.googleusercontent.com/Z4gtm5Bkxyv21Z2PtbTf95Clb9AE4VTR6olbBKYrenM=w400-h300-no-n" width="400" height="300" layout="responsive"></amp-img><amp-soundcloud height="300" layout="fixed-height" data-trackid="243169232"></amp-soundcloud><amp-youtube data-videoid="mGENRKrdoGY" width="400" height="300"></amp-youtube><amp-anim src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no" width="400" height="300"><amp-img placeholder="" src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no-k" width="400" height="300"></amp-img></amp-anim><amp-audio src="https://ia801402.us.archive.org/16/items/EDIS-SRP-0197-06/EDIS-SRP-0197-06.mp3"></amp-audio><amp-brightcove data-account="906043040001" data-video-id="1401169490001" data-player="180a5658-8be8-4f33-8eba-d562ab41b40c" layout="responsive" width="480" height="270"></amp-brightcove><amp-vimeo data-videoid="27246366" width="500" height="281"></amp-vimeo><amp-dailymotion data-videoid="x3rdtfy" width="500" height="281"></amp-dailymotion><amp-vine data-vineid="MdKjXez002d" width="381" height="381" layout="responsive"></amp-vine><amp-video src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4" width="358" height="204" layout="responsive" controls=""></amp-video></amp-carousel><amp-carousel width="auto" height="300" controls=""><div>hello world</div><amp-img src="https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n" width="400" height="300"></amp-img><amp-img src="https://lh3.googleusercontent.com/5rcQ32ml8E5ONp9f9-Rf78IofLb9QjS5_0mqsY1zEFc=w400-h300-no-n" width="400" height="300"></amp-img><amp-img src="https://lh3.googleusercontent.com/Z4gtm5Bkxyv21Z2PtbTf95Clb9AE4VTR6olbBKYrenM=w400-h300-no-n" width="400" height="300"></amp-img><amp-soundcloud height="300" layout="fixed-height" data-trackid="243169232"></amp-soundcloud><amp-youtube data-videoid="mGENRKrdoGY" width="400" height="300"></amp-youtube><amp-anim src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no" width="400" height="300"><amp-img placeholder="" src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h300-no-k" width="400" height="300"></amp-img></amp-anim><amp-audio src="https://ia801402.us.archive.org/16/items/EDIS-SRP-0197-06/EDIS-SRP-0197-06.mp3"></amp-audio><amp-brightcove data-account="906043040001" data-video-id="1401169490001" data-player="180a5658-8be8-4f33-8eba-d562ab41b40c" layout="responsive" width="300" height="300"></amp-brightcove><amp-vimeo data-videoid="27246366" width="300" height="300"></amp-vimeo><amp-dailymotion data-videoid="x3rdtfy" width="300" height="300"></amp-dailymotion><amp-vine data-vineid="MdKjXez002d" width="300" height="300"></amp-vine><amp-video src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4" width="300" height="300" controls=""></amp-video></amp-carousel>', - [ 'amp-anim', 'amp-audio', 'amp-brightcove', 'amp-carousel', 'amp-dailymotion', 'amp-soundcloud', 'amp-video', 'amp-vimeo', 'amp-vine', 'amp-youtube' ], - ], - - 'carousel_simple' => [ - '<amp-carousel width="450" height="300"></amp-carousel>', - null, - [ 'amp-carousel' ], - ], - - 'carousel_lightbox' => [ - '<amp-carousel width="450" height="300" delay="100" arrows [slide]="foo" autoplay loop lightbox></amp-carousel>', - '<amp-carousel width="450" height="300" delay="100" arrows data-amp-bind-slide="foo" autoplay loop lightbox></amp-carousel>', - [ 'amp-bind', 'amp-carousel', 'amp-lightbox-gallery' ], - ], - - 'base_carousel' => [ - ' - <amp-base-carousel width="4" height="3" auto-advance="true" controls="auto" layout="responsive" heights="(min-width: 600px) calc(100% * 4 * 3 / 2), calc(100% * 3 * 3 / 2)" visible-count="(min-width: 600px) 4, 3" advance-count="(min-width: 600px) 4, 3" loop> - <div lightbox-thumbnail-id="food">first slide</div> - <div lightbox-exclude>second slide</div> - </amp-base-carousel> - ', - null, - [ 'amp-base-carousel' ], - ], - - 'amp-dailymotion' => [ - '<amp-dailymotion data-videoid="x3rdtfy" width="500" height="281" dock></amp-dailymotion><h4>Default (responsive)</h4><amp-dailymotion data-videoid="x3rdtfy" width="500" height="281" layout="responsive"></amp-dailymotion><h4>Custom</h4><amp-dailymotion data-videoid="x3rdtfy" data-endscreen-enable="false" data-sharing-enable="false" data-ui-highlight="444444" data-ui-logo="false" data-info="false" width="640" height="360"></amp-dailymotion>', - null, - [ 'amp-dailymotion', 'amp-video-docking' ], - ], - - // Try to test for NAME_VALUE_PARENT_DISPATCH. - 'amp_ima_video' => [ - '<amp-ima-video width="640" height="360" layout="responsive" data-tag="ads.xml" data-poster="poster.png"><source src="foo.mp4" type="video/mp4"><source src="foo.webm" type="video/webm"><track label="English subtitles" kind="subtitles" srclang="en" src="https://example.com/subtitles.vtt"><script type="application/json">{"locale": "en", "numRedirects": 4}</script></amp-ima-video>', - null, // No change. - [ 'amp-ima-video' ], - ], - - // Try to test for NAME_VALUE_DISPATCH. - 'doubleclick-1' => [ - '<amp-ad width="480" height="75" type="doubleclick" data-slot="/4119129/mobile_ad_banner" data-multi-size="320x50" class="dashedborder" sticky></amp-ad>', - '<amp-ad width="480" height="75" type="doubleclick" data-slot="/4119129/mobile_ad_banner" data-multi-size="320x50" class="dashedborder" sticky></amp-ad>', - [ 'amp-ad' ], - ], - - // Try to test for NAME_DISPATCH. - 'nav_dispatch_key' => [ - '<nav><a href="https://example.com">Example</a></nav>', - null, - ], - - 'json_linked_data' => [ - '<script type="application/ld+json">{"@context":"http:\/\/schema.org"}</script>', - null, // No Change. - ], - - 'json_linked_data_with_bad_cdata' => [ - '<script type="application/ld+json"><!-- {"@context":"http:\/\/schema.org"} --></script>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_CDATA_HTML_COMMENTS ], - ], - - 'facebook' => [ - '<amp-facebook width="552" height="303" layout="responsive" data-href="https://www.facebook.com/zuck/posts/10102593740125791"></amp-facebook><h1>More Posts</h1>', - '<amp-facebook width="552" height="303" layout="responsive" data-href="https://www.facebook.com/zuck/posts/10102593740125791"></amp-facebook><h1>More Posts</h1>', - [ 'amp-facebook' ], - ], - - 'font' => [ - '<amp-font layout="nodisplay" font-family="Comic AMP" timeout="2000"></amp-font><amp-font layout="nodisplay" font-family="Comic AMP Bold" timeout="3000" font-weight="bold"></amp-font>', - '<amp-font layout="nodisplay" font-family="Comic AMP" timeout="2000"></amp-font><amp-font layout="nodisplay" font-family="Comic AMP Bold" timeout="3000" font-weight="bold"></amp-font>', - [ 'amp-font' ], - ], - - 'form' => [ - ' - <form method="get" action="/form/search-html/get" target="_blank"> - <fieldset> - <label><span>Search for</span><input type="search" placeholder="test" name="term" required></label> - <input type="checkbox" checked disabled readonly> - <input type="checkbox" checked="CHECKED" disabled="disabled" readonly=""> - <input type="submit" value="Search" enterkeyhint="search"><input type="button" value="Open Lightbox" on="tap:lb1.open"> - </fieldset> - </form> - ', - null, - [ 'amp-form' ], - ], - - 'scripts-gathered-from-invalid-parents' => [ - ' - <ancestor-unknown> - <amp-audio src="https://example.com/foo.mp3" width="100" height="200"></amp-audio> - <parent-unknown> - <amp-form> - <form method="GET" id="a_string" class="a_string" action="https://example.com" target="_blank"> - <unrecognized>who are you?</unrecognized> - <input type=text value="test" name="hello"> - </form> - </amp-form> - </parent-unknown> - <amp-video src="https://example.com/foo.mp4" width="100" height="200"></amp-video> - </ancestor-unknown> - ', - ' - <amp-audio src="https://example.com/foo.mp3" width="100" height="200"></amp-audio> - <form method="GET" id="a_string" class="a_string" action="https://example.com" target="_blank"> - who are you? - <input type="text" value="test" name="hello"> - </form> - <amp-video src="https://example.com/foo.mp4" width="100" height="200"></amp-video> - ', - [ 'amp-audio', 'amp-form', 'amp-video' ], - array_fill( 0, 4, AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ), - ], - - 'form-visible-when-invalid' => [ - ' - <form method="post" - action-xhr="https://example.com/subscribe" - custom-validation-reporting="show-all-on-submit" target="_blank"> - <fieldset> - <label> - <span>Name:</span> - <input type="text" - name="name" - id="name5" - required - pattern="\w+\s\w+"> - <span visible-when-invalid="valueMissing" - validation-for="name5"></span> - <span visible-when-invalid="patternMismatch" - validation-for="name5"> - Please enter your first and last name separated by a space (e.g. Jane Miller) - </span> - </label> - <br> - <label> - <span>Email:</span> - <input type="email" - name="email" - id="email5" - required> - <span visible-when-invalid="valueMissing" - validation-for="email5"></span> - <span visible-when-invalid="typeMismatch" - validation-for="email5"></span> - </label> - <br> - <input type="submit" - value="Subscribe"> - </fieldset> - <input type="image" name="img" src="https://example.com/image.png" width="10" height="30"> - </form> - ', - null, - [ 'amp-form' ], - ], - - 'gfycat' => [ - '<amp-gfycat data-gfyid="BareSecondaryFlamingo" width="225" height="400"></amp-gfycat>', - '<amp-gfycat data-gfyid="BareSecondaryFlamingo" width="225" height="400"></amp-gfycat>', - [ 'amp-gfycat' ], - ], - - 'h2' => [ - '<h2>Example Text</h2>', - ], - - 'empty_element' => [ - '<br>', - ], - - 'merge_two_attr_specs' => [ - '<div submit-success>Whatever</div>', - '<div>Whatever</div>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'attribute_value_disallowed_by_regex_removed' => [ - '<a href="__amp_source_origin">Click me.</a>', - '<a>Click me.</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_DISALLOWED_VALUE_REGEX ], - ], - - 'host_relative_url_allowed' => [ - '<a href="/path/to/content">Click me.</a>', - ], - - 'protocol_relative_url_allowed' => [ - '<a href="//example.com/path/to/content">Click me.</a>', - ], - - 'node_with_allowlisted_protocol_http_allowed' => [ - '<a href="http://example.com/path/to/content">Click me.</a>', - ], - - 'node_with_allowlisted_protocol_https_allowed' => [ - '<a href="https://example.com/path/to/content">Click me.</a>', - ], - - 'node_with_allowlisted_protocol_other_allowed' => [ - implode( - '', - [ - '<a href="fb-messenger://example.com/path/to/content">Click me.</a>', - '<a href="webcal:foo">Click me.</a>', - '<a href="whatsapp:foo">Click me.</a>', - '<a href="web+mastodon:follow/@handle@instance">Click me.</a>', - '<a href="feed://blog.amp.dev/feed/" type="application/rss+xml">Click me.</a>', - ] - ), - ], - - 'node_with_non_parseable_url_removed' => [ - '<a href="http://foo@">Invalid Link</a>', - '<a>Invalid Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL ], - ], - - 'node_with_non_parseable_url_leftovers_cleaned_up' => [ - '<a id="this-is-kept" href="http://foo@" target="_blank" download rel="nofollow" rev="nofollow" hreflang="en" type="text/html" class="this-stays">Invalid Link</a>', - '<a id="this-is-kept" class="this-stays">Invalid Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL ], - ], - - 'attribute_value_valid' => [ - '<template type="amp-mustache">Hello {{world}}! <a href="{{user_url}}" title="{{user_name}}">Homepage</a> User content: {{{some_formatting}}} A guy with Mustache: :-{). {{#returning}}Welcome back!{{/returning}} {{^returning}}Welcome for the first time!{{/returning}} </template>', - null, - [ 'amp-mustache' ], - ], - - 'attribute_value_invalid' => [ - // type is mandatory, so the node is removed. - '<template type="bad-type">Template Data</template>', - '', - [], // No scripts because removed. - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE, - 'node_name' => 'type', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'node_name' => 'template', - ], - ], - ], - - 'attribute_requirements_overridden_by_placeholders_within_mustache_template' => [ - '<template type="amp-mustache"><amp-timeago datetime="{{iso}}" width="100" height="100"></amp-timeago></template>', - null, - [ 'amp-mustache', 'amp-timeago' ], - ], - - 'attribute_requirements_overridden_by_placeholders_within_mustache_script' => [ - '<script template="amp-mustache" type="text/plain"><amp-timeago datetime="{{iso}}" width="100" height="100"></amp-timeago></script>', - null, - [ 'amp-mustache', 'amp-timeago' ], - ], - - 'attribute_requirements_overriden_by_placeholders_within_template_newlines' => [ - "<template type=\"amp-mustache\"><amp-timeago datetime=\"first-line\n{{iso}}\" width=\"100\" height=\"100\"></amp-timeago></template>", - null, - [ 'amp-mustache', 'amp-timeago' ], - ], - - 'attribute_requirements_not_overriden_by_placeholders_outside_of_template' => [ - '<amp-timeago datetime="{{iso}}" width="100" height="100"></amp-timeago>', - '', - [], - [ - AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX, - AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - ], - ], - - 'attribute_requirements_overriden_in_indirect_template_parents' => [ - '<template type="amp-mustache"><div><span><amp-timeago datetime="{{iso}}" width="100" height="100"></amp-timeago></span></div></template>', - null, - [ 'amp-mustache', 'amp-timeago' ], - ], - - 'attribute_requirements_not_overriden_in_sibling_template_tags' => [ - '<template type="amp-mustache"></template><amp-timeago datetime="{{iso}}" width="100" height="100"></amp-timeago>', - '<template type="amp-mustache"></template>', - [ 'amp-mustache' ], - [ - AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX, - AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - ], - ], - - 'attribute_amp_accordion_value' => call_user_func( - static function() { - $html = str_replace( - [ "\n", "\t" ], - '', - ' - <amp-accordion class="sample" disable-session-states=""> - ok - <section expanded> - <h4>Section 1</h4> - <p>Bunch of awesome content.</p> - </section> - <section access-hide> - <h4>Section 2</h4> - <div>Bunch of even more awesome content. This time in a <code><div></code>.</div> - </section> - <section> - <h4>Section 3</h4> - <figure> - <amp-img src="/img/clean-1.jpg" layout="intrinsic" width="400" height="710"></amp-img> - <figcaption>Images work as well.</figcaption> - </figure> - </section> - ok - </amp-accordion> - ' - ); - - return [ - $html, - null, // No change. - [ 'amp-accordion' ], - ]; - } - ), - - 'attribute_value_with_disallowed_regex_removed' => [ - '<a rel="import">Click me.</a>', - '<a>Click me.</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_DISALLOWED_VALUE_REGEX ], - ], - - 'attribute_value_with_disallowed_multi-part_regex_removed' => [ - '<a rel="something else import">Click me.</a>', - '<a>Click me.</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_DISALLOWED_VALUE_REGEX ], - ], - - 'attribute_value_with_required_regex' => [ - '<a target="_blank">Click me.</a>', - ], - - 'attribute_value_with_disallowed_required_regex_removed' => [ - '<a target="_not_blank">Click me.</a>', - '<a>Click me.</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE ], - ], - - 'attribute_value_with_required_value_casei_lower' => [ - '<a type="text/html">Click.me.</a>', - ], - - 'attribute_value_with_required_value_casei_upper' => [ - '<a type="TEXT/HTML">Click.me.</a>', - ], - - 'attribute_value_with_required_value_casei_mixed' => [ - '<a type="TeXt/HtMl">Click.me.</a>', - ], - - 'attribute_value_with_bad_value_casei_removed' => [ - '<a type="bad_type">Click.me.</a>', - '<a>Click.me.</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_CASEI ], - ], - - 'attribute_value_with_value_regex_casei_lower' => [ - '<amp-dailymotion data-videoid="abc" width="100" height="100"></amp-dailymotion>', - null, // No change. - [ 'amp-dailymotion' ], - ], - - 'attribute_value_with_value_regex_casei_upper' => [ - '<amp-dailymotion data-videoid="ABC" width="100" height="100"></amp-dailymotion>', - null, // No change. - [ 'amp-dailymotion' ], - ], - - 'attribute_value_with_bad_value_regex_casei_removed' => [ - // data-ui-logo should be true|false. - '<amp-dailymotion data-videoid="123" data-ui-logo="maybe" width="100" height="100"></amp-dailymotion>', - '<amp-dailymotion data-videoid="123" width="100" height="100"></amp-dailymotion>', - [ 'amp-dailymotion' ], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE ], - ], - - 'attribute_bad_attr_with_no_value_removed' => [ - '<amp-ad type="adsense" bad-attr-no-value width="100" height="100"><div fallback>something here</div></amp-ad>', - '<amp-ad type="adsense" width="100" height="100"><div fallback>something here</div></amp-ad>', - [ 'amp-ad' ], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'attribute_bad_attr_with_value_removed' => [ - '<amp-ad type="adsense" bad-attr="some-value" width="100" height="100">something here</amp-ad>', - '<amp-ad type="adsense" width="100" height="100">something here</amp-ad>', - [ 'amp-ad' ], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'remove_node_with_invalid_mandatory_attribute' => [ - // script only allows application/json, nothing else. - '<script type="type/javascript">console.log()</script>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'remove_node_without_mandatory_attribute' => [ - '<script>console.log()</script>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'remove_amp_list_no_mandatory_anyof_attribute' => [ - '<amp-list width="400" height="400"></amp-list>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MANDATORY_ANYOF_ATTR_MISSING, - 'mandatory_anyof_attrs' => [ - 'data-amp-bind-src', - 'src', - ], - ], - ], - ], - - 'allow_amp_list_two_mandatory_anyof_attrs' => [ - '<amp-list src="https://foo.com" data-amp-bind-src="https://baz.com" width="400" height="400"></amp-list>', - null, - [ 'amp-bind', 'amp-list' ], - ], - - 'remove_amp_iframe_no_mandatory_oneof_attr' => [ - '<amp-iframe width="200" height="100"></amp-iframe>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MANDATORY_ONEOF_ATTR_MISSING ], - ], - - 'remove_amp_iframe_two_mandatory_oneof_attrs' => [ - '<amp-iframe src="https://example.com" srcdoc="https://foo.com" width="200" height="100"></amp-iframe>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DUPLICATE_ONEOF_ATTRS, - 'duplicate_oneof_attrs' => [ - 'src', - 'srcdoc', - ], - ], - ], - ], - - 'allow_amp_iframe_one_mandatory_oneof_attr' => [ - '<amp-iframe srcdoc="https://foo.com" width="200" height="100"></amp-iframe>', - null, - [ 'amp-iframe' ], - ], - - 'remove_script_with_async_attribute' => [ - '<script async src="//cdn.someecards.com/assets/embed/embed-v1.07.min.js" charset="utf-8"></script>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'remove_invalid_json_script' => [ - '<script type="application/json" class="wp-playlist-script">{}</script>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'allow_node_with_valid_mandatory_attribute' => [ - '<amp-analytics><script type="application/json">{"vars": {"apid": "XXXX"}}</script></amp-analytics>', - null, // No change. - [ 'amp-analytics' ], - ], - - 'nodes_with_non_allowlisted_tags_replaced_by_children' => [ - '<invalid_tag>this is some text inside the invalid node</invalid_tag>', - 'this is some text inside the invalid node', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'empty_parent_nodes_of_non_allowlisted_tags_removed' => [ - '<div><span><span><invalid_tag></invalid_tag></span></span></div>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'non_empty_parent_nodes_of_non_allowlisted_tags_removed' => [ - '<div><span><span class="not-empty"><invalid_tag></invalid_tag></span></span></div>', - '<div><span><span class="not-empty"></span></span></div>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'replace_non_allowlisted_node_with_children' => [ - '<p>This is some text <invalid_tag>with a disallowed tag</invalid_tag> in the middle of it.</p>', - '<p>This is some text with a disallowed tag in the middle of it.</p>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'remove_attribute_on_node_with_missing_mandatory_parent' => [ - '<div submit-success>This is a test.</div>', - '<div>This is a test.</div>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'leave_attribute_on_node_with_present_mandatory_parent' => [ - '<form action-xhr="form.php" method="post" target="_top"><div submit-success>This is a test.</div></form>', - null, - [ 'amp-form' ], - ], - - 'disallowed_empty_attr_removed' => [ - '<amp-user-notification data-dismiss-href layout="nodisplay"></amp-user-notification>', - '<amp-user-notification layout="nodisplay"></amp-user-notification>', - [ 'amp-user-notification' ], - [ AMP_Tag_And_Attribute_Sanitizer::MISSING_URL ], - ], - - 'allowed_empty_attr' => [ - '<a border=""></a>', - ], - - 'remove_node_with_disallowed_ancestor_and_disallowed_child_nodes' => [ - '<amp-sidebar layout="nodisplay"><amp-app-banner>This node is not allowed here.</amp-app-banner><nav><ul><li>Hello</li></ul><ol><li>Hello</li></ol></nav><amp-app-banner>This node is not allowed here.</amp-app-banner></amp-sidebar>', - '<amp-sidebar layout="nodisplay"><nav><ul><li>Hello</li></ul><ol><li>Hello</li></ol></nav></amp-sidebar>', - [ 'amp-sidebar' ], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::WRONG_PARENT_TAG, - 'node_name' => 'amp-app-banner', - 'spec_name' => 'amp-app-banner', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::WRONG_PARENT_TAG, - 'node_name' => 'amp-app-banner', - 'spec_name' => 'amp-app-banner', - ], - ], - ], - - 'amp_story_with_amp_sidebar' => [ - str_replace( - [ "\n", "\t" ], - '', - ' - <amp-story standalone="standalone" title="Stories in AMP - Hello World" publisher="AMP Project" publisher-logo-src="https://ampbyexample.com/favicons/coast-228x228.png" poster-portrait-src="https://ampbyexample.com/img/story_dog2_portrait.jpg"> - <amp-sidebar id="sidebar1" layout="nodisplay"> - <ul> - <li><a href="https://www.ampproject.org"> External Link </a></li> - <li>Nav item 2</li> - <li>Nav item 3</li> - </ul> - </amp-sidebar> - <amp-story-page id="cover"> - <amp-story-grid-layer template="fill"> - <h1>Hello World</h1> - <p>This is the cover page of this story.</p> - </amp-story-grid-layer> - </amp-story-page> - </amp-story> - ' - ), - null, - [ 'amp-sidebar', 'amp-story' ], - ], - - 'amp_sidebar_with_autoscroll' => [ - str_replace( - [ "\n", "\t" ], - '', - ' - <amp-sidebar id="sidebar1" layout="nodisplay" side="right"> - <nav toolbar="(max-width: 767px)" toolbar-target="target-element"> - <ul> - <li>Nav item 1</li> - <li>Nav item 2</li> - <li>Nav item 3</li> - <li autoscroll class="currentPage">Nav item 4</li> - <li>Nav item 5</li> - <li>Nav item 6</li> - </ul> - </nav> - </amp-sidebar> - <div id="target-element"></div> - ' - ), - null, - [ 'amp-sidebar' ], - ], - - 'amp_sidebar_inside_and_outside_div' => [ - ' - <amp-sidebar id="mobile-sidebar" layout="nodisplay" side="left"> - <nav><a href="/">Home!</a></nav> - </amp-sidebar> - <div> - <amp-sidebar id="mobile-sidebar" layout="nodisplay" side="right"> - <nav> - <ul> - <li><a href="https://example.com/"></a></li> - </ul> - <div class="some-div"> - ... - </div> - </nav> - </amp-sidebar> - </div> - ', - null, - [ 'amp-sidebar' ], - ], - - 'remove_node_without_mandatory_ancestor' => [ - '<div>All I have is this div, when all you want is a noscript tag.<audio>Sweet tunes</audio></div>', - '<div>All I have is this div, when all you want is a noscript tag.</div>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MANDATORY_TAG_ANCESTOR ], - ], - - 'amp-img_with_good_protocols' => [ - '<amp-img src="https://example.com/resource1" srcset="https://example.com/resource1 320w, https://example.com/resource2 480w" width="100" height="100"></amp-img>', - ], - - 'amp-img_with_relative_urls_containing_colons' => [ - '<amp-img src="/winning:yes.jpg" width="100" height="200"></amp-img>', - ], - - 'allowed_tag_only' => [ - '<p>Text</p><video src="/path/to/file.jpg"></video>', - '<p>Text</p>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MANDATORY_TAG_ANCESTOR ], - ], - - 'disallowed_attributes' => [ - '<a href="/path/to/file.jpg" color="red">Link</a>', - '<a href="/path/to/file.jpg">Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'onclick_attribute' => [ - '<a href="/path/to/file.jpg" onclick="alert(e);">Link</a>', - '<a href="/path/to/file.jpg">Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'on_attribute' => [ - '<button on="tap:my-lightbox">Tap Me</button>', - ], - - 'multiple_disallowed_attributes' => [ - '<a href="/path/to/file.jpg" color="red" onclick="alert(e);">Link</a>', - '<a href="/path/to/file.jpg">Link</a>', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'node_name' => 'color', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'node_name' => 'onclick', - ], - ], - ], - - 'attribute_recursive' => [ - '<div color="red"><a href="/path/to/file.jpg" onclick="alert(e);">Hello World</a></div>', - '<div><a href="/path/to/file.jpg">Hello World</a></div>', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'node_name' => 'onclick', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'node_name' => 'color', - ], - ], - ], - - 'no_strip_amp_tags' => [ - '<amp-img src="http://example.com/path/to/file.jpg" width="300" height="300"></amp-img>', - ], - - 'a_with_attachment_rel' => [ - '<a href="http://example.com" rel="wp-att-1686">Link</a>', - ], - - 'a_with_invalid_name' => [ - '<a name=shadowRoot>Shadow Root!</a>', - '<a>Shadow Root!</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_DISALLOWED_VALUE_REGEX ], - ], - - 'a_with_attachment_rel_plus_another_valid_value' => [ - '<a href="http://example.com" rel="attachment wp-att-1686">Link</a>', - ], - - 'a_with_rev' => [ - '<a href="http://example.com" rev="footnote">Link</a>', - ], - - 'a_with_target_blank' => [ - '<a href="http://example.com" target="_blank">Link</a>', - ], - - 'a_with_target_uppercase_blank' => [ - '<a href="http://example.com" target="_BLANK">Link</a>', - '<a href="http://example.com">Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE ], - ], - - 'a_with_target_new' => [ - '<a href="http://example.com" target="_new">Link</a>', - '<a href="http://example.com">Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE ], - ], - - 'a_with_target_self' => [ - '<a href="http://example.com" target="_self">Link</a>', - ], - - 'a_with_target_invalid' => [ - '<a href="http://example.com" target="boom">Link</a>', - '<a href="http://example.com">Link</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE ], - ], - - 'a_with_href_invalid' => [ - '<a href="some%20random%20text">Link</a>', - ], - - 'a_with_href_scheme_tel' => [ - '<a href="tel:4166669999">Call Me, Maybe</a>', - ], - - 'a_with_href_scheme_sms' => [ - '<a href="sms:4166669999">SMS Me, Maybe</a>', - ], - - 'a_with_href_scheme_mailto' => [ - '<a href="mailto:email@example.com">Email Me, Maybe</a>', - ], - - 'a_with_href_relative' => [ - '<a href="/home">Home</a>', - ], - - 'a_with_anchor' => [ - '<a href="#section2">Home</a>', - ], - - 'a_is_anchor' => [ - '<a name="section2"></a>', - ], - - 'a_is_achor_with_id' => [ - '<a id="section3"></a>', - ], - - 'a_empty' => [ - '<a>Hello World</a>', - ], - - 'a_empty_with_children_with_restricted_attributes' => [ - '<a><span color="red">Red</span>&<span color="orange">Orange</span></a>', - '<a><span>Red</span>&<span>Orange</span></a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'spans_with_xml_namespaced_attributes' => [ - '<p><span lang="es" xml:lang="es">hola</span><span xml:space="preserve">mundo</span></p>', - '<p><span lang="es">hola</span><span>mundo</span></p>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'h1_with_size' => [ - '<h1 size="1">Headline</h1>', - '<h1>Headline</h1>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'font_tag' => [ - '<font size="1">Headline</font>', - 'Headline', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'span_with_custom_attr' => [ - '<span class="foo" custom="not-allowed">value</span>', - '<span class="foo">value</span>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'a_with_custom_protocol' => [ - '<a class="foo" href="custom:bad">value</a>', - '<a class="foo">value</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL_PROTOCOL ], - ], - - 'a_with_wrong_host' => [ - '<a class="foo" href="http://foo bar">value</a>', - '<a class="foo">value</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL ], - ], - 'a_with_encoded_host' => [ - '<a class="foo" href="http://%65%78%61%6d%70%6c%65%2e%63%6f%6d/foo/">value</a>', - null, - ], - 'a_with_wrong_schemeless_host' => [ - '<a class="foo" href="//bad domain with a space.com/foo">value</a>', - '<a class="foo">value</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL ], - ], - 'a_with_valid_mail_host' => [ - '<a class="foo" href="mailto:foo@bar.com&body=https://example.org/">value</a>', - null, - ], - - // font is removed so we should check that other elements are checked as well. - 'font_with_other_bad_elements' => [ - '<font size="1">Headline</font><span color="blue">Span</span>', - 'Headline<span>Span</span>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'amp_bind_attr' => [ - '<p [text]="\'Hello \' + foo">Hello World</p><button on="tap:AMP.setState({foo: \'amp-bind\'})">Update</button>', - '<p data-amp-bind-text="\'Hello \' + foo">Hello World</p><button on="tap:AMP.setState({foo: \'amp-bind\'})">Update</button>', - [ 'amp-bind' ], - ], - - 'data_amp_bind_attr' => [ - '<p data-amp-bind-text="\'Hello \' + foo">Hello World</p><button on="tap:AMP.setState({foo: \'amp-bind\'})">Update</button>', - null, - [ 'amp-bind' ], - ], - - 'amp_bind_with_greater_than_symbol' => [ - '<div class="home page-template-default page page-id-7 logged-in wp-custom-logo group-blog" [class]="minnow.bodyClasses.concat( minnow.navMenuExpanded ? \'sidebar-open\' : \'\' ).filter( className => \'\' != className )">hello</div>', - '<div class="home page-template-default page page-id-7 logged-in wp-custom-logo group-blog" data-amp-bind-class="minnow.bodyClasses.concat( minnow.navMenuExpanded ? \'sidebar-open\' : \'\' ).filter( className => \'\' != className )">hello</div>', - [ 'amp-bind' ], - ], - - 'amp_bad_bind_attr' => [ - '<a [href]=\'/\' [hidden]>test</a><p [text]="\'Hello \' + name" [unrecognized] title="Foo"><button [disabled]="" [type]=\'\'>Hello World</button></p>', - '<a data-amp-bind-href="/" data-amp-bind-hidden>test</a><p data-amp-bind-text="\'Hello \' + name" title="Foo"><button data-amp-bind-disabled="" data-amp-bind-type="">Hello World</button></p>', - [ 'amp-bind' ], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'node_name' => 'data-amp-bind-unrecognized', - ], - ], - ], - - 'amp-state' => [ - '<amp-state id="someNumber"><script type="application/json">4</script></amp-state>', - null, - [ 'amp-bind' ], - ], - - 'amp-state-bad' => [ - '<amp-state id="someNumber"><i>bad</i><script type="application/json">4</script></amp-state>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_FIRST_CHILD_TAG, - 'first_child_tag' => 'i', - ], - ], - ], - - 'amp-state-src' => [ - '<amp-state id="myRemoteState" src="https://data.com/articles.json"></amp-state>', - null, - [ 'amp-bind' ], - ], - - // Adapted from <https://www.ampproject.org/docs/reference/components/amp-selector>. - 'reference-points-amp_selector_and_carousel_with_boolean_attributes' => [ - str_replace( - [ "\n", "\t" ], - '', - ' - <form action="/" method="get" target="_blank" id="form1"> - <amp-selector layout="container" name="single_image_select"> - <ul> - <li> - <amp-img src="/img1.png" width="50" height="50" option="1"></amp-img> - </li> - <li> - <amp-img src="/img2.png" width="50" height="50" option="2" disabled></amp-img> - </li> - <li> - <amp-img src="/img3.png" width="50" height="50" option="2" disabled="disabled"></amp-img> - </li> - <li option="na" selected>None of the Above</li> - </ul> - </amp-selector> - <amp-selector layout="container" name="multi_image_select" multiple> - <amp-img src="/img1.png" width="50" height="50" option="1"></amp-img> - <amp-img src="/img2.png" width="50" height="50" option="2"></amp-img> - <amp-img src="/img3.png" width="50" height="50" option="3"></amp-img> - </amp-selector> - <amp-selector layout="container" name="multi_image_select_1" multiple> - <amp-carousel id="carousel-1" width="200" height="60" controls> - <amp-img src="/img1.png" width="80" height="60" option="a"></amp-img> - <amp-img src="/img2.png" width="80" height="60" option="b" selected></amp-img> - <amp-img src="/img3.png" width="80" height="60" option="c"></amp-img> - <amp-img src="/img4.png" width="80" height="60" option="d" disabled></amp-img> - </amp-carousel> - </amp-selector> - </form> - <amp-selector layout="container" name="multi_image_select_2" multiple form="form1"> - <amp-carousel id="carousel-1" width="400" height="300" type="slides" controls> - <amp-img src="/img1.png" width="80" height="60" option="a"></amp-img> - <amp-img src="/img2.png" width="80" height="60" option="b" selected></amp-img> - <amp-img src="/img3.png" width="80" height="60" option="c"></amp-img> - <amp-img src="/img4.png" width="80" height="60" option="d"></amp-img> - </amp-carousel> - </amp-selector> - ' - ), - null, // No change. - [ 'amp-selector', 'amp-form', 'amp-carousel' ], - ], - - 'reference-point-descendant-attr-outside-parent' => [ - '<div option="foo">Foo!</div>', - '<div>Foo!</div>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - - 'amp_live_list_sort' => [ - '<amp-live-list sort="ascending" data-poll-interval="15000" data-max-items-per-page="5" id="amp-live-list-insert-blog"><button update on="tap:amp-live-list-insert-blog.update" class="ampstart-btn ml1 caps">You have updates</button><div items><div id="A green landscape with trees." data-sort-time="20180317225019">Hello</div></div></amp-live-list>', - null, // No change. - [ 'amp-live-list' ], - ], - - 'amp_consent' => [ - '<amp-consent media="all" noloading layout="nodisplay"></amp-consent>', - null, // No change. - [ 'amp-consent' ], - ], - - 'amp_date_picker' => [ - '<amp-date-picker id="simple-date-picker" type="single" mode="overlay" layout="container" on="select:AMP.setState({date1: event.date, dateType1: event.id})" format="Y-MM-DD" open-after-select input-selector="[name=date1]" class="mr1 ml1 flex picker" hide-keyboard-shortcuts-panel><div class="ampstart-input inline-block mt1"><input class="border-none p0" name="date1" placeholder="Pick a date"></div><button class="ampstart-btn m1 caps" on="tap: simple-date-picker.clear">Clear</button></amp-date-picker>', - null, // No change. - [ 'amp-date-picker' ], - ], - - 'amp_date_picker_range' => [ - '<amp-date-picker type="range" minimum-nights="2" maximum-nights="4" mode="overlay" id="range-date-picker" on=" select: AMP.setState({ dates: event.dates, startDate: event.start, endDate: event.end })" format="YYYY-MM-DD" open-after-select min="2017-10-26" start-input-selector="#range-start" end-input-selector="#range-end" class="example-picker space-between"><div class="ampstart-input"><input class="border-none p0" id="range-start" placeholder="Start date"></div><div class="ampstart-input"><input class="border-none p0" id="range-end" placeholder="End date"></div><button class="ampstart-btn caps" on="tap:range-date-picker.clear">Clear</button><template type="amp-mustache" info-template><span [text]="(startDate && endDate ? \'You picked \' + startDate.date + \' as start date and \' + endDate.date + \' as end date.\' : \'You will see your chosen dates here.\')"> You will see your chosen dates here.</span></template></amp-date-picker>', - '<amp-date-picker type="range" minimum-nights="2" maximum-nights="4" mode="overlay" id="range-date-picker" on=" select: AMP.setState({ dates: event.dates, startDate: event.start, endDate: event.end })" format="YYYY-MM-DD" open-after-select min="2017-10-26" start-input-selector="#range-start" end-input-selector="#range-end" class="example-picker space-between"><div class="ampstart-input"><input class="border-none p0" id="range-start" placeholder="Start date"></div><div class="ampstart-input"><input class="border-none p0" id="range-end" placeholder="End date"></div><button class="ampstart-btn caps" on="tap:range-date-picker.clear">Clear</button><template type="amp-mustache" info-template><span data-amp-bind-text="(startDate && endDate ? \'You picked \' + startDate.date + \' as start date and \' + endDate.date + \' as end date.\' : \'You will see your chosen dates here.\')"> You will see your chosen dates here.</span></template></amp-date-picker>', - [ 'amp-date-picker', 'amp-bind', 'amp-mustache' ], - ], - - 'amp-delight-player' => [ - '<amp-delight-player data-content-id="-987521" layout="responsive" width="400" height="300"></amp-delight-player>', - null, // No change. - [ 'amp-delight-player' ], - ], - - 'amp-img-layout-allowed' => [ - implode( - '', - [ - '<amp-img src="/img1.png" width="50" height="50" layout="fill"></amp-img>', - '<amp-img src="/img1.png" width="50" height="50" layout="fixed"></amp-img>', - '<amp-img src="/img1.png" width="auto" height="50" layout="fixed-height"></amp-img>', - '<amp-img src="/img1.png" width="50" height="50" layout="flex-item"></amp-img>', - '<amp-img src="/img1.png" width="50" height="50" layout="intrinsic"></amp-img>', - '<amp-img src="/img1.png" width="50" height="50" layout="nodisplay"></amp-img>', - '<amp-img src="/img1.png" width="50" height="50" layout="responsive"></amp-img>', - ] - ), - null, // No change. - [], - ], - - 'amp-img-layout-illegal' => [ - '<amp-img src="/img1.png" width="50" height="50" layout="container"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::SPECIFIED_LAYOUT_INVALID ], - ], - - 'amp-img-layout-unknown' => [ - '<amp-img src="/img1.png" width="50" height="50" layout="bogus-value"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::SPECIFIED_LAYOUT_INVALID ], - ], - - 'non-layout-span-element-attrs' => [ - '<span id="test" width="1" height="1" heights="(min-width:500px) 200px, 80%" sizes="(min-width: 650px) 50vw, 100vw" layout="nodisplay" [height]="1" [width]="1">Test</span>', - '<span id="test">Test</span>', - [], - array_fill( 0, 7, AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ), - ], - - 'non-layout-col-element-attrs' => [ - '<table><col class="foo" width="123" color="red"><col class="bar" color="green" width="12%"><col class="baz" color="blue" width="2*"><tr><td>1</td><td>2</td><td>3</td></tr></table>', - '<table><col class="foo"><col class="bar"><col class="baz"><tr><td>1</td><td>2</td><td>3</td></tr></table>', - [], - [ - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - ], - ], - - 'amp-geo' => [ - '<amp-geo layout="nodisplay"><script type="application/json">{ "AmpBind": true, "ISOCountryGroups": { "nafta": [ "ca", "mx", "us", "unknown" ], "waldo": [ "unknown" ], "anz": [ "au", "nz" ] } }</script></amp-geo>', - null, - [ 'amp-geo' ], - ], - - 'amp-geo-bad-children' => [ - '<amp-geo layout="nodisplay"><div>bad</div><script type="application/json">{ "AmpBind": true, "ISOCountryGroups": { "nafta": [ "ca", "mx", "us", "unknown" ], "waldo": [ "unknown" ], "anz": [ "au", "nz" ] } }</script></amp-geo>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_FIRST_CHILD_TAG ], - ], - - 'amp-addthis-valid' => [ - ' - <amp-addthis - width="320" - height="92" - data-pub-id="ra-59c2c366435ef478" - data-widget-id="0fyg"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-responsive-layout' => [ - ' - <amp-addthis - width="320" - height="92" - layout="responsive" - data-pub-id="ra-59c3d23bf51957fd" - data-widget-id="o2x1"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-custom-share-attributes' => [ - ' - <amp-addthis - width="320" - height="92" - data-pub-id="ra-59c2c366435ef478" - data-widget-id="0fyg" - data-share-title="This Title Will Be Shared" - data-share-url="https://www.addthis.com" - data-share-media="https://i.imgur.com/yNlQWRM.jpg" - data-share-description="This is the description that will be shared."> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-wordpress-mode' => [ - ' - <!-- AddThis WordPress Mode --> - <amp-addthis - width="320" - height="92" - data-pub-id="ra-5c1a9eed18daaf81" - data-class-name="at-above-post" - data-widget-id="g7wl"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-wordpress-mode-no-render-without-class-name' => [ - ' - <amp-addthis - width="320" - height="92" - data-pub-id="ra-5c1a9eed18daaf81" - data-class-name="" - data-widget-id="g7wl"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-inline-using-widget-id' => [ - ' - <amp-addthis - width="320" - height="92" - data-pub-id="ra-5adf5f2869f63c7c" - data-widget-id="1o1v"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-inline-using-product-code' => [ - ' - <amp-addthis - width="320" - height="92" - data-pub-id="ra-5adf5f2869f63c7c" - data-product-code="shin"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-floating-using-product-code' => [ - ' - <amp-addthis - width="320" - height="92" - data-pub-id="ra-5adf5ec1cb6be565" - data-widget-type="floating" - data-product-code="shfs"> - </amp-addthis> - ', - null, - [ 'amp-addthis' ], - ], - - 'amp-addthis-with-invalid-attribute' => [ - '<amp-addthis width="320" height="240" data-pub-id="ra-5adf5f2869f63c7c" data-product-code="shin" data-share-url="mailto:foo@example.com"></amp-addthis>', - '<amp-addthis width="320" height="240" data-pub-id="ra-5adf5f2869f63c7c" data-product-code="shin" data-share-url=""></amp-addthis>', - [ 'amp-addthis' ], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL_PROTOCOL ], - ], - - 'amp-bodymovin-animation' => [ - ' - <amp-bodymovin-animation layout="responsive" width="1920" height="1080" src="https://amp.dev/static/samples/json/bodymovin_happy_2016.json"></amp-bodymovin-animation> - <amp-bodymovin-animation layout="responsive" width="1920" height="1080" src="https://amp.dev/static/samples/json/bodymovin_happy_2016.json" loop="true" renderer="html"></amp-bodymovin-animation> - <amp-bodymovin-animation layout="responsive" width="1920" height="1080" src="https://amp.dev/static/samples/json/bodymovin_happy_2016.json" loop="false" renderer="canvas"></amp-bodymovin-animation> - <amp-bodymovin-animation layout="responsive" width="1920" height="1080" src="https://amp.dev/static/samples/json/bodymovin_happy_2016.json" loop="5" renderer="svg"></amp-bodymovin-animation> - ', - null, - [ 'amp-bodymovin-animation' ], - [], - ], - - 'amp-3d-gltf' => [ - '<amp-3d-gltf layout="responsive" width="320" height="240" alpha="true" antialiasing="true" src="path/to/model.glb"></amp-3d-gltf>', - null, - [ 'amp-3d-gltf' ], - ], - - 'amp-date-countdown' => [ - '<amp-date-countdown timestamp-seconds="2147483648" data-count-up layout="fixed-height" height="50"><template type="amp-mustache"><p class="p1"> {{d}} days, {{h}} hours, {{m}} minutes and {{s}} seconds until <a href="https://en.wikipedia.org/wiki/Year_2038_problem">Y2K38</a>.</p></template></amp-date-countdown>', - null, - [ 'amp-date-countdown', 'amp-mustache' ], - ], - - 'amp-google-document-embed' => [ - '<amp-google-document-embed src="https://www.example.com/document.pdf" width="800" height="600" layout="responsive"></amp-google-document-embed>', - null, - [ 'amp-google-document-embed' ], - ], - - 'amp-orientation-observer' => [ - '<amp-orientation-observer on="beta:clockAnim1.seekTo(percent=event.percent)" alpha-range="0 180" beta-range="0 180" gamma-range="0 90" smoothing="5" layout="nodisplay"></amp-orientation-observer>', - null, - [ 'amp-orientation-observer' ], - ], - - 'amp-pan-zoom' => [ - '<amp-layout layout="responsive" width="4" height="3"><amp-pan-zoom layout="fill" disable-double-tap><svg focusable="false"> ... </svg></amp-pan-zoom></amp-layout>', - null, - [ 'amp-pan-zoom' ], - ], - - 'amp-yotpo' => [ - '<amp-yotpo width="550" height="700" layout="responsive" data-app-key="liSBkl621ZZsb88tsckAs6Bzx6jQeTJTv8CDf8y5" data-widget-type="MainWidget" data-product-id="9408616206" data-name="hockey skates" data-url="https://ranabram.myshopify.com/products/hockey-skates" data-image-url="https://ichef.bbci.co.uk/news/320/media/images/83351000/jpg/_83351965_explorer273lincolnshirewoldssouthpicturebynicholassilkstone.jpg" data-descriptipn="skates" data-yotpo-element-id="1"></amp-yotpo>', - null, - [ 'amp-yotpo' ], - ], - - 'amp-embedly' => [ - '<amp-embedly-key value="12af2e3543ee432ca35ac30a4b4f656a" layout="nodisplay"></amp-embedly-key><amp-embedly-card data-url="https://twitter.com/AMPhtml/status/986750295077040128" layout="responsive" width="150" height="80" data-card-theme="dark" data-card-controls="0"></amp-embedly-card>', - null, - [ 'amp-embedly-card' ], - ], - - 'amp-lightbox' => [ - '<amp-lightbox id="my-lightbox" [open]="true" animate-in="fly-in-top" layout="nodisplay"><div class="lightbox" on="tap:my-lightbox.close" role="button" tabindex="0"><h1>Hello World!</h1></div></amp-lightbox>', - '<amp-lightbox id="my-lightbox" data-amp-bind-open="true" animate-in="fly-in-top" layout="nodisplay"><div class="lightbox" on="tap:my-lightbox.close" role="button" tabindex="0"><h1>Hello World!</h1></div></amp-lightbox>', - [ 'amp-lightbox', 'amp-bind' ], - ], - - 'amp-form-messages' => [ - '<form action-xhr="https://example.com/" method="post"><fieldset><input type="text" name="do-not-verify" no-verify><input type="text" name="firstName"></fieldset><div verify-error=""><template type="amp-mustache">There is a mistake in the form!{{#verifyErrors}}{{message}}{{/verifyErrors}}</template></div><div submitting=""><template type="amp-mustache">Form submitting... Thank you for waiting {{name}}.</template></div><div submit-success=""><template type="amp-mustache">Success! Thanks {{name}} for subscribing! Please make sure to check your email {{email}}to confirm! After that we\'ll start sending you weekly articles on {{#interests}}<b>{{name}}</b> {{/interests}}.</template></div><div submit-error><template type="amp-mustache">Oops! {{name}}, {{message}}.</template></div></form>', - null, - [ 'amp-form', 'amp-mustache' ], - ], - - 'amp-input-mask' => [ - '<form method="post" class="p2" action-xhr="/components/amp-inputmask/postal" target="_top"><label>Postal code: <input name="code" mask="L0L_0L0" mask-trim-zeros="3" placeholder="A1A 1A1"></label><input type="submit"><div submit-success><template type="amp-mustache"><p>You submitted: {{code}}</p></template></div></form>', - null, - [ 'amp-form', 'amp-inputmask', 'amp-mustache' ], - ], - - 'amp_textarea_without_autoexpand' => [ - '<textarea name="without-autoexpand"></textarea>', - null, - [], - ], - - 'amp_textarea_with_autoexpand_and_defaulttext' => [ - '<textarea name="with-autoexpand" autoexpand [defaulttext]="hello" [text]="goodbye">hello</textarea>', - '<textarea name="with-autoexpand" autoexpand data-amp-bind-defaulttext="hello" data-amp-bind-text="goodbye">hello</textarea>', - [ 'amp-form', 'amp-bind' ], - ], - - 'amp-viqeo-player' => [ - '<amp-viqeo-player data-profileid="184" data-videoid="b51b70cdbb06248f4438" width="640" height="360" layout="responsive"></amp-viqeo-player>', - null, - [ 'amp-viqeo-player' ], - ], - - 'amp-image-slider' => [ - '<amp-image-slider layout="responsive" width="100" height="200"><amp-img src="/green-apple.jpg" alt="A green apple" width="100" height="100"></amp-img><amp-img src="/red-apple.jpg" alt="A red apple" width="100" height="100"></amp-img><div first>This apple is green</div><div second>This apple is red</div></amp-image-slider>', - null, - [ 'amp-image-slider' ], - ], - - 'amp-image-slider-bad-children' => [ - '<amp-image-slider layout="responsive" width="100" height="200"><amp-img src="/green-apple.jpg" alt="A green apple" width="100" height="100"></amp-img></amp-image-slider>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::INCORRECT_MIN_NUM_CHILD_TAGS, - 'children_count' => 1, - ], - ], - ], - - 'amp-animation-bad-number-children' => [ - '<amp-animation layout="nodisplay"><script type="application/json">{}</script><script type="application/json">{}</script></amp-animation>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::INCORRECT_NUM_CHILD_TAGS, - 'children_count' => 2, - ], - ], - ], - - 'amp-image-slider-more-bad-children' => [ - '<amp-image-slider layout="responsive" width="100" height="200"><span>Not allowed</span><amp-img src="/green-apple.jpg" alt="A green apple" width="100" height="100"></amp-img><i>forbidden</i><amp-img src="/red-apple.jpg" alt="A red apple" width="100" height="100"></amp-img><div first>This apple is green</div><strong>not allowed</strong><div second>This apple is red</div><i>not</i> <span>ok</span></amp-image-slider>', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_CHILD_TAG, - 'child_tag' => 'span', - ], - ], - ], - - 'amp-fx-collection' => [ - '<h1 amp-fx="parallax" data-parallax-factor="1.5">A title that moves faster than other content.</h1>', - null, - [ 'amp-fx-collection' ], - ], - - 'amp-date-display' => [ - '<amp-date-display datetime="2017-08-02T15:05:05.000" layout="fixed" width="360" height="20"><template type="amp-mustache"><div>{{dayName}} {{day}} {{monthName}} {{year}} {{hourTwoDigit}}:{{minuteTwoDigit}}:{{secondTwoDigit}}</div></template></amp-date-display>', - null, - [ 'amp-date-display', 'amp-mustache' ], - ], - - 'amp_date_display_template' => [ - ' - <amp-date-display template="dateTime" locale="pt-br" datetime="now" layout="flex-item"> </amp-date-display> - <template type="amp-mustache" id="dateTime"> - {{day}} de {{monthName}} {{year}}<small class="fg-muted block">{{hourTwoDigit}}:{{minuteTwoDigit}}</small> - </template> - ', - null, // No change. - [ 'amp-date-display', 'amp-mustache' ], - ], - - 'amp-list' => [ - '<amp-list credentials="include" src="https://example.com/json/product.json?clientId=CLIENT_ID(myCookieId)" width="100" height="100"><template type="amp-mustache">Your personal offer: ${{price}}</template></amp-list>', - null, - [ 'amp-list', 'amp-mustache' ], - ], - - 'amp-list-amp-script' => [ - ' - <amp-script id="dataFunctions" script="local-script" nodom></amp-script> - <script id="local-script" type="text/plain" target="amp-script"> - function getRemoteData() { /*...*/ } - exportFunction(\'getRemoteData\', getRemoteData); - </script> - - <amp-list - id="amp-list" - width="auto" - height="100" - layout="fixed-height" - src="amp-script:dataFunctions.getRemoteData"> - <template type="amp-mustache"> - <div>{{.}}</div> - </template> - </amp-list> - ', - null, - [ 'amp-list', 'amp-mustache', 'amp-script' ], - ], - - 'amp-list-load-more' => [ - str_replace( - [ "\n", "\t" ], - '', - ' - <amp-list load-more="auto" src="https://www.load.more.example.com/" width="400" height="800" xssi-prefix=")]}\'"> - <amp-list-load-more load-more-button> - <template type="amp-mustache"> - Showing {{#count}} out of {{#total}} items - <button>Click here to see more!</button> - </template> - </amp-list-load-more> - <amp-list-load-more load-more-failed> - <div> - Here is some unclickable text saying sorry loading failed. - </div> - <button load-more-clickable>Click me to reload!</button> - </amp-list-load-more> - <amp-list-load-more load-more-loading> - <svg>...</svg> - </amp-list-load-more> - <amp-list-load-more load-more-failed> - <button>Unable to Load More</button> - </amp-list-load-more> - <amp-list-load-more load-more-end> - Congratulations! You reached the end. - </amp-list-load-more> - <div fetch-error align="center"> - Fetch error! - </div> - <div placeholder> - Placeholder! - </div> - <div fallback> - Fallback! - </div> - </amp-list> - ' - ), - null, - [ 'amp-list', 'amp-mustache' ], - ], - - 'amp-list-load-more-bad-buttons' => [ - ' - <amp-list load-more="auto" src="https://www.load.more.example.com/" width="400" height="800"> - <amp-list-load-more load-more-button load-more-end load-more-failed load-more-loading> - <template type="amp-mustache"> - Showing {{#count}} out of {{#total}} items - <button>Click here to see more!</button> - </template> - </amp-list-load-more> - </amp-list> - ', - '<amp-list load-more="auto" src="https://www.load.more.example.com/" width="400" height="800"></amp-list>', - [ 'amp-list' ], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DUPLICATE_ONEOF_ATTRS, - 'duplicate_oneof_attrs' => [ - 'load-more-button', - 'load-more-end', - 'load-more-failed', - 'load-more-loading', - ], - ], - ], - ], - - 'amp-recaptcha-input' => [ - '<form action-xhr="/" target="_top" method="post"><amp-recaptcha-input layout="nodisplay" name="reCAPTCHA_body_key" data-sitekey="reCAPTCHA_site_key" data-action="reCAPTCHA_example_action"></amp-recaptcha-input></form>', - null, - [ 'amp-form', 'amp-recaptcha-input' ], - ], - - 'amp-video-iframe' => [ - '<amp-video-iframe src="https://example.com/video/" width="500" height="500" poster="https://example.com/poster.jpg" autoplay dock implements-media-session implements-rotate-to-fullscreen referrerpolicy></amp-video-iframe>', - null, - [ 'amp-video-iframe', 'amp-video-docking' ], - ], - - 'amp-youtube' => [ - '<amp-youtube id="myLiveChannel" loop data-live-channelid="UCB8Kb4pxYzsDsHxzBfnid4Q" width="358" height="204" layout="responsive" dock><amp-img src="https://i.ytimg.com/vi/Wm1fWz-7nLQ/hqdefault_live.jpg" placeholder layout="fill"></amp-img></amp-youtube>', - null, - [ 'amp-youtube', 'amp-video-docking' ], - ], - - 'details' => [ - '<details open [open]="foo.state"><summary>Learn more</summary><p>You are educated</p></details>', - '<details open data-amp-bind-open="foo.state"><summary>Learn more</summary><p>You are educated</p></details>', - [ 'amp-bind' ], - ], - - 'amp-plain-text-script-template' => [ - '<script type="text/plain" template="amp-mustache">Hello {{world}}!</script>', - null, - [ 'amp-mustache' ], - ], - - 'amp-action-macro' => [ - // @todo Should calling AMP.setState() automatically cause the amp-bind extension to be added? - ' - <amp-action-macro id="closeNavigations" execute="AMP.setState({nav1: \'close\', nav2: \'close})"></amp-action-macro> - <button on="tap:closeNavigations.execute()">Close all</button> - <div on="tap:closeNavigations.execute()">Close all</div> - ', - null, - [ 'amp-action-macro' ], - ], - - 'amp-smart-links' => [ - '<amp-smartlinks layout="nodisplay" nrtv-account-name="examplepublisher" linkmate exclusive-links link-attribute="href" link-selector="a"></amp-smartlinks>', - null, - [ 'amp-smartlinks' ], - ], - - 'amp-script-1' => [ - '<amp-script layout="container" src="https://example.com/hello-world.js" sandboxed><button id="hello">Insert Hello World!</button></amp-script>', - null, - [ 'amp-script' ], - ], - 'amp-script-2' => [ - ' - <amp-script layout="container" src="https://example.com/examples/amp-script/hello-world.js"> - <div class="root"> - <button id="hello">Insert Hello World!</button> - <button id="long">Long task</button> - <button id="amp-img">Insert amp-img</button> - <button id="script">Insert <script></button> - <button id="img">Insert <img></button> - </div> - </amp-script> - ', - null, - [ 'amp-script' ], - ], - 'amp-script-3' => [ - ' - <amp-script src="https://example.com/examples/amp-script/todomvc.ssr.js" layout="container"> - <div><header class="header"><h1>todos</h1><input class="new-todo" placeholder="What needs to be done?" autofocus="true"></header></div> - </amp-script> - ', - null, - [ 'amp-script' ], - ], - - 'amp-script-4' => [ - ' - <amp-script layout="container" src="https://example.com/examples/amp-script/empty.js" max-age="3600"> - <div class="root">should be empty</div> - </amp-script> - ', - null, - [ 'amp-script' ], - ], - - 'amp-script-5' => [ - ' - <amp-script script="myScript" layout="container" data-ampdevmode></amp-script> - <script type="text/plain" target="amp-script" id="myScript"> - document.body.textContent += \'Hello world!\'; - </script> - ', - null, - [ 'amp-script' ], - ], - - 'amp-script-with-canvas' => [ - ' - <amp-script src="https://example.com/examples/amp-script/empty.js"> - <canvas width="100" height="100"></canvas> - </amp-script> - ', - null, - [ 'amp-script' ], - ], - - 'amp_img_with_object_fit_position' => [ - '<amp-img src="http://placehold.it/400x500" width="300" height="300" object-fit="none" object-position="right top" layout="intrinsic"></amp-img>', - null, - [], - ], - - 'amp_img_missing_url' => [ - '<amp-img src="" height="100" width="200"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MISSING_URL, AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING ], - ], - - 'amp_img_missing_srcset' => [ - '<amp-img srcset="" height="100" width="200"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MISSING_URL, AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING ], - ], - - 'amp_pixel_blank_src' => [ - '<amp-pixel src="" layout="nodisplay"></amp-pixel>', - null, - [], - [], - ], - - 'amp_pixel_missing_src' => [ - '<amp-pixel layout="nodisplay"></amp-pixel>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING ], - ], - - 'amp_link_rewriter' => [ - '<amp-link-rewriter layout="nodisplay"><script type="application/json">{}</script></amp-link-rewriter>', - null, - [ 'amp-link-rewriter' ], - ], - - 'unique_constraint' => [ - str_repeat( '<amp-geo layout="nodisplay"><script type="application/json">{}</script></amp-geo>', 2 ), - '<amp-geo layout="nodisplay"><script type="application/json">{}</script></amp-geo>', - [ 'amp-geo' ], - [ AMP_Tag_And_Attribute_Sanitizer::DUPLICATE_UNIQUE_TAG ], - ], - - 'amp-autocomplete' => [ - ' - <form method="post" action-xhr="/form/echo-json/post" target="_blank" on="submit-success:AMP.setState({result: event.response})"> - <amp-autocomplete id="autocomplete" filter="substring" min-characters="0" inline="@" max-items="10" prefetch> - <input type="text" id="input"> - <script type="application/json" id="script"> - { "items" : ["apple", "banana", "orange"] } - </script> - </amp-autocomplete> - </form> - <amp-autocomplete id="autocomplete2" filter="substring" min-characters="0"> - <input type="text" id="input2"> - <script type="application/json" id="script"> - { "items" : ["red", "green", "blue"] } - </script> - </amp-autocomplete> - <amp-autocomplete - filter="prefix" - src="https://example.com/articles.json?ref=CANONICAL_URL" - query="q"> - <input> - </amp-autocomplete> - ', - null, - [ 'amp-form', 'amp-autocomplete' ], - ], - - 'amp-connatix-player' => [ - '<amp-connatix-player data-player-id="03ef71d8-0941-4bff-94f2-74ca3580b497" layout="responsive" width="16" height="9"></amp-connatix-player>', - null, - [ 'amp-connatix-player' ], - ], - - 'amp-truncate-text' => [ - ' - <amp-truncate-text layout="fixed" height="3em" width="20em"> - Some text that may get truncated. - <button slot="expand">See more</button> - <button slot="collapse">See less</button> - </amp-truncate-text> - ', - null, - [ 'amp-truncate-text' ], - ], - - 'amp-megaphone' => [ - '<amp-megaphone height="166" layout="fixed-height" data-episode="OSC7749686951" data-light></amp-megaphone>', - null, - [ 'amp-megaphone' ], - ], - - 'amp-minute-media-player' => [ - '<amp-minute-media-player dock data-content-type="semantic" data-minimum-date-factor="10" data-scanned-element-type="tag" data-scanned-element="post-body" data-scoped-keywords="football" layout="responsive" width="160" height="96"></amp-minute-media-player>', - null, - [ 'amp-minute-media-player', 'amp-video-docking' ], - ], - - 'deeply_nested_elements_200' => [ - // If a DOM tree is too deep, libxml itself will issue an error: Excessive depth in document: 256 use XML_PARSE_HUGE option. - // Also, if XDebug is enabled, then max_nesting_level error is reached if call stack is >256. A nesting level of 200 is safe, - // so this tests up to that level of nesting to also ensure that the recursive \AMP_Tag_And_Attribute_Sanitizer::sanitize_element() - // method does not cause a different error at the PHP level when a recursion call stack reaches that same level. - str_repeat( '<div>', 200 ) . '<bad>hello world!</bad>' . str_repeat( '</div>', 200 ), - str_repeat( '<div>', 200 ) . 'hello world!' . str_repeat( '</div>', 200 ), - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - - 'invalid_php_pi' => [ - '<?php $schema = get_post_meta(get_the_ID(), \'schema\', true); if(!empty($schema)) { echo $schema; } ?>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROCESSING_INSTRUCTION ], - ], - - 'invalid_xml_pi' => [ - '<?xml version="1.0" encoding="utf-8"?>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROCESSING_INSTRUCTION ], - ], - - 'malformed_attribute_syntax_curly_quotes' => [ - '<a href=“%E2%80%9Chttps://example.com/path/to/post/%E2%80%9D“ target=“_blank“ rel=“noopener“>Whatever</a>', - '<a>Whatever</a>', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_URL_PROTOCOL, AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE ], - ], - - 'cdata_html_comments' => [ - '<amp-geo layout="nodisplay"><script type="application/json"><!-- not allowed --></script></amp-geo>', - '<amp-geo layout="nodisplay"></amp-geo>', - [ 'amp-geo' ], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_CDATA_HTML_COMMENTS ], - ], - - 'amp-social-share-relative-url' => [ - '<amp-social-share type="foo" data-share-endpoint="./foo/relative/" data-param-text="Check out this article: TITLE - CANONICAL_URL"></amp-social-share>', - '<amp-social-share type="foo" data-param-text="Check out this article: TITLE - CANONICAL_URL"></amp-social-share>', - [ 'amp-social-share' ], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_RELATIVE_URL ], - ], - - 'illegal_width_attribute' => [ - '<amp-img src="/img1.png" width="50%" height="50"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_WIDTH ], - ], - - 'empty_width_attribute' => [ - '<amp-img src="/img1.png" width="" height="50"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_WIDTH ], - ], - - 'empty_height_attribute' => [ - '<amp-img src="/img1.png" width="50" height=""></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_HEIGHT ], - ], - - 'variable_attributes_in_mustache_template' => [ - ' - <template type="amp-mustache"> - <div><div><div> - <amp-img src="/img1.png" width="{{width}}" height="50"></amp-img> - </div></div></div> - </template> - ', - null, - [ 'amp-mustache' ], - ], - - 'variable_attributes_in_mustache_script' => [ - ' - <script template="amp-mustache" type="text/plain"> - <div><div><div> - <amp-img src="/img1.png" width="{{width}}" height="50"></amp-img> - </div></div></div> - </script> - ', - null, - [ 'amp-mustache' ], - ], - - 'illegal_height_attribute' => [ - '<amp-img src="/img1.png" width="50" height="50%"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_HEIGHT ], - ], - - '0_width_attribute' => [ - '<amp-img src="/img1.png" width="0" height="50" layout="responsive"></amp-img>', - null, - ], - - 'empty_width_attribute_responsive_layout' => [ - '<amp-img src="/img1.png" width="auto" height="50" layout="responsive"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_AUTO_WIDTH ], - ], - - 'auto_height_attribute' => [ - '<amp-img src="/img1.png" width="50" height="auto" layout="responsive"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_AUTO_HEIGHT ], - ], - - 'no_height_fixed_layout' => [ - '<amp-img src="/img1.png" width="50" layout="fixed"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_NO_HEIGHT ], - ], - - 'no_height_fixed_height_layout' => [ - '<amp-img src="/img1.png" width="50" layout="fixed-height"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_NO_HEIGHT ], - ], - - 'no_height_intrinsic_layout' => [ - '<amp-img src="/img1.png" width="50" layout="intrinsic"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_NO_HEIGHT ], - ], - - 'no_height_responsive_layout' => [ - '<amp-img src="/img1.png" width="50" layout="responsive"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_NO_HEIGHT ], - ], - - 'static_width_fixed_height_layout' => [ - '<amp-img src="/img1.png" width="50" height="50" layout="fixed-height"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_FIXED_HEIGHT ], - ], - - 'responsive_layout_different_unit_dimensions' => [ - '<amp-img src="/img1.png" width="50px" height="50em" layout="responsive"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_UNIT_DIMENSIONS ], - ], - - 'intrinsic_layout_different_unit_dimensions' => [ - '<amp-img src="/img1.png" width="50px" height="50em" layout="intrinsic"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_UNIT_DIMENSIONS ], - ], - - 'fixed_layout_with_invalid_heights_attr' => [ - '<amp-img layout="fixed" alt="AMP" src="/static/inline-examples/images/amp.jpg" width="320" height="256" heights="(min-width:500px) 200px, 80%"></amp-img>', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_HEIGHTS ], - ], - - 'responsive_layout_heights_attribute' => [ - '<amp-img src="/img1.png" width="50" height="50" heights="(min-width:500px) 200px, 80%" layout="responsive"></amp-img>', - null, - ], - - 'multiple_width_attributes' => [ - '<amp-img src="/img1.png" width="50" width="40" width="30" height="50" layout="responsive"></amp-img>', - '<amp-img src="/img1.png" width="50" height="50" layout="responsive"></amp-img>', - ], - - 'fill_layout' => [ - '<amp-img src="/img1.png" width="30" height="30" layout="fill"></amp-img>', - null, - ], - 'fill_layout_no_height' => [ - '<amp-img src="/img1.png" width="30" layout="fill"></amp-img>', - null, - ], - 'fill_layout_no_width' => [ - '<amp-img src="/img1.png" height="30" layout="fill"></amp-img>', - null, - ], - 'fill_layout_no_dimensions' => [ - '<amp-img src="/img1.png" layout="fill"></amp-img>', - null, - ], - - 'disable-inline-width' => [ - '<amp-img layout="intrinsic" height="160" width="480" disable-inline-width src="https://example.com/elva-fairy-800w.jpg" srcset="https://example.com/elva-fairy-480w.jpg 480w, https://example.com/elva-fairy-800w.jpg 800w" sizes="(max-width: 600px) 480px, 800px"></amp-img>', - null, - ], - - 'amp-inline-gallery' => [ - ' - <amp-inline-gallery layout="container"> - <amp-base-carousel - class="gallery" - layout="responsive" - width="3.6" - height="2" - snap-align="center" - loop="true" - visible-count="1.2" - lightbox> - <amp-img - src="/static/inline-examples/images/image1.jpg" - layout="responsive" - width="450" - height="300"></amp-img> - <amp-img - src="/static/inline-examples/images/image2.jpg" - layout="responsive" - width="450" - noloading - height="300"></amp-img> - <amp-img - src="/static/inline-examples/images/image3.jpg" - layout="responsive" - width="450" - noloading="noloading" - height="300"></amp-img> - <amp-img - src="/static/inline-examples/images/image4.jpg" - layout="responsive" - width="450" - noloading="" - height="300"></amp-img> - </amp-base-carousel> - <amp-inline-gallery-pagination layout="nodisplay" inset> - </amp-inline-gallery-pagination> - </amp-inline-gallery> - ', - null, - [ 'amp-base-carousel', 'amp-inline-gallery', 'amp-lightbox-gallery' ], - ], - - 'amp-inline-gallery-with-thumbs' => [ - ' - <amp-inline-gallery layout="container"> - <!-- - The amp-layout with layout="container" is used to display the pagination on - top of the carousel instead of the thumbnails. You can also use a div with - `position: relative;` - --> - <amp-layout layout="container"> - <amp-base-carousel - class="gallery" - layout="responsive" - width="3" - height="2" - snap-align="center" - loop="true"> - <amp-img - class="slide" - layout="flex-item" - src="https://picsum.photos/id/779/600/400" - srcset="https://picsum.photos/id/779/150/100 150w, - https://picsum.photos/id/779/600/400 600w, - https://picsum.photos/id/779/1200/800 1200w"> - </amp-img> - <amp-img - class="slide" - layout="flex-item" - src="https://picsum.photos/id/1048/600/400" - srcset="https://picsum.photos/id/1048/150/100 150w, - https://picsum.photos/id/1048/600/400 600w, - https://picsum.photos/id/1048/1200/800 1200w"> - </amp-img> - <amp-img - class="slide" - layout="flex-item" - src="https://picsum.photos/id/108/600/400" - srcset="https://picsum.photos/id/108/150/100 150w, - https://picsum.photos/id/108/600/400 600w, - https://picsum.photos/id/108/1200/800 1200w"> - </amp-img> - </amp-base-carousel> - <!-- - If using fewer than 8 slides, consider adding something - like media="(max-width: 799px)". - --> - <amp-inline-gallery-pagination layout="nodisplay" inset> - </amp-inline-gallery-pagination> - </amp-layout> - <amp-inline-gallery-thumbnails - media="(min-width: 800px)" - layout="fixed-height" - height="96"> - </amp-inline-gallery-thumbnails> - </amp-inline-gallery> - ', - null, - [ 'amp-base-carousel', 'amp-inline-gallery' ], - ], - - 'amp-mega-menu' => [ - ' - <amp-mega-menu height="30" layout="fixed-height"> - <nav> - <ul> - <li> - <span role="button">Image</span> - <div role="dialog" aria-modal="true" id="unique_id"> - <amp-img - src="/static/inline-examples/images/image1.jpg" - width="300" - height="200"></amp-img> - </div> - </li> - <li> - <span role="button">List</span> - <div role="dialog"> - <ol> - <li>item 1</li> - <li>item 2</li> - <li>item 3</li> - </ol> - </div> - </li> - <li> - <a href="https://amp.dev/">Link</a> - </li> - </ul> - </nav> - </amp-mega-menu> - ', - null, - [ 'amp-mega-menu' ], - ], - - 'amp-mega-menu-with-template' => [ - ' - <amp-mega-menu height="60" layout="fixed-height"> - <amp-list - height="350" - layout="fixed-height" - src="/static/samples/json/product-single-item.json" - single-item> - <template type="amp-mustache"> - <nav> - <ul> - {{#values}} <li> - <h4 role="button">{{name}}</h4> - <div role="dialog"> - <amp-img - src="{{img}}" - width="320" - height="213"></amp-img> - <p>Price: $<b>{{price}}</b></p> - </div> - </li> - {{/values}} </ul> - </nav> - </template> - </amp-list> - </amp-mega-menu> - ', - null, - [ 'amp-mega-menu', 'amp-list', 'amp-mustache' ], - ], - - 'amp-mega-menu-disallowed-descendants' => [ - ' - <amp-mega-menu height="30" layout="fixed-height"> - <nav> - <ul> - <li> - <span role="button">List</span> - <div role="dialog"> - <details><summary>Not</summary> allowed</details> - </div> - </li> - <li> - <a href="https://amp.dev/">Link</a> - </li> - </ul> - </nav> - </amp-mega-menu> - ', - ' - <amp-mega-menu height="30" layout="fixed-height"> - <nav> - <ul> - <li> - <span role="button">List</span> - <div role="dialog"></div> - </li> - <li> - <a href="https://amp.dev/">Link</a> - </li> - </ul> - </nav> - </amp-mega-menu> - ', - [ 'amp-mega-menu' ], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_DESCENDANT_TAG ], - ], - - 'amp-mega-menu-invalid-child' => [ - ' - <amp-mega-menu height="30" layout="fixed-height"> - <div>Not allowed</div> - </amp-mega-menu> - ', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_CHILD_TAG ], - ], - - 'amp-nested-menu' => [ - ' - <button on="tap:sidebar1">Open Sidebar</button> - <amp-sidebar id="sidebar1" layout="nodisplay" style="width:300px"> - <amp-nested-menu layout="fill"> - <svg viewbox="0 0 100 100"><circle cx="50" cy="50" r="50" /></svg> - <ul> - <li> - <h4 amp-nested-submenu-open>Open Sub-Menu</h4> - <div amp-nested-submenu> - <ul> - <li> - <h4 amp-nested-submenu-close>go back</h4> - </li> - <li> - <h4 amp-nested-submenu-open>Open Another Sub-Menu</h4> - <div amp-nested-submenu> - <h4 amp-nested-submenu-close>go back</h4> - <amp-img - src="/static/inline-examples/images/image1.jpg" - layout="responsive" - width="450" - height="300"></amp-img> - </div> - </li> - </ul> - </div> - </li> - <li> - <a href="https://amp.dev/">Link</a> - </li> - </ul> - </amp-nested-menu> - </amp-sidebar> - ', - null, - [ 'amp-sidebar' ], - ], - - 'amp-nested-menu-with-amp-list' => [ - ' - <button on="tap:sidebar2">Open Sidebar</button> - <amp-sidebar id="sidebar2" layout="nodisplay" style="width:300px"> - <amp-list - layout="fill" - src="/static/inline-examples/data/amp-list-data.json" - items="." - single-item> - <template type="amp-mustache"> - <amp-nested-menu layout="fill"> - <ul> - {{#items}} <li> - <h3 amp-nested-submenu-open>{{title}}</h3> - <div amp-nested-submenu> - <button amp-nested-submenu-close>close</button> - <amp-img - src="{{imageUrl}}" - layout="responsive" - width="400" - height="300"></amp-img> - </div> - </li> - {{/items}} </ul> - </amp-nested-menu> - </template> - </amp-list> - </amp-sidebar> - ', - null, - [ 'amp-sidebar', 'amp-list', 'amp-mustache' ], - ], - - 'amp-redbull-player' => [ - ' - <amp-redbull-player - id="rbvideo" - data-param-videoid="rrn:content:videos:3965a26c-052e-575f-a28b-ded6bee23ee1:en-INT" - data-param-skinid="com" - data-param-locale="en" - height="360" - width="640"></amp-redbull-player> - ', - null, - [ 'amp-redbull-player' ], - ], - - 'mustache_templates_with_variable_attrs' => [ - ' - <template type="amp-mustache"> - <amp-img src="/img1.png" layout="bad" width="bad" height="bad" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img2.png" layout="{{layout}}" width="bad" height="bad" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img3.png" layout="bad" width="{{width}}" height="bad" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img4.png" layout="bad" width="bad" height="{{height}}" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img5.png" layout="bad" width="bad" height="bad" heights="{{heights}}" sizes="bad"></amp-img> - <amp-img src="/img6.png" layout="bad" width="bad" height="bad" heights="bad" sizes="{{sizes}}"></amp-img> - </template> - ', - ' - <template type="amp-mustache"> - <amp-img src="/img2.png" layout="{{layout}}" width="bad" height="bad" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img3.png" width="{{width}}" height="bad" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img4.png" width="bad" height="{{height}}" heights="bad" sizes="bad"></amp-img> - <amp-img src="/img5.png" width="bad" height="bad" heights="{{heights}}" sizes="bad"></amp-img> - <amp-img src="/img6.png" width="bad" height="bad" heights="bad" sizes="{{sizes}}"></amp-img> - </template> - ', - [ 'amp-mustache' ], - [ - AMP_Tag_And_Attribute_Sanitizer::INVALID_LAYOUT_WIDTH, - AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX_CASEI, - AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX_CASEI, - AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX_CASEI, - AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX_CASEI, - ], - ], - - 'missing-layout-and-width-height' => [ - ' - <amp-img src="https://placeholder.com/350"></amp-img> - <amp-gist data-gistid="b9bb35bc68df68259af94430f012425f"></amp-gist> - <amp-web-push-widget visibility="unsubscribed"></amp-web-push-widget> - <amp-megaphone data-episode="OSC7749686951" data-light></amp-megaphone> - ', - '', - [], - [ - AMP_Tag_And_Attribute_Sanitizer::MISSING_LAYOUT_ATTRIBUTES, - AMP_Tag_And_Attribute_Sanitizer::IMPLIED_LAYOUT_INVALID, - AMP_Tag_And_Attribute_Sanitizer::IMPLIED_LAYOUT_INVALID, - AMP_Tag_And_Attribute_Sanitizer::IMPLIED_LAYOUT_INVALID, - ], - ], - - 'missing-layout-nodisplay' => [ - ' - <amp-animation><script type="application/json">{}</script></amp-animation> - <amp-link-rewriter><script type="application/json">{}</script></amp-link-rewriter> - <amp-install-serviceworker src="https://www.example.com/serviceworker.js" data-iframe-src="https://www.example.com/install-serviceworker.html"></amp-install-serviceworker> - ', - '', - [], - [ - AMP_Tag_And_Attribute_Sanitizer::IMPLIED_LAYOUT_INVALID, - AMP_Tag_And_Attribute_Sanitizer::IMPLIED_LAYOUT_INVALID, - AMP_Tag_And_Attribute_Sanitizer::IMPLIED_LAYOUT_INVALID, - ], - ], - - 'layout-attributes-not-required' => [ - ' - <amp-audio src="https://example.com/foo.mp3"></amp-audio> - <amp-pixel src="https://example.com/tracker/foo"></amp-pixel> - ', - null, - [ 'amp-audio' ], - [], - ], - - 'layout-specified-is-invalid' => [ - '<amp-animation layout="responsive"><script type="application/json">{}</script></amp-animation>', - '', - [], - [ - AMP_Tag_And_Attribute_Sanitizer::SPECIFIED_LAYOUT_INVALID, - ], - ], - - 'amp-onetap-google' => [ - '<amp-onetap-google layout="nodisplay" data-src="https://rp.com/intermediate"></amp-onetap-google>', - null, - [ 'amp-onetap-google' ], - ], - - 'svg_filter_primitives' => [ - // Example from <https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feBlend>. - ' - <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> - <defs> - <filter id="spotlight"> - <feflood result="floodFill" x="0" y="0" width="100%" height="100%" flood-color="green" flood-opacity="1"></feflood> - <feblend in="SourceGraphic" in2="floodFill" mode="multiply"></feblend> - </filter> - </defs> - <image xlink:href="//developer.mozilla.org/files/6457/mdn_logo_only_color.png" x="10%" y="10%" width="80%" height="80%" style="filter:url(#spotlight);"></image> - </svg> - ', - null, - [], - ], - - 'amp-iframely' => [ - ' - <amp-iframely data-id="UjEwgS" width="400" height="140" layout="responsive" resizable></amp-iframely> - <amp-iframely data-id="JQfo4N" data-domain="cdn.iframe.ly" width="400" height="225" layout="responsive"></amp-iframely> - <amp-iframely data-id="CsmRlq" width="400" height="213" layout="responsive"></amp-iframely> - <amp-iframely data-url="https://iframely.com/" data-key="8a237467d51be2771401abcabbd46d92" height="200" width="400" layout="responsive"></amp-iframely> - ', - null, - [ 'amp-iframely' ], - ], - - 'amp-render' => [ - ' - <!-- Valid: amp-render with only src attribute --> - <amp-render - width="10" - height="10" - src="amp-state:source"> - </amp-render> - - <!-- Valid: amp-render with only [src] attribute --> - <amp-render width="10" height="10" data-amp-bind-src="srcUrl"> </amp-render> - - <!-- Valid: amp-render with relative URL as src attribute --> - <amp-render width="10" height="10" src="/path/to/data.json"> </amp-render> - - <!-- Valid: amp-render with both src and [src] attributes --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - data-amp-bind-src="foo.bar"> - </amp-render> - - <!-- Valid: amp-render with binding="refresh" attribute --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - binding="refresh"> - </amp-render> - - <!-- Valid: amp-render with binding="no" attribute --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - binding="no"> - </amp-render> - - <!-- Valid: amp-render with binding="always" attribute --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - binding="always"> - </amp-render> - - <!-- Valid: amp-render with credentials="include" --> - <amp-render - width="10" - height="10" - src="amp-script:scriptFn.dataFn" - credentials="include"> - </amp-render> - - <!-- Valid: amp-render with credentials="omit" --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - credentials="omit"> - </amp-render> - - <!-- Valid: amp-render with xssi-prefix attribute --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - xssi-prefix="({["> - </amp-render> - - <!-- Valid: amp-render with key attribute --> - <amp-render - width="10" - height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - key="name"> - </amp-render> - - <!-- Valid: amp-render with template attribute --> - <amp-render width="10" height="10" - src="https://data.com/articles.json?ref=CANONICAL_URL" - template="found"> - </amp-render> - <template id="found" type="amp-mustache"></template> - ', - null, - [ 'amp-render', 'amp-bind', 'amp-mustache' ], - ], - - 'amp-stream-gallery' => [ - ' - <amp-stream-gallery width="4" height="3" loop="true"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" loop="false"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" loop="(min-width: 800px) true, false"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" loop="(min-width: 800px) true, (max-height: 1000px) true, false"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-item-width="200"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-item-width="(min-width: 800px) 300, 100"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-item-width="(min-width: 800px) 200, (max-height: 1000px) 300, 100"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-visible-count="2"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-visible-count="3.2"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-visible-count="(min-width: 800px) 3.2, 1"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" min-visible-count="(min-width: 800px) 3, (max-height: 1000px) 3, 1.1"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" controls="always"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" controls="auto"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" controls="never"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" controls="(min-width: 800px) never, auto"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" controls="(min-width: 800px) always, (max-height: 1000px) auto, never"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" loop="(min-width: 800px) true, false"> - </amp-stream-gallery> - <amp-stream-gallery width="4" height="3" loop="(min-width: 800px) true,(max-height: 1000px) true,false"> - </amp-stream-gallery> - ', - null, - [ 'amp-stream-gallery' ], - ], - - 'amp-tiktok' => [ - ' - <amp-tiktok width="500" height="500" data-src="6943753342808034566"></amp-tiktok> - <amp-tiktok - width="700" - height="800" - data-src="https://www.tiktok.com/@scout2015/video/6943753342808034566"> - </amp-tiktok> - <amp-tiktok width="500" height="800"> - <blockquote - placeholder - class="tiktok-embed" - cite="https://www.tiktok.com/@countingprimes/video/6948210747285441798" - data-video-id="6948210747285441798" - style="max-width: 605px; min-width: 325px"> - <section> - <a - target="_blank" - title="@countingprimes" - href="https://www.tiktok.com/@countingprimes">@countingprimes</a> - <p> - VIM is great.... right up until you start typing the commands into every - single text editor you see. I’d like to apologize for all my unneeded - “:wq”’s - </p> - <a - target="_blank" - title="♬ original sound - countingprimes" - href="https://www.tiktok.com/music/original-sound-6948210588145175302">♬ original sound - countingprimes</a> - </section> - </blockquote> - </amp-tiktok> - ', - null, - [ 'amp-tiktok' ], - ], - - 'amp-wordpress-embed' => [ - ' - <amp-wordpress-embed - data-url="https://make.wordpress.org/core/2015/10/28/new-embeds-feature-in-wordpress-4-4/" - layout="fixed" - height="400" - width="600"> - <button overflow>Load more</button> - </amp-wordpress-embed> - ', - null, - [ 'amp-wordpress-embed' ], - ], - ]; - } - - /** - * Get data for testing sanitization in the html. - * - * @return array[] Each array item is a tuple containing pre-sanitized string, sanitized string, and scripts - * identified during sanitization. - */ - public function get_html_data() { - $data = [ - 'meta_charset_and_viewport_and_canonical' => [ - '<html amp lang="ar" dir="rtl"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport" content="width=device-width, minimum-scale=1"><base target="_blank"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine"><link rel="canonical" href="self.html"><title>marhabaan bialealim!', - ], - 'script_tag_externals' => [ - '', - '', - [], - array_fill( - 0, - 4, - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'script', - ] - ), - ], - 'script_tag_inline' => [ - '', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'script', - ], - ], - ], - 'style_external' => [ - '', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX, - 'node_name' => 'href', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'node_name' => 'link', - ], - ], - ], - 'style_inline' => [ - '', - '', - [], - array_fill( - 0, - 2, - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'style', - ] - ), - ], - 'bad_external_font' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_ATTR_VALUE_REGEX, AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING ], - ], - 'bad_meta_ua_compatible' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROPERTY_IN_ATTR_VALUE, AMP_Tag_And_Attribute_Sanitizer::MISSING_REQUIRED_PROPERTY_VALUE ], - ], - 'bad_meta_width_property' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MISSING_REQUIRED_PROPERTY_VALUE ], - ], - 'bad_meta_width_and_unknown_property' => [ - '', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROPERTY_IN_ATTR_VALUE, - 'meta_property_name' => 'bad', - 'meta_property_value' => 'yes', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MISSING_REQUIRED_PROPERTY_VALUE, - 'meta_property_name' => 'width', - 'meta_property_value' => '600', - 'meta_property_required_value' => 'device-width', - ], - ], - ], - 'missing_meta_width_and_unknown_property' => [ - '', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROPERTY_IN_ATTR_VALUE, - 'meta_property_name' => 'bad', - 'meta_property_value' => 'yes', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::MISSING_MANDATORY_PROPERTY, - 'meta_property_name' => 'width', - 'meta_property_required_value' => 'device-width', - ], - ], - ], - 'bad_meta_charset' => [ - 'Mojibake?', - 'Mojibake?', // Note the charset attribute is removed because it violates the attribute spec, but the entire element is not removed because charset is not mandatory. - ], - 'bad_meta_viewport' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MISSING_MANDATORY_PROPERTY ], - ], - 'invalid_meta_viewport_property' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_PROPERTY_IN_ATTR_VALUE ], - ], - 'parse_malformed_meta_charset_tag' => [ - '', - '', - [], - [], - ], - 'edge_meta_ua_compatible' => [ - '', - null, // No change. - ], - 'meta_viewport_extras' => [ - '', - null, // No change. - ], - 'meta_og_property' => [ - '', - null, // No change. - ], - 'head_with_valid_amp_illegal_parent' => [ - '', - '', - [ 'amp-analytics' ], - ], - 'head_with_invalid_nodes' => [ - 'bad! other', - 'bad!

        other

        ', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG ], - ], - 'head_with_duplicate_charset' => [ - '

        Content

        ', - '

        Content

        ', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DUPLICATE_UNIQUE_TAG ], - ], - 'head_with_duplicate_viewport' => [ - '

        Content

        ', - '

        Content

        ', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DUPLICATE_UNIQUE_TAG ], - ], - 'meta_amp_script_src' => [ - '', - null, // No change. - ], - 'meta_story_meta_tags' => [ - '', - null, // No change. - ], - 'meta_theme_color' => [ - '', - null, // No change. - ], - 'link_without_valid_mandatory_href' => [ - '', - '', - [], - [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::INVALID_URL, - 'node_name' => 'href', - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::ATTR_REQUIRED_BUT_MISSING, - 'node_name' => 'link', - ], - ], - ], - 'cdata_css_i_amphtml_name' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_CDATA_CSS_I_AMPHTML_NAME ], - ], - 'cdata_css_html_comment' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_CDATA_HTML_COMMENTS ], - ], - 'cdata_contents_bad_comment' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_CDATA_HTML_COMMENTS ], - ], - 'cdata_malformed_json' => [ - '', - '', - [ 'amp-ima-video' ], - [ AMP_Tag_And_Attribute_Sanitizer::JSON_ERROR_SYNTAX ], - ], - 'cdata_malformed_json_with_emojis' => [ - '', - '', - [ 'amp-ima-video' ], - [ AMP_Tag_And_Attribute_Sanitizer::JSON_ERROR_SYNTAX ], - ], - 'cdata_malformed_utf8_json' => [ - sprintf( '', "\xFF" ), - '', - [ 'amp-ima-video' ], - [ AMP_Tag_And_Attribute_Sanitizer::JSON_ERROR_UTF8 ], - ], - 'cdata_empty_json_considered_invalid' => [ - '', - '', - [ 'amp-ima-video' ], - [ AMP_Tag_And_Attribute_Sanitizer::JSON_ERROR_EMPTY ], - ], - 'cdata_empty_json_not_considered_invalid' => [ - '', - null, - [], - [], - ], - 'analytics_empty_json_considered_invalid' => [ - '', - '', - [ 'amp-analytics' ], - [ AMP_Tag_And_Attribute_Sanitizer::JSON_ERROR_EMPTY ], - ], - 'analytics_state_mismatch_json_error' => [ - '', - '', - [ 'amp-analytics' ], - [ AMP_Tag_And_Attribute_Sanitizer::JSON_ERROR_STATE_MISMATCH ], - ], - 'script_cdata_contents_bad' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::INVALID_CDATA_CONTENTS ], - ], - 'cdata_regex_failure' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::MANDATORY_CDATA_MISSING_OR_INCORRECT ], - ], - 'amp_runtime' => [ - '', - null, - [], - ], - 'amp_runtime_lts' => [ - '', - null, - [], - ], - 'amp-subscriptions' => [ - // @todo The but it is not yet supported. Support depends on todo in \AMP_Tag_And_Attribute_Sanitizer::has_parent(). - ' - - - - - - -
        - ... -
        - - - - ', - null, - [ 'amp-subscriptions' ], - ], - 'bad http-equiv meta tag' => [ - '', - '', - [], - [ AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR ], - ], - 'responsive_image_preload_links' => [ - '', - null, // No change. - [], - [], - ], - 'modulepreload_link' => [ - '', - null, // No change. - [], - [], - ], - 'script_onerror' => [ - '', - null, // No change. - [], - [], - ], - ]; - - $bad_dev_mode_document = sprintf( - ' - - - - - - - - - - - - - - ', - 'button::before { content:"' . str_repeat( 'a', 75001 ) . '";"}', - '{"foo":"' . str_repeat( 'b', 100001 ) . '"}' - ); - - $data['dev_mode_not_set_on_html_element'] = [ - $bad_dev_mode_document, - ' - - - - - - - - - - - ', - [ 'amp-bind' ], - [ - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - AMP_Tag_And_Attribute_Sanitizer::CDATA_TOO_LONG, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - ], - ]; - - $bad_dev_mode_document = sprintf( - ' - - - - - - - - - - - - - - ', - 'button::before { content:"' . str_repeat( 'a', 75001 ) . '";"}', - '{"foo":"' . str_repeat( 'b', 100001 ) . '"}' - ); - - $data['dev_mode_set_on_html_element'] = [ - $bad_dev_mode_document, - null, - [ 'amp-bind' ], - [], // All validation errors suppressed. - ]; - - $data['bad_document_without_dev_mode'] = [ - str_replace( 'data-ampdevmode', '', $bad_dev_mode_document ), - ' - - - - - - - - - - ', - [ 'amp-bind' ], - [ - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - AMP_Tag_And_Attribute_Sanitizer::CDATA_TOO_LONG, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - ], - ]; - - $max_size = null; - foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'style' ) as $spec_rule ) { - if ( isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) && 'style amp-custom' === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) { - $max_size = $spec_rule[ AMP_Rule_Spec::CDATA ]['max_bytes']; - break; - } - } - if ( ! $max_size ) { - throw new Exception( 'Could not find amp-custom max_bytes' ); - } - - $dont_strip_excessive_css_in_amp_custom_document = sprintf( - ' - - - - - - - - - ', - 'body::after { content:"' . str_repeat( 'a', $max_size ) . '";"}' - ); - - $data['dont_strip_excessive_css_in_amp_custom_document'] = [ - $dont_strip_excessive_css_in_amp_custom_document, - ]; - - // Also include the body tests. - $html_doc_format = '%s'; - foreach ( $this->get_body_data() as $name => $body_test ) { - if ( isset( $data[ $name ] ) ) { - throw new Exception( "Test data error: duplicate test name: $name" ); - } - $html_test = $body_test; - $html_test[0] = sprintf( $html_doc_format, $html_test[0] ); - if ( isset( $html_test[1] ) ) { - $html_test[1] = sprintf( $html_doc_format, $html_test[1] ); - } - $data[ $name ] = $html_test; - } - - return $data; - } - - /** - * Test sanitization of tags and attributes for the entire document, including the HEAD. - * - * @dataProvider get_html_data - * @group allowed-tags - * @covers AMP_Tag_And_Attribute_Sanitizer::sanitize() - * - * @param string $source Markup to process. - * @param string $expected The markup to expect. - * @param array $expected_scripts The AMP component script names that are obtained through sanitization. - * @param array|null $expected_errors Expected validation errors, either codes or validation error subsets. - * @param array $sanitizer_args Sanitizer args. - */ - public function test_sanitize( $source, $expected = null, $expected_scripts = [], $expected_errors = [], $sanitizer_args = [] ) { - $expected = isset( $expected ) ? $expected : $source; - $dom = Document::fromHtml( $source, Options::DEFAULTS ); - $actual_errors = []; - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( - $dom, - array_merge( - [ - 'use_document_element' => true, - 'validation_error_callback' => static function( $error ) use ( &$actual_errors ) { - $actual_errors[] = $error; - return true; - }, - ], - $sanitizer_args - ) - ); - $sanitizer->sanitize(); - $content = $dom->saveHTML( $dom->documentElement ); - $this->assertEqualMarkup( $expected, $content ); - - $this->assertEqualSets( $expected_scripts, array_keys( $sanitizer->get_scripts() ) ); - - $expected_errors = array_map( - static function ( $error ) { - if ( is_string( $error ) ) { - return [ 'code' => $error ]; - } else { - return $error; - } - }, - $expected_errors - ); - $this->assertEquals( wp_list_pluck( $expected_errors, 'code' ), wp_list_pluck( $actual_errors, 'code' ) ); - foreach ( $expected_errors as $i => $expected_error ) { - foreach ( array_keys( $expected_error ) as $key ) { - $this->assertArrayHasKey( $key, $actual_errors[ $i ] ); - $this->assertEquals( $expected_error[ $key ], $actual_errors[ $i ][ $key ], "For key: $key" ); - } - } - } - - /** - * Ensure that sanitizing with use_document_element arg not supplied works as expected. - * - * @covers AMP_Tag_And_Attribute_Sanitizer::sanitize() - */ - public function test_sanitize_body_only() { - $source = 'Hello'; - $expected = 'Hello'; - - $dom = Document::fromHtml( $source, Options::DEFAULTS ); - $actual_errors = []; - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( - $dom, - [ - 'use_document_element' => false, - 'validation_error_callback' => static function( $error ) use ( &$actual_errors ) { - $actual_errors[] = $error; - return true; - }, - ] - ); - - $sanitizer->sanitize(); - $actual = AMP_DOM_Utils::get_content_from_dom( $dom ); - $this->assertEquals( $expected, $actual ); - $this->assertEqualSets( [ 'amp-sidebar' ], array_keys( $sanitizer->get_scripts() ) ); - - $this->assertCount( 1, $actual_errors ); - $this->assertAssocArrayContains( - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, // @todo Should be DISALLOWED_SCRIPT_TAG. - ], - $actual_errors[0] - ); - } - - /** - * Tests is_missing_mandatory_attribute - * - * @see AMP_Tag_And_Attribute_Sanitizer::is_missing_mandatory_attribute() - */ - public function test_is_missing_mandatory_attribute() { - $spec = [ - 'data-gistid' => [ - 'mandatory' => true, - ], - 'noloading' => [], - ]; - $dom = new Document(); - $node = new DOMElement( 'amp-gist' ); - $dom->appendChild( $node ); - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( $dom ); - $this->assertTrue( $sanitizer->is_missing_mandatory_attribute( $spec, $node ) ); - - $node->setAttribute( 'data-gistid', 'foo-value' ); - $this->assertFalse( $sanitizer->is_missing_mandatory_attribute( $spec, $node ) ); - } - - /** - * Get data for replace_node_with_children_validation_errors test. - * - * @return array[] Test data. - */ - public function get_data_for_replace_node_with_children_validation_errors() { - return [ - 'amp_image' => [ - '', - '', - [ - [ - 'node_name' => 'amp-image', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [ - 'src' => '/none.jpg', - 'width' => '100', - 'height' => '100', - 'alt' => 'None', - ], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'invalid_parent_element' => [ - '

        Invalid baz parent element.

        ', - '

        Invalid baz parent element.

        ', - [ - [ - 'node_name' => 'baz', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [ 'class' => 'baz-invalid' ], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'invalid_a_tag' => [ - '
        Invalid a tag.', - '', - [ - [ - 'node_name' => 'amp-story-grid-layer', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::MANDATORY_TAG_ANCESTOR, - 'node_attributes' => [ 'class' => 'a-invalid' ], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'spec_name' => 'amp-story-grid-layer', - 'required_ancestor_name' => 'amp-story-page', - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'invalid_foo_tag' => [ - 'Invalid foo tag.', - 'Invalid foo tag.', - [ - [ - 'node_name' => 'foo', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [ 'class' => 'foo-invalid' ], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'invalid_barbaz_tag' => [ - 'Is an invalid "bazbar" tag.', - 'Is an invalid "bazbar" tag.', - [ - [ - 'node_name' => 'bazbar', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'nested_valid_and_invalid' => [ - ' -
        -

        Nesting valid and invalid elements.

        - Is an invalid "invalid" tag - Is an invalid "foo" tag

        This should pass.

        -
        - ', - ' -
        -

        Nesting valid and invalid elements.

        - Is an invalid "invalid" tag Is an invalid "foo" tag

        This should pass.

        -
        - ', - [ - [ - 'node_name' => 'invalid_p', - 'parent_name' => 'div', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [ 'id' => 'invalid' ], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - [ - 'node_name' => 'bazfoo', - 'parent_name' => 'div', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'bad_lili' => [ - ' -
          -
        • hello
        • - world -
        - ', - '
        • hello
        • world
        ', - [ - [ - 'node_name' => 'lili', - 'parent_name' => 'ul', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'invalid_nested_elements' => [ - 'Invalid nested elements', - 'Invalid nested elements', - [ - [ - 'node_name' => 'foo', - 'parent_name' => 'divs', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - [ - 'node_name' => 'divs', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - ], - - 'custom_elements-removed' => [ - 'Hello!', - 'Hello!', - [ - [ - 'node_name' => 'bar-baz', - 'parent_name' => 'foo-bar', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - [ - 'node_name' => 'foo-bar', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - true, - ], - - 'custom_elements-kept' => [ - 'Hello!', - sprintf( 'Hello!', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ), - [ - [ - 'node_name' => 'bar-baz', - 'parent_name' => 'foo-bar', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - [ - 'node_name' => 'foo-bar', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - false, - ], - - 'custom_element-removed-empty' => [ - '', - '', - [ - [ - 'node_name' => 'foo-bar', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - true, // Sanitize. - ], - - 'custom_elements-kept-repeated' => [ - 'Hello!Hello!', - sprintf( 'Hello!Hello!', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ), - [ - [ - 'node_name' => 'foo-bar', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - [ - 'node_name' => 'foo-bar', - 'parent_name' => 'body', - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_attributes' => [], - 'type' => AMP_Validation_Error_Taxonomy::HTML_ELEMENT_ERROR_TYPE, - 'node_type' => XML_ELEMENT_NODE, - ], - ], - false, // Sanitize. - ], - - 'custom_elements-devmode' => [ - sprintf( 'Hello!', DevMode::DEV_MODE_ATTRIBUTE ), - sprintf( 'Hello!', DevMode::DEV_MODE_ATTRIBUTE ), - [], - true, // Sanitize. - true, // Dev Mode. - ], - - 'custom_elements-amp-unvalidated' => [ - sprintf( 'Hello!', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ), - sprintf( 'Hello!', ValidationExemption::AMP_UNVALIDATED_TAG_ATTRIBUTE ), - [], - true, // Sanitize. - ], - - 'custom_elements-px-verified' => [ - sprintf( 'Hello!', ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ), - sprintf( 'Hello!', ValidationExemption::PX_VERIFIED_TAG_ATTRIBUTE ), - [], - true, // Sanitize. - ], - ]; - } - - /** - * Tests replace_node_with_children validation errors. - * - * @dataProvider get_data_for_replace_node_with_children_validation_errors - * @covers \AMP_Tag_And_Attribute_Sanitizer::replace_node_with_children() - * - * @param string $source_content Source DOM content. - * @param string $expected_content Expected content after sanitization. - * @param array[] $expected_errors Expected errors. - * @param bool $sanitize Whether the invalid markup should be sanitized. - */ - public function test_replace_node_with_children_validation_errors( $source_content, $expected_content, $expected_errors, $sanitize = true, $dev_mode = false ) { - $dom = AMP_DOM_Utils::get_dom_from_content( $source_content ); - - if ( $dev_mode ) { - $dom->documentElement->setAttribute( DevMode::DEV_MODE_ATTRIBUTE, '' ); - } - - $sanitizer = new AMP_Tag_And_Attribute_Sanitizer( - $dom, - [ - 'validation_error_callback' => function( $error, $context ) use ( &$expected_errors, $sanitize ) { - $expected = array_shift( $expected_errors ); - $this->assertIsArray( $expected ); - $tag = $expected['node_name']; - $this->assertEquals( $expected, $error ); - $this->assertInstanceOf( 'DOMElement', $context['node'] ); - $this->assertEquals( $tag, $context['node']->tagName ); - return $sanitize; - }, - ] - ); - $sanitizer->sanitize(); - - $this->assertEmpty( $expected_errors, 'There should be no expected validation errors remaining.' ); - $this->assertEqualMarkup( $expected_content, AMP_DOM_Utils::get_content_from_dom( $dom ) ); - } -} diff --git a/tests/php/test-uninstall.php b/tests/php/test-uninstall.php deleted file mode 100644 index e2c4167c3da..00000000000 --- a/tests/php/test-uninstall.php +++ /dev/null @@ -1,669 +0,0 @@ -was_using_ext_object_cache = wp_using_ext_object_cache(); - require_once AMP__DIR__ . '/includes/uninstall-functions.php'; - } - - public function tear_down() { - wp_using_ext_object_cache( $this->was_using_ext_object_cache ); - parent::tear_down(); - } - - /** - * @covers \AmpProject\AmpWP\delete_options() - */ - public function test_delete_options() { - global $wpdb; - - $reader_theme = 'foo'; - - // Non-AMP options. - $blog_name = 'Sample Blog Name'; - update_option( 'blogname', $blog_name ); - set_theme_mod( 'color', 'blue' ); - - // AMP options. - AMP_Options_Manager::update_options( - [ - Option::THEME_SUPPORT => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - Option::READER_THEME => $reader_theme, - ] - ); - update_option( MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY, [] ); - update_option( URLValidationCron::OPTION_KEY, [] ); - update_option( - "theme_mods_{$reader_theme}", - [ - 'color' => 'red', - AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY => [ - 'color' => time(), - ], - ] - ); - - $options_before_delete = $wpdb->get_col( "SELECT option_name FROM $wpdb->options" ); - - delete_options(); - $this->flush_cache(); - - $this->assertEquals( $blog_name, get_option( 'blogname' ) ); - $this->assertEquals( 'blue', get_theme_mod( 'color' ) ); - - $this->assertFalse( get_theme_mod( AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY ) ); - $foo_theme_mods = get_option( 'theme_mods_foo' ); - $this->assertEquals( 'red', $foo_theme_mods['color'] ); - $this->assertArrayNotHasKey( AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY, $foo_theme_mods ); - - $options_after_delete = $wpdb->get_col( "SELECT option_name FROM $wpdb->options" ); - $this->assertEqualSets( - [ - AMP_Options_Manager::OPTION_NAME, - URLValidationCron::OPTION_KEY, - MonitorCssTransientCaching::TIME_SERIES_OPTION_KEY, - ], - array_diff( $options_before_delete, $options_after_delete ), - 'Expected only 3 options to have been deleted.' - ); - } - - /** - * @covers \AmpProject\AmpWP\delete_user_metadata() - */ - public function test_delete_user_metadata() { - global $wpdb; - - $user_ids = self::factory()->user->create_many( 3 ); - foreach ( $user_ids as $user_id ) { - update_user_meta( $user_id, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, '...' ); - update_user_meta( $user_id, UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE, '...' ); - update_user_meta( $user_id, 'additional_user_meta', '...' ); - } - - $user_meta_keys_before_delete = $wpdb->get_col( "SELECT meta_key FROM $wpdb->usermeta" ); - - delete_user_metadata(); - $this->flush_cache(); - - foreach ( $user_ids as $user_id ) { - $this->assertEmpty( get_user_meta( $user_id, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, true ) ); - $this->assertEmpty( get_user_meta( $user_id, UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE, true ) ); - $this->assertEquals( '...', get_user_meta( $user_id, 'additional_user_meta', true ) ); - } - - $user_meta_keys_after_delete = $wpdb->get_col( "SELECT meta_key FROM $wpdb->usermeta" ); - $this->assertEqualSets( - [ - UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, - UserRESTEndpointExtension::USER_FIELD_REVIEW_PANEL_DISMISSED_FOR_TEMPLATE_MODE, - ], - array_unique( array_diff( $user_meta_keys_before_delete, $user_meta_keys_after_delete ) ) - ); - } - - /** @return array */ - private function create_data() { - - $validated_url_post_ids = []; - - $meta_input = [ - 'public_key' => 'public value', - '_private_key' => 'private value', - ]; - - $post_ids = self::factory()->post->create_many( - 3, - [ - 'post_type' => 'post', - 'meta_input' => $meta_input, - ] - ); - - $post_tag_terms = self::factory()->term->create_many( - 5, - [ - 'taxonomy' => 'post_tag', - ] - ); - $category_terms = self::factory()->term->create_many( - 5, - [ - 'taxonomy' => 'category', - ] - ); - foreach ( array_merge( $post_tag_terms, $category_terms ) as $term_id ) { - foreach ( $meta_input as $key => $value ) { - update_term_meta( $term_id, $key, $value ); - } - } - - foreach ( $post_ids as $post_id ) { - wp_set_object_terms( $post_id, $post_tag_terms, 'post_tag' ); - wp_set_object_terms( $post_id, $category_terms, 'category' ); - - $validated_url_post_ids[] = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - [ 'code' => 'bar' ], - [ 'code' => 'baz' ], - ], - get_permalink( $post_id ), - [ - 'queried_object' => [ - 'type' => 'post', - 'id' => $post_id, - ], - 'php_fatal_error' => [ - 'message' => 'Bad', - 'file' => __FILE__, - 'line' => __LINE__, - ], - 'stylesheets' => [ - [ '...' ], - ], - ] - ); - } - - $page_ids = self::factory()->post->create_many( - 3, - [ - 'post_type' => 'page', - 'meta_input' => $meta_input, - ] - ); - foreach ( $page_ids as $page_id ) { - $validated_url_post_ids[] = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'a' ], - [ 'code' => 'b' ], - [ 'code' => 'c' ], - ], - get_permalink( $page_id ), - [ - 'queried_object' => [ - 'type' => 'post', - 'id' => $page_id, - ], - 'stylesheets' => [ - [ '...' ], - ], - ] - ); - } - - return compact( - 'post_ids', - 'page_ids', - 'validated_url_post_ids', - 'post_tag_terms', - 'category_terms', - 'meta_input' - ); - } - - /** - * @covers \AmpProject\AmpWP\delete_posts() - */ - public function test_delete_posts() { - global $wpdb; - - $data = $this->create_data(); - - $post_types_before_delete = $wpdb->get_col( "SELECT post_type FROM $wpdb->posts" ); - $post_meta_keys_before_delete = $wpdb->get_col( "SELECT meta_key FROM $wpdb->postmeta" ); - - delete_posts(); - $this->flush_cache(); - - foreach ( $data['post_ids'] as $post_id ) { - $this->assertInstanceOf( WP_Post::class, get_post( $post_id ) ); - foreach ( $data['meta_input'] as $key => $value ) { - $this->assertEquals( $value, get_post_meta( $post_id, $key, true ) ); - } - } - foreach ( $data['page_ids'] as $page_id ) { - $this->assertInstanceOf( WP_Post::class, get_post( $page_id ) ); - foreach ( $data['meta_input'] as $key => $value ) { - $this->assertEquals( $value, get_post_meta( $page_id, $key, true ) ); - } - } - foreach ( $data['validated_url_post_ids'] as $id ) { - $this->assertEmpty( get_post( $id ) ); - } - - $post_types_after_delete = $wpdb->get_col( "SELECT post_type FROM $wpdb->posts" ); - $post_meta_keys_after_delete = $wpdb->get_col( "SELECT meta_key FROM $wpdb->postmeta" ); - - $this->assertEqualSets( - [ - AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - ], - array_unique( array_diff( $post_types_before_delete, $post_types_after_delete ) ) - ); - $this->assertContains( 'post', $post_types_after_delete ); - $this->assertContains( 'page', $post_types_after_delete ); - - $this->assertEqualSets( - [ - AMP_Validated_URL_Post_Type::PHP_FATAL_ERROR_POST_META_KEY, - AMP_Validated_URL_Post_Type::QUERIED_OBJECT_POST_META_KEY, - AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY, - AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY, - ], - array_unique( array_diff( $post_meta_keys_before_delete, $post_meta_keys_after_delete ) ) - ); - foreach ( array_keys( $data['meta_input'] ) as $meta_key ) { - $this->assertContains( $meta_key, $post_meta_keys_after_delete ); - } - } - - /** - * @covers \AmpProject\AmpWP\delete_terms() - */ - public function test_delete_terms() { - global $wpdb; - - $data = $this->create_data(); - - $term_meta_keys_before_delete = $wpdb->get_col( "SELECT meta_key FROM $wpdb->termmeta" ); - $term_taxonomies_before_delete = $wpdb->get_col( "SELECT taxonomy FROM $wpdb->term_taxonomy" ); - $term_slugs_before_delete = $wpdb->get_col( "SELECT slug FROM $wpdb->terms" ); - - $validation_error_terms = get_terms( - [ - 'taxonomy' => AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, - 'hide_empty' => false, - ] - ); - $this->assertGreaterThan( 0, count( $validation_error_terms ) ); - - delete_terms(); - $this->flush_cache(); - - foreach ( $data['post_ids'] as $post_id ) { - $this->assertInstanceOf( WP_Post::class, get_post( $post_id ) ); - $this->assertEqualSets( - $data['post_tag_terms'], - wp_list_pluck( wp_get_post_terms( $post_id, 'post_tag' ), 'term_id' ) - ); - $this->assertEqualSets( - $data['category_terms'], - wp_list_pluck( wp_get_post_terms( $post_id, 'category' ), 'term_id' ) - ); - } - - foreach ( $validation_error_terms as $term ) { - $this->assertEmpty( get_term( $term->term_id ) ); - } - foreach ( $data['post_tag_terms'] as $term_id ) { - $this->assertInstanceOf( WP_Term::class, get_term( $term_id ) ); - foreach ( $data['meta_input'] as $key => $value ) { - $this->assertEquals( $value, get_term_meta( $term_id, $key, true ) ); - } - } - foreach ( $data['category_terms'] as $term_id ) { - $this->assertInstanceOf( WP_Term::class, get_term( $term_id ) ); - foreach ( $data['meta_input'] as $key => $value ) { - $this->assertEquals( $value, get_term_meta( $term_id, $key, true ) ); - } - } - - $term_meta_keys_after_delete = $wpdb->get_col( "SELECT meta_key FROM $wpdb->termmeta" ); - $this->assertEqualSets( - [ - 'created_date_gmt', - ], - array_unique( array_diff( $term_meta_keys_before_delete, $term_meta_keys_after_delete ) ) - ); - foreach ( array_keys( $data['meta_input'] ) as $key ) { - $this->assertContains( $key, $term_meta_keys_after_delete ); - } - - $term_taxonomies_after_delete = $wpdb->get_col( "SELECT taxonomy FROM $wpdb->term_taxonomy" ); - $this->assertEqualSets( - [ - AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, - ], - array_unique( array_diff( $term_taxonomies_before_delete, $term_taxonomies_after_delete ) ) - ); - $this->assertContains( 'post_tag', $term_taxonomies_after_delete ); - $this->assertContains( 'category', $term_taxonomies_after_delete ); - - $term_slugs_after_delete = $wpdb->get_col( "SELECT slug FROM $wpdb->terms" ); - foreach ( array_diff( $term_slugs_before_delete, $term_slugs_after_delete ) as $deleted_slug ) { - $this->assertMatchesRegularExpression( '/^[0-9a-f]{32}$/', $deleted_slug ); - } - $this->assertContains( 'uncategorized', $term_slugs_after_delete ); - - $this->assertCount( - 0, - get_terms( - [ - 'taxonomy' => AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, - 'hide_empty' => false, - ] - ) - ); - - $term_ids_after_delete = $wpdb->get_col( "SELECT term_id FROM $wpdb->terms" ); - foreach ( $validation_error_terms as $validation_error_term ) { - $this->assertNotContains( $validation_error_term->term_id, $term_ids_after_delete ); - } - foreach ( $term_ids_after_delete as $term_id ) { - $term = get_term( $term_id ); - $this->assertInstanceOf( WP_Term::class, $term ); - $this->assertNotEquals( AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, $term->taxonomy ); - $this->assertTrue( taxonomy_exists( $term->taxonomy ) ); - if ( 'uncategorized' !== $term->slug ) { - $objects = get_objects_in_term( $term_id, [ 'post_tag', 'category' ] ); - $this->assertNotEmpty( $objects ); - } - } - } - - /** @return array */ - public function get_data_to_test_delete_transients() { - return [ - 'using_ext_object_cache' => [ true ], - 'not_using_ext_object_cache' => [ false ], - ]; - } - - /** - * @dataProvider get_data_to_test_delete_transients - * @covers \AmpProject\AmpWP\delete_transients() - */ - public function test_delete_transients( $using_ext_object_cache ) { - global $wpdb; - - wp_using_ext_object_cache( $using_ext_object_cache ); - - // Non-AMP transients. - set_transient( 'foo', 1 ); - set_transient( 'bar', 2, MINUTE_IN_SECONDS ); - set_transient( 'baz', 3, HOUR_IN_SECONDS ); - - // AMP transients. - set_transient( BlockSources::class . BlockSources::CACHE_KEY, '...', BlockSources::CACHE_TIMEOUT ); - set_transient( 'amp-parsed-stylesheet-v10-1', [ '...' ], MONTH_IN_SECONDS ); - set_transient( 'amp-parsed-stylesheet-v10-2', [ '...' ], MONTH_IN_SECONDS ); - set_transient( 'amp-parsed-stylesheet-v10-3', [ '...' ], MONTH_IN_SECONDS ); - set_transient( 'amp-parsed-stylesheet-v10-3', [ '...' ], MONTH_IN_SECONDS ); - set_transient( 'amp_error_index_counts', '...' ); - set_transient( 'amp_has_page_caching', '...' ); - set_transient( 'amp_img_123abc', '...' ); - set_transient( 'amp_lock_123abc', '...' ); - set_transient( 'amp_new_validation_error_urls_count', '...' ); - set_transient( 'amp_plugin_activation_validation_errors', '...' ); - set_transient( 'amp_remote_request_101623f47561580a914e5d56e153cf6c', '...' ); - set_transient( 'amp_themes_wporg', '...', DAY_IN_SECONDS ); - - $transient_keys_before_delete = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_%'" ); - $num_queries_before = $wpdb->num_queries; - delete_transients(); - $num_queries_after = $wpdb->num_queries; - $transient_keys_after_delete = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_%'" ); - - if ( $using_ext_object_cache ) { - $this->assertEquals( $num_queries_before, $num_queries_after ); - $this->assertEquals( $transient_keys_before_delete, $transient_keys_after_delete ); - } else { - $this->assertEquals( $num_queries_before + 1, $num_queries_after ); - $this->assertContains( - '_transient_amp_themes_wporg', - $transient_keys_before_delete - ); - $this->assertContains( - '_transient_timeout_amp_themes_wporg', - $transient_keys_before_delete - ); - $this->assertEqualSets( - [ - '_transient_bar', - '_transient_baz', - '_transient_foo', - '_transient_timeout_bar', - '_transient_timeout_baz', - ], - $transient_keys_after_delete - ); - } - } - - /** - * @covers \AmpProject\AmpWP\delete_options() - * @covers \AmpProject\AmpWP\delete_user_metadata() - * @covers \AmpProject\AmpWP\delete_posts() - * @covers \AmpProject\AmpWP\delete_terms() - * @covers \AmpProject\AmpWP\delete_transients() - * @covers \AmpProject\AmpWP\remove_plugin_data() - */ - public function test_remove_plugin_data() { - global $wpdb; - wp_using_ext_object_cache( false ); - - // Create dummy data. - $blog_name = 'Sample Blog Name'; - $meta_key = 'amp_meta_key'; - $meta_value = 'amp_meta_value'; - - update_option( 'blogname', $blog_name ); - update_option( - 'amp-options', - [ 'reader_theme' => 'foo' ] - ); - - $users = $this->factory()->user->create_many( 2, [ 'role' => 'administrator' ] ); - - foreach ( $users as $user ) { - update_user_meta( $user, 'amp_dev_tools_enabled', 'Yes' ); - update_user_meta( $user, 'amp_review_panel_dismissed_for_template_mode', 'Yes' ); - update_user_meta( $user, 'additional_user_meta', 'Yes' ); - } - - $amp_validated_post = $this->factory()->post->create_and_get( - [ - 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, - 'meta_input' => [ - $meta_key => $meta_value, - ], - ] - ); - - $page_post = $this->factory()->post->create_and_get( - [ - 'post_type' => 'page', - 'meta_input' => [ - $meta_key => $meta_value, - ], - ] - ); - - $amp_error_term = $this->factory()->term->create_and_get( - [ - 'taxonomy' => AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, - ] - ); - - update_term_meta( $amp_error_term->term_id, $meta_key, $meta_value ); - wp_add_object_terms( $amp_validated_post->ID, $amp_error_term->term_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ); - - $post_tag_term = $this->factory()->term->create_and_get( - [ - 'taxonomy' => 'post_tag', - ] - ); - update_term_meta( $post_tag_term->term_id, $meta_key, $meta_value ); - wp_add_object_terms( $page_post->ID, $post_tag_term->term_id, 'post_tag' ); - $post_tag_term_taxonomy_row_count = $wpdb->query( "SELECT * FROM {$wpdb->term_taxonomy} WHERE taxonomy = 'post_tag';" ); - $this->assertGreaterThan( 0, $post_tag_term_taxonomy_row_count ); - $post_tag_term_relationships_row_count = $wpdb->query( $wpdb->prepare( "SELECT * FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = %d", $post_tag_term->term_id ) ); - $this->assertGreaterThan( 0, $post_tag_term_relationships_row_count ); - - set_theme_mod( 'color', 'blue' ); - set_theme_mod( AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY, [ 'color' => time() ] ); - update_option( - 'theme_mods_foo', - [ - 'color' => 'red', - AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY => [ - 'color' => time(), - ], - ] - ); - - $transient_groups_to_remove = [ - 'amp-parsed-stylesheet-v...', - 'amp_img_...', - 'amp_new_validation_error_urls_count', - 'amp_error_index_counts', - 'amp_plugin_activation_validation_errors', - 'amp_themes_wporg', - 'amp_lock_...', - ]; - - foreach ( $transient_groups_to_remove as $transient_group ) { - set_transient( $transient_group, 'Sample value', 10000 ); - } - - set_transient( 'amp_sample_group', 'AMP Sample value', 10000 ); - - // Mock uninstall const. - if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) { - define( 'WP_UNINSTALL_PLUGIN', 'Yes' ); - } - - // Test 1: With option to keep AMP data ON. - AMP_Options_Manager::update_option( Option::DELETE_DATA_AT_UNINSTALL, false ); - - $num_queries_before = $wpdb->num_queries; - require AMP__DIR__ . '/uninstall.php'; - $this->flush_cache(); - $this->assertEquals( $num_queries_before, $wpdb->num_queries ); - - $this->assertNotEmpty( get_option( AMP_Options_Manager::OPTION_NAME, false ) ); - - // Test 2: With option to keep AMP data OFF. - AMP_Options_Manager::update_option( Option::DELETE_DATA_AT_UNINSTALL, true ); - - $num_queries_before = $wpdb->num_queries; - require AMP__DIR__ . '/uninstall.php'; - $this->flush_cache(); - $this->assertGreaterThan( $num_queries_before, $wpdb->num_queries ); - - // Assert that AMP related data does get deleted. - $this->assertEmpty( get_option( AMP_Options_Manager::OPTION_NAME, false ) ); - - $this->assertEmpty( get_post( $amp_validated_post->ID ) ); - $this->assertEmpty( get_post_meta( $amp_validated_post->ID, $meta_key, true ) ); - - $this->assertEmpty( get_term( $amp_error_term->term_id ) ); - $this->assertEmpty( get_term_meta( $amp_error_term->term_id, $meta_key, true ) ); - - // Assert that there is no data left for `amp_validation_error` taxonomy. - $this->assertEmpty( - $wpdb->query( - $wpdb->prepare( - "SELECT * FROM {$wpdb->term_taxonomy} WHERE taxonomy = %s;", - AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG - ) - ) - ); - $this->assertEmpty( - $wpdb->query( - $wpdb->prepare( - "SELECT * FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = %d", - $amp_error_term->term_id - ) - ) - ); - $this->assertEmpty( - $wpdb->query( - $wpdb->prepare( - "SELECT * FROM {$wpdb->terms} WHERE term_id = %d", - $amp_error_term->term_id - ) - ) - ); - - // Assert that other than AMP related data does not get deleted. - $this->assertInstanceOf( WP_Post::class, get_post( $page_post->ID ) ); - $this->assertEquals( $meta_value, get_post_meta( $page_post->ID, $meta_key, true ) ); - $this->assertInstanceOf( WP_Term::class, get_term( $post_tag_term->term_id ) ); - $this->assertEquals( $meta_value, get_term_meta( $post_tag_term->term_id, $meta_key, true ) ); - - // Assert that there is no deleted other than `amp_validation_error` taxonomy. - $this->assertEquals( - $post_tag_term_taxonomy_row_count, - $wpdb->query( "SELECT * FROM {$wpdb->term_taxonomy} WHERE taxonomy = 'post_tag';" ) - ); - $this->assertEquals( - $post_tag_term_relationships_row_count, - $wpdb->query( - $wpdb->prepare( - "SELECT * FROM {$wpdb->term_relationships} WHERE term_taxonomy_id = %d", - $post_tag_term->term_id - ) - ) - ); - $this->assertEquals( - 1, - $wpdb->query( - $wpdb->prepare( - "SELECT * FROM {$wpdb->terms} WHERE term_id = %d", - $post_tag_term->term_id - ) - ) - ); - - $this->assertEquals( $blog_name, get_option( 'blogname', false ) ); - - $this->assertEquals( 'blue', get_theme_mod( 'color' ) ); - $this->assertFalse( get_theme_mod( AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY ) ); - $foo_theme_mods = get_option( 'theme_mods_foo' ); - $this->assertEquals( 'red', $foo_theme_mods['color'] ); - $this->assertArrayNotHasKey( AMP_Template_Customizer::THEME_MOD_TIMESTAMPS_KEY, $foo_theme_mods ); - - foreach ( $transient_groups_to_remove as $transient_group ) { - $this->assertEmpty( get_transient( $transient_group ) ); - } - - $this->assertEquals( 'AMP Sample value', get_transient( 'amp_sample_group' ) ); - - foreach ( $users as $user ) { - $this->assertEmpty( get_user_meta( $user, 'amp_dev_tools_enabled', true ) ); - $this->assertEmpty( get_user_meta( $user, 'amp_review_panel_dismissed_for_template_mode', true ) ); - $this->assertEquals( 'Yes', get_user_meta( $user, 'additional_user_meta', true ) ); - } - } -} diff --git a/tests/php/test-wp-http-remote-get-request.php b/tests/php/test-wp-http-remote-get-request.php deleted file mode 100644 index a769a301132..00000000000 --- a/tests/php/test-wp-http-remote-get-request.php +++ /dev/null @@ -1,72 +0,0 @@ - [ [ 'something' => 'to test' ], 'something', 'to test' ], - - 'accepts traversables' => [ - new Requests_Utility_CaseInsensitiveDictionary( [ 'something' => 'to test' ] ), - 'something', - 'to test', - ], - ]; - } - - /** - * Test whether the headers are correctly parsed. - * - * @dataProvider headers_test_data() - * - * @covers ::get() - * - * @param mixed $headers Headers that are provided to the response. - * @param string $header_to_check Name of the header entry to check. - * @param mixed $expected Expected header entry value. - */ - public function test_processing_headers( $headers, $header_to_check, $expected ) { - $href = 'https://example.com/some_file.txt'; - - add_filter( - 'pre_http_request', - function( $preempt, $request, $url ) use ( $href, $headers ) { - $this->assertMatchesRegularExpression( '#^https?://#', $url ); - if ( set_url_scheme( $url, 'https' ) === set_url_scheme( $href, 'https' ) ) { - $preempt = [ - 'response' => [ - 'code' => 200, - ], - 'headers' => $headers, - 'body' => '', - ]; - } - return $preempt; - }, - 10, - 3 - ); - - $remote_request = new WpHttpRemoteGetRequest(); - $response = $remote_request->get( 'https://example.com/some_file.txt' ); - $this->assertEquals( $expected, $response->getHeader( $header_to_check )[0] ); - } -} diff --git a/tests/php/validation/test-class-amp-validated-url-post-type.php b/tests/php/validation/test-class-amp-validated-url-post-type.php deleted file mode 100644 index 228903a9892..00000000000 --- a/tests/php/validation/test-class-amp-validated-url-post-type.php +++ /dev/null @@ -1,2156 +0,0 @@ -register_core_themes(); - } - - public function tear_down() { - global $current_screen; - $current_screen = null; - - $this->restore_theme_directories(); - - parent::tear_down(); - } - - /** - * Test register. - * - * @covers \AMP_Validated_URL_Post_Type::register() - * @covers \AMP_Validated_URL_Post_Type::add_admin_hooks() - */ - public function test_register() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->assertFalse( is_admin() ); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - AMP_Validated_URL_Post_Type::register(); - $amp_post_type = get_post_type_object( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ); - - $this->assertContains( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, get_post_types() ); - $this->assertEquals( [], get_all_post_type_supports( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ) ); - $this->assertEquals( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, $amp_post_type->name ); - $this->assertEquals( 'AMP Validated URLs', $amp_post_type->label ); - $this->assertEquals( false, $amp_post_type->public ); - $this->assertTrue( $amp_post_type->show_ui ); - if ( ( new DependencySupport() )->has_support() ) { - $this->assertEquals( AMP_Options_Manager::OPTION_NAME, $amp_post_type->show_in_menu ); - } else { - $this->assertFalse( $amp_post_type->show_in_menu ); - } - $this->assertEquals( ( new DependencySupport() )->has_support(), $amp_post_type->show_in_admin_bar ); - $this->assertNotContains( AMP_Validated_URL_Post_Type::REMAINING_ERRORS, wp_removable_query_args() ); - $this->assertEquals( - ( new DependencySupport() )->has_support() ? 10 : false, - has_action( 'admin_menu', [ self::TESTED_CLASS, 'update_validated_url_menu_item' ] ) - ); - - // Make sure that add_admin_hooks() gets called. - set_current_screen( 'index.php' ); - AMP_Validated_URL_Post_Type::register(); - $this->assertContains( AMP_Validated_URL_Post_Type::REMAINING_ERRORS, wp_removable_query_args() ); - - $post = self::factory()->post->create( [ 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ] ); - $this->assertTrue( user_can( wp_get_current_user()->ID, 'edit_post', $post ) ); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'subscriber' ] ) ); - $this->assertFalse( current_user_can( 'edit_post', $post ) ); - } - - /** - * Test add_admin_hooks. - * - * @covers \AMP_Validated_URL_Post_Type::add_admin_hooks() - */ - public function test_add_admin_hooks() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Validated_URL_Post_Type::add_admin_hooks(); - - $this->assertEquals( 10, has_action( 'admin_enqueue_scripts', [ self::TESTED_CLASS, 'enqueue_edit_post_screen_scripts' ] ) ); - $this->assertEquals( PHP_INT_MAX, has_action( 'add_meta_boxes', [ self::TESTED_CLASS, 'add_meta_boxes' ] ) ); - $this->assertEquals( 10, has_action( 'edit_form_top', [ self::TESTED_CLASS, 'print_url_as_title' ] ) ); - - $this->assertEquals( 10, has_filter( 'the_title', [ self::TESTED_CLASS, 'filter_the_title_in_post_list_table' ] ) ); - $this->assertEquals( 10, has_filter( 'restrict_manage_posts', [ self::TESTED_CLASS, 'render_post_filters' ] ) ); - $this->assertEquals( 10, has_filter( 'manage_' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG . '_posts_columns', [ self::TESTED_CLASS, 'add_post_columns' ] ) ); - $this->assertEquals( 10, has_filter( 'manage_' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG . '_columns', [ self::TESTED_CLASS, 'add_single_post_columns' ] ) ); - $this->assertEquals( 10, has_action( 'manage_posts_custom_column', [ self::TESTED_CLASS, 'output_custom_column' ] ) ); - $this->assertEquals( PHP_INT_MAX - 1, has_filter( 'post_row_actions', [ self::TESTED_CLASS, 'filter_post_row_actions' ] ) ); - $this->assertEquals( 10, has_filter( 'bulk_actions-edit-' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, [ self::TESTED_CLASS, 'filter_bulk_actions' ] ) ); - $this->assertEquals( 10, has_filter( 'bulk_actions-' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, '__return_false' ) ); - $this->assertEquals( 10, has_filter( 'handle_bulk_actions-edit-' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG, [ self::TESTED_CLASS, 'handle_bulk_action' ] ) ); - $this->assertEquals( 10, has_action( 'admin_notices', [ self::TESTED_CLASS, 'print_admin_notice' ] ) ); - $this->assertEquals( 10, has_action( 'admin_action_' . AMP_Validated_URL_Post_Type::VALIDATE_ACTION, [ self::TESTED_CLASS, 'handle_validate_request' ] ) ); - $this->assertEquals( 10, has_action( 'post_action_' . AMP_Validated_URL_Post_Type::UPDATE_POST_TERM_STATUS_ACTION, [ self::TESTED_CLASS, 'handle_validation_error_status_update' ] ) ); - - $post = self::factory()->post->create_and_get( [ 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ] ); - $this->assertEquals( '', apply_filters( 'post_date_column_status', 'publish', $post ) ); - $this->assertEquals( 'publish', apply_filters( 'post_date_column_status', 'publish', self::factory()->post->create_and_get() ) ); - - $this->assertContains( 'amp_actioned', wp_removable_query_args() ); - $this->assertContains( 'amp_taxonomy_terms_updated', wp_removable_query_args() ); - $this->assertContains( AMP_Validated_URL_Post_Type::REMAINING_ERRORS, wp_removable_query_args() ); - $this->assertContains( 'amp_urls_tested', wp_removable_query_args() ); - $this->assertContains( 'amp_validate_error', wp_removable_query_args() ); - } - - /** - * Test update_validated_url_menu_item. - * - * @covers \AMP_Validated_URL_Post_Type::update_validated_url_menu_item() - */ - public function test_update_validated_url_menu_item() { - $admin_user = self::factory()->user->create_and_get( [ 'role' => 'administrator' ] ); - wp_set_current_user( $admin_user->ID ); - global $submenu; - - $original_submenu = $submenu; - - AMP_Validation_Manager::init(); // Register the post type and taxonomy. - AMP_Validated_URL_Post_Type::update_validated_url_menu_item(); - - $submenu[ AMP_Options_Manager::OPTION_NAME ] = [ - 0 => [ - 0 => 'General', - 1 => 'manage_options', - 2 => 'amp-options', - 3 => 'AMP Settings', - ], - 1 => [ - 0 => 'Analytics', - 1 => 'manage_options', - 2 => 'amp-analytics-options', - 3 => 'AMP Analytics Options', - ], - 2 => [ - 0 => 'All Validated URLs', - 1 => 'amp_validate', - 2 => 'edit.php?post_type=amp_validated_url', - 3 => 'AMP Validated URLs', - ], - ]; - - AMP_Validated_URL_Post_Type::update_validated_url_menu_item(); - $this->assertSame( 'Validated URLs', $submenu[ AMP_Options_Manager::OPTION_NAME ][2][0] ); - - update_user_meta( $admin_user->ID, UserAccess::USER_FIELD_DEVELOPER_TOOLS_ENABLED, wp_json_encode( true ) ); - - AMP_Validated_URL_Post_Type::update_validated_url_menu_item(); - if ( Services::get( 'dependency_support' )->has_support() ) { - $this->assertSame( 'Validated URLs ', $submenu[ AMP_Options_Manager::OPTION_NAME ][2][0] ); - } else { - $this->assertSame( 'Validated URLs', $submenu[ AMP_Options_Manager::OPTION_NAME ][2][0] ); - } - - $submenu = $original_submenu; - } - - /** - * Test get_invalid_url_validation_errors and display_invalid_url_validation_error_counts_summary. - * - * @covers \AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors() - * @covers \AMP_Validated_URL_Post_Type::display_invalid_url_validation_error_counts_summary() - * @covers \AMP_Validated_URL_Post_Type::store_validation_errors() - */ - public function test_get_invalid_url_validation_errors() { - $this->accept_sanitization_by_default( false ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - AMP_Validation_Manager::init(); - $post = self::factory()->post->create(); - $this->assertEmpty( AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( get_permalink( $post ) ) ); - - add_filter( - 'amp_validation_error_default_sanitized', - static function( $sanitized, $error ) { - if ( 'new accepted' === $error['code'] ) { - $sanitized = true; - } elseif ( 'new rejected' === $error['code'] ) { - $sanitized = false; - } - return $sanitized; - }, - 10, - 2 - ); - - add_filter( - 'amp_validation_error_sanitized', - static function( $sanitized, $error ) { - if ( 'accepted' === $error['code'] ) { - $sanitized = true; - } elseif ( 'rejected' === $error['code'] ) { - $sanitized = false; - } - return $sanitized; - }, - 10, - 2 - ); - - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'accepted' ], - [ 'code' => 'rejected' ], - [ 'code' => 'new accepted' ], - [ 'code' => 'new rejected' ], - ], - get_permalink( $post ) - ); - $this->assertNotInstanceOf( 'WP_Error', $invalid_url_post_id ); - - $errors = AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( get_permalink( $post ) ); - $this->assertCount( 4, $errors ); - - $error = array_shift( $errors ); - $this->assertEquals( 'accepted', $error['data']['code'] ); - $this->assertEquals( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, $error['term_status'] ); - $error = array_shift( $errors ); - $this->assertEquals( 'rejected', $error['data']['code'] ); - $this->assertEquals( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, $error['term_status'] ); - $error = array_shift( $errors ); - $this->assertEquals( 'new accepted', $error['data']['code'] ); - $this->assertEquals( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS, $error['term_status'] ); - $error = array_shift( $errors ); - $this->assertEquals( 'new rejected', $error['data']['code'] ); - $this->assertEquals( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS, $error['term_status'] ); - - $errors = AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( get_permalink( $post ), [ 'ignore_accepted' => true ] ); - $this->assertCount( 2, $errors ); - $error = array_shift( $errors ); - $this->assertEquals( 'rejected', $error['data']['code'] ); - $this->assertEquals( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, $error['term_status'] ); - $error = array_shift( $errors ); - $this->assertEquals( 'new rejected', $error['data']['code'] ); - $this->assertEquals( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS, $error['term_status'] ); - - $summary = get_echo( [ AMP_Validated_URL_Post_Type::class, 'display_invalid_url_validation_error_counts_summary' ], [ $invalid_url_post_id ] ); - $this->assertStringContainsString( 'Invalid markup kept: 2', $summary ); - $this->assertStringContainsString( 'Invalid markup removed: 2', $summary ); - } - - /** - * Test for get_invalid_url_post(). - * - * @covers \AMP_Validated_URL_Post_Type::get_invalid_url_post() - */ - public function test_get_invalid_url_post() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - AMP_Validation_Manager::init(); - $post = self::factory()->post->create_and_get(); - $this->assertEquals( null, AMP_Validated_URL_Post_Type::get_invalid_url_post( get_permalink( $post ) ) ); - - $invalid_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - ], - get_permalink( $post ) - ); - $this->assertNotInstanceOf( 'WP_Error', $invalid_post_id ); - - $this->assertEquals( - $invalid_post_id, - AMP_Validated_URL_Post_Type::get_invalid_url_post( get_permalink( $post ) )->ID - ); - - // Test trashed. - wp_trash_post( $invalid_post_id ); - $this->assertNull( AMP_Validated_URL_Post_Type::get_invalid_url_post( get_permalink( $post ) ) ); - $args = [ 'include_trashed' => true ]; - $this->assertEquals( - $invalid_post_id, - AMP_Validated_URL_Post_Type::get_invalid_url_post( get_permalink( $post ), $args )->ID - ); - wp_untrash_post( $invalid_post_id ); - - // Test normalized. - $args = [ 'normalize' => false ]; - $url = add_query_arg( - array_fill_keys( wp_removable_query_args(), 'true' ), - get_permalink( $post ) . '#baz' - ); - $url = set_url_scheme( $url, 'http' ); - $this->assertNull( AMP_Validated_URL_Post_Type::get_invalid_url_post( $url, $args ) ); - $args = [ 'normalize' => true ]; - $this->assertEquals( $invalid_post_id, AMP_Validated_URL_Post_Type::get_invalid_url_post( $url, $args )->ID ); - $this->assertEquals( $invalid_post_id, AMP_Validated_URL_Post_Type::get_invalid_url_post( $url )->ID ); - $url = set_url_scheme( get_permalink( $post ), 'http' ); - $this->assertNull( AMP_Validated_URL_Post_Type::get_invalid_url_post( $url, [ 'normalize' => false ] ) ); - $this->assertEquals( $invalid_post_id, AMP_Validated_URL_Post_Type::get_invalid_url_post( $url, [ 'normalize' => true ] )->ID ); - } - - /** - * Test get_url_from_post. - * - * @covers \AMP_Validated_URL_Post_Type::get_url_from_post() - */ - public function test_get_url_from_post() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - AMP_Validation_Manager::init(); - $post = self::factory()->post->create_and_get(); - - $this->assertNull( AMP_Validated_URL_Post_Type::get_url_from_post( 0 ) ); - $this->assertNull( AMP_Validated_URL_Post_Type::get_url_from_post( $post ) ); - - $invalid_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - ], - get_permalink( $post ) - ); - $this->assertNotInstanceOf( 'WP_Error', $invalid_post_id ); - - $this->assertEquals( - amp_add_paired_endpoint( get_permalink( $post ) ), - AMP_Validated_URL_Post_Type::get_url_from_post( $invalid_post_id ) - ); - - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $this->assertEquals( - get_permalink( $post ), - AMP_Validated_URL_Post_Type::get_url_from_post( $invalid_post_id ) - ); - - // Check URL scheme. - add_filter( - 'home_url', - static function ( $url ) { - return set_url_scheme( $url, 'http' ); - }, - 10 - ); - $this->assertEquals( 'http', wp_parse_url( AMP_Validated_URL_Post_Type::get_url_from_post( $invalid_post_id ), PHP_URL_SCHEME ) ); - add_filter( - 'home_url', - static function ( $url ) { - return set_url_scheme( $url, 'https' ); - }, - 10 - ); - $this->assertEquals( 'https', wp_parse_url( AMP_Validated_URL_Post_Type::get_url_from_post( $invalid_post_id ), PHP_URL_SCHEME ) ); - } - - /** - * Test for store_validation_errors() - * - * @covers \AMP_Validated_URL_Post_Type::store_validation_errors() - */ - public function test_store_validation_errors() { - global $post; - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - AMP_Validation_Manager::init(); - $post = self::factory()->post->create_and_get(); - - add_filter( - 'amp_validation_error_sanitized', - static function( $sanitized, $error ) { - if ( 'accepted' === $error['code'] ) { - $sanitized = true; - } elseif ( 'rejected' === $error['code'] ) { - $sanitized = false; - } - return $sanitized; - }, - 10, - 2 - ); - - $errors = [ - [ - 'code' => 'accepted', - 'sources' => [ - [ - 'type' => 'plugin', - 'name' => 'amp', - 'evil' => '', // Test slash preservation and kses suspension. - ], - ], - ], - [ - 'code' => 'rejected', - 'evil' => '', // Test slash preservation and kses suspension. - 'sources' => [ - [ - 'type' => 'theme', - 'name' => 'twentyseventeen', - ], - ], - ], - [ - 'code' => 'rejected', - 'evil' => '', // Test protection against wp_targeted_link_rel JSON corruption. - 'sources' => [ - [ - 'type' => 'theme', - 'name' => 'twentyseventeen', - ], - ], - ], - [ - 'code' => 'new', - 'sources' => [ - [ - 'type' => 'core', - 'name' => 'wp-includes', - ], - ], - ], - ]; - - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - $errors, - get_permalink( $post ), - [ - 'invalid_url_post' => 0, - ] - ); - $this->assertNotInstanceOf( 'WP_Error', $invalid_url_post_id ); - $this->assertNotEquals( $invalid_url_post_id, $post->ID, 'Passing an empty invalid_url_post should not re-use the global $post ever.' ); - - // Test resurrection from trash. - wp_trash_post( $invalid_url_post_id ); - $this->assertEquals( - $invalid_url_post_id, - AMP_Validated_URL_Post_Type::store_validation_errors( - $errors, - get_permalink( $post ), - [ - 'queried_object' => [ - 'type' => 'post', - 'id' => $post->ID, - ], - ] - ) - ); - $this->assertEquals( 'publish', get_post_status( $invalid_url_post_id ) ); - $this->assertEquals( - [ - 'type' => 'post', - 'id' => $post->ID, - ], - get_post_meta( $invalid_url_post_id, '_amp_queried_object', true ) - ); - - // Test passing specific post to override the URL. - $this->assertEquals( - $invalid_url_post_id, - AMP_Validated_URL_Post_Type::store_validation_errors( - $errors, - home_url( '/something/else/' ), - [ - 'invalid_url_post' => $invalid_url_post_id, - ] - ) - ); - - $this->assertEquals( - home_url( '/something/else/', 'https' ), - get_post( $invalid_url_post_id )->post_title - ); - - $stored_errors = AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $invalid_url_post_id ); - $this->assertEquals( - $errors, - array_map( - static function( $stored_error ) { - return $stored_error['data']; - }, - $stored_errors - ) - ); - - $error_groups = [ - AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, - AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, - AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, - AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS, - ]; - - foreach ( $errors as $i => $error ) { - $stored_error = $stored_errors[ $i ]; - - $this->assertEquals( $error, $stored_error['data'] ); - - $sourceless_error = $error; - unset( $sourceless_error['sources'] ); - - /** - * Term. - * - * @var WP_Term $term - */ - $term = $stored_error['term']; - $this->assertEquals( $sourceless_error, json_decode( $term->description, true ) ); - - $this->assertNotEmpty( get_term_meta( $term->term_id, 'created_date_gmt', true ) ); - $this->assertEquals( $error_groups[ $i ], $stored_error['term_status'] ); - $this->assertEquals( $error_groups[ $i ], $term->term_group ); - } - } - - /** @covers AMP_Validated_URL_Post_Type::delete_stylesheets_postmeta_batch() */ - public function test_delete_stylesheets_postmeta_batch() { - - $old_post_id = self::factory()->post->create( - [ - 'post_type' => 'post', - 'post_date' => gmdate( 'Y-m-d H:i:s', strtotime( '1 year ago' ) ), - 'post_date_gmt' => gmdate( 'Y-m-d H:i:s', strtotime( '1 year ago' ) ), - ] - ); - add_post_meta( $old_post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY, [ 'Preserved!' ] ); - add_post_meta( $old_post_id, 'other', 'Also preserved!' ); - - // Expect none to be deleted initially. - $this->assertEquals( 0, AMP_Validated_URL_Post_Type::delete_stylesheets_postmeta_batch( 10, '1 week ago' ) ); - - // Insert four weeks of validated URLs. - $post_ids = []; - for ( $days_ago = 1; $days_ago <= 28; $days_ago++ ) { - $post_date = gmdate( 'Y-m-d H:i:s', strtotime( "$days_ago days ago" ) + 5 ); - $post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [], - home_url( "/days-ago-$days_ago/" ), - [ - 'stylesheets' => [ '/*...*/' ], - 'queried_object' => [ - 'type' => 'post', - 'id' => self::factory()->post->create(), - ], - ] - ); - wp_update_post( - [ - 'ID' => $post_id, - 'post_date_gmt' => $post_date, - 'post_date' => $post_date, - ] - ); - $post_ids[ $days_ago ] = $post_id; - } - - // Verify that no data is removed if looking before the oldest post. - $this->assertEquals( 0, AMP_Validated_URL_Post_Type::delete_stylesheets_postmeta_batch( 100, '1 month ago' ) ); - foreach ( $post_ids as $post_id ) { - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ) ); - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::QUERIED_OBJECT_POST_META_KEY ) ); - } - - // Delete just one post older than 3 weeks. - $this->assertEquals( 1, AMP_Validated_URL_Post_Type::delete_stylesheets_postmeta_batch( 1, '3 weeks ago' ) ); - foreach ( $post_ids as $days_ago => $post_id ) { - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::QUERIED_OBJECT_POST_META_KEY ) ); - if ( $days_ago > 27 ) { - $this->assertEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ), "Expected $days_ago days ago to be empty." ); - } else { - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ), "Expected $days_ago days ago to not be empty." ); - } - } - - // Delete everything older than 1 week, so that means 20 days of validated URLs since the 21st was deleted above . - $this->assertEquals( 20, AMP_Validated_URL_Post_Type::delete_stylesheets_postmeta_batch( 100, '1 week ago' ) ); - foreach ( $post_ids as $days_ago => $post_id ) { - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::QUERIED_OBJECT_POST_META_KEY ) ); - if ( $days_ago > 7 ) { - $this->assertEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ), "Expected $days_ago days ago to be empty." ); - } else { - $this->assertNotEmpty( get_post_meta( $post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY ), "Expected $days_ago days ago to not be empty." ); - } - } - - // Make sure other postmeta is retained. - $this->assertEquals( [ 'Preserved!' ], get_post_meta( $old_post_id, AMP_Validated_URL_Post_Type::STYLESHEETS_POST_META_KEY, true ) ); - $this->assertEquals( 'Also preserved!', get_post_meta( $old_post_id, 'other', true ) ); - } - - /** @return int */ - public function create_vanilla_post() { - return self::factory()->post->create( - [ - 'post_type' => 'post', - 'post_date' => gmdate( 'Y-m-d H:i:s', strtotime( '1 month ago' ) ), - ] - ); - } - - public function touch_validated_environment() { - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, ! AMP_Options_Manager::get_option( Option::ALL_TEMPLATES_SUPPORTED ) ); - } - - /** - * @param int $post_id - * @param int $timestamp - */ - public function update_post_date( $post_id, $timestamp ) { - $this->assertNotInstanceOf( - WP_Error::class, - wp_update_post( - [ - 'ID' => $post_id, - 'post_date' => gmdate( 'Y-m-d H:i:s', $timestamp ), - 'post_date_gmt' => gmdate( 'Y-m-d H:i:s', $timestamp ), - ], - true - ) - ); - } - - /** - * @covers \AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect() - * @covers \AMP_Validated_URL_Post_Type::garbage_collect_validated_urls() - */ - public function test_is_post_safe_to_garbage_collect_not_validated_url() { - $vanilla_post_id = $this->create_vanilla_post(); - - // Try giving a non-validated URL post a validated environment meta just to make sure it is truly ignored. - update_post_meta( $vanilla_post_id, AMP_Validated_URL_Post_Type::VALIDATED_ENVIRONMENT_POST_META_KEY, [ 'theme' => 'old' ] ); - - $this->assertFalse( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $vanilla_post_id ) ) ); - - AMP_Validated_URL_Post_Type::garbage_collect_validated_urls(); - - $this->assertSame( 'publish', get_post_status( $vanilla_post_id ) ); - } - - /** - * @covers \AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect() - * @covers \AMP_Validated_URL_Post_Type::garbage_collect_validated_urls() - */ - public function test_is_post_safe_to_garbage_collect_non_stale_validated_url() { - $vanilla_post_id = $this->create_vanilla_post(); - - $validated_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [], - home_url( '/' ) - ); - - $this->assertEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $validated_url_post_id ) ); - $this->assertFalse( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $validated_url_post_id ) ) ); - - AMP_Validated_URL_Post_Type::garbage_collect_validated_urls(); - - $this->assertSame( 'publish', get_post_status( $validated_url_post_id ) ); - $this->assertSame( 'publish', get_post_status( $vanilla_post_id ) ); - } - - /** @return array */ - public function get_error_sets() { - return [ - 'none' => [ - 'errors' => [], - ], - 'some' => [ - 'errors' => [ - [ 'code' => 'foo' ], - [ 'code' => 'bar' ], - [ 'code' => 'baz' ], - ], - ], - ]; - } - - /** - * @dataProvider get_error_sets - * @covers \AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect() - * @covers \AMP_Validated_URL_Post_Type::garbage_collect_validated_urls() - * - * @param array $errors - */ - public function test_is_post_safe_to_garbage_collect_stale_validated_url_with_one_old_and_one_new( $errors ) { - $vanilla_post_id = $this->create_vanilla_post(); - - $old_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( $errors, home_url( '/old/' ) ); - $this->update_post_date( $old_post_id, strtotime( '2 weeks ago' ) ); - $new_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( $errors, home_url( '/new/' ) ); - - $this->touch_validated_environment(); - $this->assertNotEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $old_post_id ) ); - $this->assertNotEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $new_post_id ) ); - $this->assertTrue( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $old_post_id ) ) ); - $this->assertTrue( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $new_post_id ) ) ); - - // Since this only garbage-collects posts that are older then 1 week, the new one will remain. - AMP_Validated_URL_Post_Type::garbage_collect_validated_urls(); - - $this->assertFalse( get_post_status( $old_post_id ) ); - $this->assertSame( 'publish', get_post_status( $new_post_id ) ); - $this->assertSame( 'publish', get_post_status( $vanilla_post_id ) ); - } - - /** @return array */ - public function get_validation_error_term_groups() { - $cases = []; - foreach ( [ true, false ] as $add_fresh ) { - $suffix = $add_fresh ? '_with_fresh_present' : '_without_fresh_present'; - - $cases = array_merge( - $cases, - [ - 'removed_reviewed' . $suffix => [ - 'term_group' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, - 'add_fresh' => $add_fresh, - ], - 'kept_unreviewed' . $suffix => [ - 'term_group' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS, - 'add_fresh' => $add_fresh, - ], - 'kept_reviewed' . $suffix => [ - 'term_group' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, - 'add_fresh' => $add_fresh, - ], - ] - ); - } - - return $cases; - } - - /** - * @dataProvider get_validation_error_term_groups - * @covers \AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect() - * @covers \AMP_Validated_URL_Post_Type::garbage_collect_validated_urls() - * - * @param int $term_group - */ - public function test_is_post_safe_to_garbage_collect_with_reviewed_or_kept_errors( $term_group, $add_fresh ) { - $vanilla_post_id = $this->create_vanilla_post(); - - $errors = [ - [ 'code' => 'foo' ], - [ 'code' => 'bar' ], - [ 'code' => 'baz' ], - ]; - - $stale_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( $errors, home_url( '/stale/' ) ); - $this->update_post_date( $stale_post_id, strtotime( '2 weeks ago' ) ); - $this->touch_validated_environment(); - $this->assertNotEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $stale_post_id ) ); - - $fresh_post_id = null; - if ( $add_fresh ) { - $fresh_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( $errors, home_url( '/fresh/' ) ); - $this->assertEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $fresh_post_id ) ); - } - - $term_ids = wp_get_post_terms( $stale_post_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, [ 'fields' => 'ids' ] ); - $this->assertCount( 3, $term_ids ); - - $expected_count = $add_fresh ? 2 : 1; - foreach ( $term_ids as $term_id ) { - $this->assertCount( - $expected_count, - get_objects_in_term( $term_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ) - ); - } - - // Update the term group for the first term. - wp_update_term( - $term_ids[0], - AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, - compact( 'term_group' ) - ); - - if ( $add_fresh ) { - $this->assertFalse( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $fresh_post_id ) ) ); - $this->assertTrue( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $stale_post_id ) ) ); - } else { - $this->assertFalse( AMP_Validated_URL_Post_Type::is_post_safe_to_garbage_collect( get_post( $stale_post_id ) ) ); - } - - // Since this only garbage-collects posts that are older then 1 week, the new one will remain. - AMP_Validated_URL_Post_Type::garbage_collect_validated_urls(); - - if ( $add_fresh ) { - $this->assertSame( 'publish', get_post_status( $fresh_post_id ) ); - $this->assertFalse( get_post_status( $stale_post_id ) ); - } else { - $this->assertSame( 'publish', get_post_status( $stale_post_id ) ); - } - - $this->assertSame( 'publish', get_post_status( $vanilla_post_id ) ); - } - - /** - * Test get_validated_environment(). - * - * @covers \AMP_Validated_URL_Post_Type::get_validated_environment() - */ - public function test_get_validated_environment() { - switch_theme( 'twentysixteen' ); - update_option( 'active_plugins', [ 'foo/foo.php', 'bar.php' ] ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - $old_env = AMP_Validated_URL_Post_Type::get_validated_environment(); - $this->assertArrayHasKey( 'theme', $old_env ); - $this->assertArrayHasKey( 'plugins', $old_env ); - $this->assertEquals( [ 'twentysixteen' => wp_get_theme( 'twentysixteen' )->get( 'Version' ) ], $old_env['theme'] ); - $this->assertEquals( - [ - Option::THEME_SUPPORT => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG, - Option::ALL_TEMPLATES_SUPPORTED => true, - Option::READER_THEME => ReaderThemes::DEFAULT_READER_THEME, - Option::SUPPORTED_POST_TYPES => [ 'post', 'page' ], - Option::SUPPORTED_TEMPLATES => [ 'is_singular' ], - ], - $old_env['options'] - ); - - switch_theme( 'twentyseventeen' ); - update_option( 'active_plugins', [ 'foo/foo.php', 'baz.php' ] ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::ALL_TEMPLATES_SUPPORTED, false ); - $new_env = AMP_Validated_URL_Post_Type::get_validated_environment(); - $this->assertNotEquals( $old_env, $new_env ); - $this->assertEquals( [ 'twentyseventeen' => wp_get_theme( 'twentyseventeen' )->get( 'Version' ) ], $new_env['theme'] ); - $this->assertEquals( - [ - Option::THEME_SUPPORT => AMP_Theme_Support::STANDARD_MODE_SLUG, - Option::ALL_TEMPLATES_SUPPORTED => false, - Option::READER_THEME => ReaderThemes::DEFAULT_READER_THEME, - Option::SUPPORTED_POST_TYPES => [ 'post', 'page' ], - Option::SUPPORTED_TEMPLATES => [ 'is_singular' ], - ], - $new_env['options'] - ); - - $reader_theme = wp_get_theme( 'twentysixteen' ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::READER_MODE_SLUG ); - AMP_Options_Manager::update_option( Option::READER_THEME, $reader_theme->get_stylesheet() ); - $reader_env = AMP_Validated_URL_Post_Type::get_validated_environment(); - $this->assertEquals( [ $reader_theme->get_stylesheet() => $reader_theme->get( 'Version' ) ], $reader_env['theme'] ); - $this->assertEquals( - [ - Option::THEME_SUPPORT => AMP_Theme_Support::READER_MODE_SLUG, - Option::ALL_TEMPLATES_SUPPORTED => false, - Option::READER_THEME => $reader_theme->get_stylesheet(), - Option::SUPPORTED_POST_TYPES => [ 'post', 'page' ], - Option::SUPPORTED_TEMPLATES => [ 'is_singular' ], - ], - $reader_env['options'] - ); - } - - /** - * Test get_post_staleness method. - * - * @covers AMP_Validated_URL_Post_Type::get_post_staleness() - * @covers AMP_Validated_URL_Post_Type::get_validated_environment() - */ - public function test_get_post_staleness() { - $error = [ 'code' => 'foo' ]; - switch_theme( 'twentysixteen' ); - update_option( 'active_plugins', [ 'foo/foo.php', 'bar.php' ] ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - - $plugins = [ - 'foo/foo.php' => [ - 'Name' => 'Foo', - 'Version' => '0.1', - ], - 'bar.php' => [ - 'Name' => 'Bar', - 'Version' => '0.1', - ], - 'baz.php' => [ - 'Name' => 'Baz', - 'Version' => '0.1', - ], - ]; - wp_cache_set( 'plugins', [ '' => $plugins ], 'plugins' ); - - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( [ $error ], home_url( '/' ) ); - $this->assertIsInt( $invalid_url_post_id ); - $this->assertEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $invalid_url_post_id ) ); - - // Test deactivating plugin and activating another. - update_option( 'active_plugins', [ 'foo/foo.php', 'baz.php' ] ); - $staleness = AMP_Validated_URL_Post_Type::get_post_staleness( $invalid_url_post_id ); - $this->assertNotEmpty( $staleness ); - $this->assertArrayHasKey( 'plugins', $staleness ); - $this->assertArrayNotHasKey( 'theme', $staleness ); - $this->assertEqualSets( [ 'baz.php' ], $staleness['plugins']['new'] ); - $this->assertEqualSets( [ 'bar.php' ], $staleness['plugins']['old'] ); - $this->assertArrayNotHasKey( 'options', $staleness ); - - // Test theme switch. - switch_theme( 'twentyseventeen' ); - $next_staleness = AMP_Validated_URL_Post_Type::get_post_staleness( $invalid_url_post_id ); - $this->assertArrayHasKey( 'theme', $next_staleness ); - $this->assertEquals( - [ - 'old' => [ 'twentysixteen' ], - 'new' => [ 'twentyseventeen' ], - ], - $next_staleness['theme'] - ); - $this->assertSame( $next_staleness['plugins'], $staleness['plugins'] ); - $this->assertArrayNotHasKey( 'options', $staleness ); - - // Test updating plugin version, as well as the template mode. - $plugins['foo/foo.php']['Version'] = '0.2'; - wp_cache_set( 'plugins', [ '' => $plugins ], 'plugins' ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - $last_staleness = AMP_Validated_URL_Post_Type::get_post_staleness( $invalid_url_post_id ); - $this->assertEqualSets( [ 'foo', 'baz.php' ], $last_staleness['plugins']['new'] ); - $this->assertEqualSets( [ 'foo', 'bar.php' ], $last_staleness['plugins']['old'] ); - $this->assertArrayHasKey( 'options', $last_staleness ); - $this->assertEquals( [ Option::THEME_SUPPORT => AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ], $last_staleness['options'] ); - - // Re-storing results updates freshness. - AMP_Validated_URL_Post_Type::store_validation_errors( [ $error ], home_url( '/' ), $invalid_url_post_id ); - $this->assertEmpty( AMP_Validated_URL_Post_Type::get_post_staleness( $invalid_url_post_id ) ); - } - - /** - * Test for add_post_columns() - * - * @covers AMP_Validated_URL_Post_Type::add_post_columns() - */ - public function test_add_post_columns() { - $initial_columns = [ - 'cb' => '', - ]; - $this->assertEquals( - array_keys( - array_merge( - $initial_columns, - [ - AMP_Validation_Error_Taxonomy::ERROR_STATUS => 'Status', - AMP_Validation_Error_Taxonomy::FOUND_ELEMENTS_AND_ATTRIBUTES => 'Invalid', - AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT => 'Sources', - 'css_usage' => 'CSS Usage', - ] - ) - ), - array_keys( AMP_Validated_URL_Post_Type::add_post_columns( $initial_columns ) ) - ); - } - - /** - * Test for add_single_post_columns() - * - * @covers AMP_Validated_URL_Post_Type::add_single_post_columns() - */ - public function test_add_single_post_columns() { - $this->assertEquals( - [ - 'cb' => '', - 'error_code' => 'Error', - 'status' => 'Markup Status', - 'details' => 'Context', - 'sources_with_invalid_output' => 'Sources', - 'error_type' => 'Type', - 'reviewed' => 'Reviewed', - ], - AMP_Validated_URL_Post_Type::add_single_post_columns() - ); - } - - /** - * Gets the test data for test_output_custom_column(). - * - * @return array $columns - */ - public function get_custom_columns() { - $source = [ - 'type' => 'plugin', - 'name' => 'AMP', - ]; - $errors = [ - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG, - 'node_name' => 'script', - 'sources' => [ $source ], - ], - [ - 'code' => AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_ATTR, - 'node_name' => 'onclick', - 'sources' => [ $source ], - ], - ]; - - return [ - AMP_Tag_And_Attribute_Sanitizer::DISALLOWED_TAG => [ - AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT, - 'AMP', - $errors, - ], - 'removed_attributes' => [ - AMP_Validation_Error_Taxonomy::FOUND_ELEMENTS_AND_ATTRIBUTES, - 'onclick', - $errors, - ], - 'sources_invalid_input' => [ - AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT, - 'AMP', - $errors, - ], - ]; - } - - /** - * Test for output_custom_column() - * - * @dataProvider get_custom_columns - * @covers AMP_Validated_URL_Post_Type::output_custom_column() - * - * @param string $column_name The name of the column. - * @param string $expected_value The value that is expected to be present in the column markup. - * @param array $errors Errors. - */ - public function test_output_custom_column( $column_name, $expected_value, $errors ) { - AMP_Validation_Manager::init(); - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( $errors, home_url( '/' ) ); - - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'output_custom_column' ], [ $column_name, $invalid_url_post_id ] ); - $this->assertStringContainsString( $expected_value, $output ); - } - - /** - * Test for render_sources_column() - * - * @covers AMP_Validated_URL_Post_Type::render_sources_column() - */ - public function test_render_sources_column() { - $theme_name = 'foo-theme'; - $post_id = 9876; - $error_summary = [ - 'removed_attributes' => [ - 'webkitallowfullscreen' => 1, - ], - 'removed_elements' => [], - 'sources_with_invalid_output' => [ - 'embed' => true, - 'hook' => 'the_content', - 'theme' => [ $theme_name ], - ], - ]; - - // If there is an embed and a theme source, this should only output the embed icon. - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertEquals( 'Embed', $sources_column ); - - // If there is no embed source, but there is a theme, this should output the theme icon. - unset( $error_summary['sources_with_invalid_output']['embed'] ); - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $expected_theme_icon = '' . $theme_name . ''; - $this->assertEquals( $expected_theme_icon, $sources_column ); - - // If there is a plugin and theme source, this should output icons for both of them. - $plugin_name = 'baz-plugin'; - $error_summary['sources_with_invalid_output']['plugin'] = [ $plugin_name ]; - $expected_plugin_icon = '' . $plugin_name . ''; - unset( $error_summary['sources_with_invalid_output']['embed'] ); - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertEquals( $expected_plugin_icon . $expected_theme_icon, $sources_column ); - - // If there is a 'core' source, it should appear in the column output. - $error_summary['sources_with_invalid_output']['core'] = []; - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertStringContainsString( 'Other (0)', $sources_column ); - - // Even if there is a hook in the sources, it should not appear in the column if there is any other source. - $hook_name = 'wp_header'; - $error_summary['sources_with_invalid_output']['hook'] = [ $hook_name ]; - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertStringNotContainsString( $hook_name, $sources_column ); - - // If a hook is the only source, it should appear in the column. - $error_summary['sources_with_invalid_output'] = [ 'hook' => $hook_name ]; - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertEquals( 'Hook: ' . $hook_name . '', $sources_column ); - - // Content gets a translated name. - $error_summary['sources_with_invalid_output'] = [ 'hook' => 'the_content' ]; - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertEquals( 'Content', $sources_column ); - - // Blocks are listed separately, overriding Content. - $error_summary['sources_with_invalid_output'] = [ - 'hook' => 'the_content', - 'blocks' => [ 'core/html' ], - ]; - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertEquals( 'Custom HTML', $sources_column ); - - // If there's no source in 'sources_with_invalid_output', this should output the theme name. - update_post_meta( $post_id, '_amp_validated_environment', [ 'theme' => $theme_name ] ); - $error_summary['sources_with_invalid_output'] = []; - $sources_column = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_sources_column' ], [ $error_summary['sources_with_invalid_output'], $post_id ] ); - $this->assertEquals( '
        ' . $theme_name . ' (?)
        ', $sources_column ); - } - - /** - * Test for filter_bulk_actions() - * - * @covers \AMP_Validated_URL_Post_Type::filter_bulk_actions() - */ - public function test_filter_bulk_actions() { - $initial_action = [ - 'edit' => 'Edit', - 'trash' => 'Trash', - 'delete' => 'Delete', - ]; - $actions = AMP_Validated_URL_Post_Type::filter_bulk_actions( $initial_action ); - $this->assertArrayNotHasKey( 'edit', $actions ); - $this->assertEquals( 'Recheck', $actions[ AMP_Validated_URL_Post_Type::BULK_VALIDATE_ACTION ] ); - $this->assertArrayNotHasKey( 'trash', $actions ); - $this->assertEquals( 'Forget', $actions['delete'] ); - } - - /** - * Test for handle_bulk_action() - * - * @covers \AMP_Validated_URL_Post_Type::handle_bulk_action() - */ - public function test_handle_bulk_action() { - $this->accept_sanitization_by_default( false ); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - AMP_Validation_Manager::init(); - - $invalid_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - ], - home_url( '/' ) - ); - - $initial_redirect = admin_url( 'plugins.php' ); - $items = [ $invalid_post_id ]; - $urls_tested = (string) count( $items ); - - $_GET[ AMP_Validated_URL_Post_Type::URLS_TESTED ] = $urls_tested; - - // The action isn't correct, so the callback should return the URL unchanged. - $this->assertEquals( $initial_redirect, AMP_Validated_URL_Post_Type::handle_bulk_action( $initial_redirect, 'trash', $items ) ); - - $filter = function() { - return [ - 'body' => wp_json_encode( - [ - 'results' => array_map( - static function( $error ) { - return array_merge( - compact( 'error' ), - [ 'sanitized' => false ] - ); - }, - $this->get_mock_errors() - ), - ] - ), - ]; - }; - add_filter( 'pre_http_request', $filter, 10, 3 ); - $this->assertEquals( - add_query_arg( - [ - AMP_Validated_URL_Post_Type::URLS_TESTED => $urls_tested, - AMP_Validated_URL_Post_Type::REMAINING_ERRORS => count( $items ), - ], - $initial_redirect - ), - AMP_Validated_URL_Post_Type::handle_bulk_action( $initial_redirect, AMP_Validated_URL_Post_Type::BULK_VALIDATE_ACTION, $items ) - ); - remove_filter( 'pre_http_request', $filter, 10 ); - - // Test error scenario. - add_filter( - 'pre_http_request', - static function() { - return [ - 'body' => '', - ]; - } - ); - $this->assertStringContainsString( - 'amp_validate_error=', - AMP_Validated_URL_Post_Type::handle_bulk_action( $initial_redirect, AMP_Validated_URL_Post_Type::BULK_VALIDATE_ACTION, $items ) - ); - } - - /** - * Test for print_admin_notice() - * - * @covers \AMP_Validated_URL_Post_Type::print_admin_notice() - * @covers \AMP_Validation_Manager::serialize_validation_error_messages() - * @covers \AMP_Validation_Manager::unserialize_validation_error_messages() - */ - public function test_print_admin_notice() { - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::STANDARD_MODE_SLUG ); - AMP_Validation_Manager::init(); - - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertEmpty( $output ); - - $_GET['post_type'] = 'post'; - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertEmpty( $output ); - - set_current_screen( 'edit.php' ); - get_current_screen()->post_type = AMP_Validated_URL_Post_Type::POST_TYPE_SLUG; - - $_GET[ AMP_Validated_URL_Post_Type::REMAINING_ERRORS ] = '1'; - $_GET[ AMP_Validated_URL_Post_Type::URLS_TESTED ] = '1'; - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertStringContainsString( 'The rechecked URL still has remaining invalid markup kept.', $output ); - - $_GET[ AMP_Validated_URL_Post_Type::URLS_TESTED ] = '2'; - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertStringContainsString( 'The rechecked URLs still have remaining invalid markup kept.', $output ); - - $_GET[ AMP_Validated_URL_Post_Type::REMAINING_ERRORS ] = '0'; - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertStringContainsString( 'The rechecked URLs are free of non-removed invalid markup.', $output ); - - $_GET[ AMP_Validated_URL_Post_Type::URLS_TESTED ] = '1'; - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertStringContainsString( 'The rechecked URL is free of non-removed invalid markup.', $output ); - - $error_message = 'Something bad happened!'; - $_GET['amp_validate_error'] = AMP_Validation_Manager::serialize_validation_error_messages( [ $error_message ] ); - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_admin_notice' ] ); - $this->assertStringContainsString( $error_message, $output ); - - unset( $GLOBALS['current_screen'] ); - } - - /** - * Test for handle_validate_request() - * - * @covers \AMP_Validated_URL_Post_Type::handle_validate_request() - */ - public function test_handle_validate_request() { - $this->accept_sanitization_by_default( false ); - AMP_Options_Manager::update_option( Option::THEME_SUPPORT, AMP_Theme_Support::TRANSITIONAL_MODE_SLUG ); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - AMP_Validation_Manager::init(); - - $post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - ], - home_url( '/' ) - ); - - $_REQUEST['_wpnonce'] = wp_create_nonce( AMP_Validated_URL_Post_Type::NONCE_ACTION ); - - $exception = null; - add_filter( - 'wp_redirect', - static function( $url, $status ) { - throw new Exception( $url, $status ); - }, - 10, - 2 - ); - - $filter = function() { - return [ - 'body' => wp_json_encode( - [ - 'results' => array_map( - static function( $error ) { - return array_merge( - compact( 'error' ), - [ 'sanitized' => false ] - ); - }, - $this->get_mock_errors() - ), - ] - ), - ]; - }; - add_filter( 'pre_http_request', $filter, 10, 3 ); - - $handle_validate_request = static function() { - try { - AMP_Validated_URL_Post_Type::handle_validate_request(); - } catch ( Exception $exception ) { - return $exception; - } - return null; - }; - - // Test validating with missing args. - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringContainsString( - '/edit.php?post_type=amp_validated_url&_validate_error=', - $exception->getMessage() - ); - unset( $_GET['post'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Test validating for a non-valid post. - $_GET['post'] = 1234567890; - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringContainsString( - '/edit.php?post_type=amp_validated_url&_validate_error=', - $exception->getMessage() - ); - unset( $_GET['post'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Test validating for a non-valid post type. - $_GET['post'] = self::factory()->post->create(); - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringContainsString( - '/edit.php?post_type=amp_validated_url&_validate_error=', - $exception->getMessage() - ); - unset( $_GET['post'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Verify that redirect is happening for a successful case. - $_GET['post'] = $post_id; - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringContainsString( - sprintf( 'post.php?post=%s&action=edit&_urls_tested=', $post_id ), - $exception->getMessage() - ); - unset( $_GET['post'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Test validating by URL. - $_GET['url'] = home_url( '/' ); - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringEndsWith( - sprintf( 'post.php?post=%s&action=edit&_urls_tested=1&_remaining_errors=2', $post_id ), - $exception->getMessage() - ); - - // Test validating by URL which doesn't have a post already. - $_GET['url'] = home_url( '/new-URL/' ); - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringEndsWith( - '&action=edit&_urls_tested=1&_remaining_errors=2', - $exception->getMessage() - ); - - // Test validating a bad URL. - $_GET['url'] = 'http://badurl.example.com/'; - $exception = $handle_validate_request(); - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - $this->assertStringContainsString( - 'wp-admin/edit.php?post_type=amp_validated_url&_validate_error=', - $exception->getMessage() - ); - } - - /** - * Test for recheck_post() - * - * @covers \AMP_Validated_URL_Post_Type::recheck_post() - */ - public function test_recheck_post() { - AMP_Validation_Manager::init(); - - $r = AMP_Validated_URL_Post_Type::recheck_post( 'nope' ); - $this->assertInstanceOf( 'WP_Error', $r ); - $this->assertEquals( 'missing_post', $r->get_error_code() ); - - $r = AMP_Validated_URL_Post_Type::recheck_post( self::factory()->post->create() ); - $this->assertInstanceOf( 'WP_Error', $r ); - $this->assertEquals( 'missing_url', $r->get_error_code() ); - - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - ], - home_url( '/' ) - ); - add_filter( - 'pre_http_request', - static function() { - return [ - 'body' => wp_json_encode( - [ - 'results' => [ - [ - 'sanitized' => false, - 'error' => [ - 'code' => 'bar', - ], - ], - [ - 'sanitized' => false, - 'error' => [ - 'code' => 'baz', - ], - ], - ], - ] - ), - ]; - } - ); - - $r = AMP_Validated_URL_Post_Type::recheck_post( $invalid_url_post_id ); - $this->assertIsArray( $r ); - $this->assertCount( 2, $r ); - $this->assertEquals( 'bar', $r[0]['error']['code'] ); - $this->assertEquals( 'baz', $r[1]['error']['code'] ); - - $errors = AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $invalid_url_post_id ); - $this->assertCount( 2, $errors ); - foreach ( $errors as $i => $error ) { - $this->assertEquals( - $r[ $i ]['error'], - $error['data'] - ); - } - } - - /** - * Test for handle_validation_error_status_update() - * - * @covers \AMP_Validated_URL_Post_Type::handle_validation_error_status_update() - */ - public function test_handle_validation_error_status_update() { - global $post; - AMP_Validation_Manager::init(); - - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - $_REQUEST[ AMP_Validated_URL_Post_Type::UPDATE_POST_TERM_STATUS_ACTION . '_nonce' ] = wp_create_nonce( AMP_Validated_URL_Post_Type::UPDATE_POST_TERM_STATUS_ACTION ); - AMP_Validated_URL_Post_Type::handle_validation_error_status_update(); // No-op since no post. - - $errors = [ - // All statuses for errors should be updated. - [ - 'code' => 'foo', - 'status' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS, - ], - [ - 'code' => 'bar', - 'status' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, - ], - [ - 'code' => 'baz', - 'status' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS, - ], - [ - 'code' => 'buzz', - 'status' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, - ], - // Except for this. - [ - 'code' => 'status_should_not_be_updated', - 'status' => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS, - ], - ]; - - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - $errors, - home_url( '/' ) - ); - - foreach ( $errors as $data ) { - $term_data = AMP_Validation_Error_Taxonomy::prepare_validation_error_taxonomy_term( $data ); - $term = AMP_Validation_Error_Taxonomy::get_term( $term_data['slug'] ); - wp_update_term( $term->term_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, [ 'term_group' => $data['status'] ] ); - } - - add_filter( - 'pre_http_request', - static function() use ( $errors ) { - $results = array_map( - static function ( $error ) { - return [ - 'sanitized' => true, - 'error' => $error, - ]; - }, - $errors - ); - - return [ - 'body' => wp_json_encode( compact( 'results' ) ), - ]; - } - ); - - $post = get_post( $invalid_url_post_id ); - - $validation_errors = AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $invalid_url_post_id ); - - $_POST[ AMP_Validated_URL_Post_Type::VALIDATION_ERRORS_INPUT_KEY ] = [ - // Accepted and acknowledged. - $validation_errors[0]['term']->slug => [ - AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, - AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACKNOWLEDGE_ACTION => 'on', - ], - // Accepted but not acknowledged. - $validation_errors[1]['term']->slug => [ - AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, - ], - // Rejected and acknowledged. - $validation_errors[2]['term']->slug => [ - AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, - AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACKNOWLEDGE_ACTION => 'on', - ], - // Rejected but not acknowledged. - $validation_errors[3]['term']->slug => [ - AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, - ], - // Accepted but not acknowledged. Status should not be changed. - $validation_errors[4]['term']->slug => [ - AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR => AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, - ], - ]; - - add_filter( - 'wp_redirect', - static function( $url, $status ) { - throw new Exception( $url, $status ); - }, - 10, - 2 - ); - $exception = null; - try { - AMP_Validated_URL_Post_Type::handle_validation_error_status_update(); - } catch ( Exception $e ) { - $exception = $e; - } - $this->assertInstanceOf( 'Exception', $exception ); - $this->assertEquals( 302, $exception->getCode() ); - // 4 out of the 5 validation error statuses should be updated, with 2 kept errors. - $this->assertStringEndsWith( 'action=edit&_taxonomy_terms_updated=4&_remaining_errors=2', $exception->getMessage() ); - } - - /** - * Test for enqueue_edit_post_screen_scripts() - * - * @covers \AMP_Validated_URL_Post_Type::enqueue_edit_post_screen_scripts() - */ - public function test_enqueue_edit_post_screen_scripts() { - wp_enqueue_script( 'autosave' ); - set_current_screen( 'index.php' ); - AMP_Validated_URL_Post_Type::enqueue_edit_post_screen_scripts(); - $this->assertTrue( wp_script_is( 'autosave', 'enqueued' ) ); - $this->assertFalse( wp_script_is( 'amp-validated-url-post-edit-screen', 'enqueued' ) ); - - global $pagenow; - $pagenow = 'post.php'; - set_current_screen( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ); - AMP_Validated_URL_Post_Type::enqueue_edit_post_screen_scripts(); - $this->assertFalse( wp_script_is( 'autosave', 'enqueued' ) ); - $this->assertTrue( wp_script_is( 'amp-validated-url-post-edit-screen', 'enqueued' ) ); - $pagenow = null; - } - - /** - * Test render_link_to_error_index_screen. - * - * @covers \AMP_Validated_URL_Post_Type::render_link_to_error_index_screen() - */ - public function test_render_link_to_error_index_screen() { - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - global $current_screen; - set_current_screen( 'index.php' ); - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_link_to_error_index_screen' ] ); - $this->assertEmpty( $output ); - - set_current_screen( 'edit.php' ); - $current_screen->post_type = AMP_Validated_URL_Post_Type::POST_TYPE_SLUG; - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_link_to_error_index_screen' ] ); - $this->assertStringContainsString( 'View Error Index', $output ); - } - - /** - * Test for add_meta_boxes() - * - * @covers \AMP_Validated_URL_Post_Type::add_meta_boxes() - */ - public function test_add_meta_boxes() { - global $wp_meta_boxes; - AMP_Validated_URL_Post_Type::add_admin_hooks(); - add_action( - 'add_meta_boxes', - function () { - add_meta_box( 'bogus', 'Bogus', '__return_empty_string', AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ); - }, - 100 - ); - do_action( 'add_meta_boxes' ); - $side_meta_box = $wp_meta_boxes[ AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ]['side']['default'][ AMP_Validated_URL_Post_Type::STATUS_META_BOX ]; - $this->assertEquals( AMP_Validated_URL_Post_Type::STATUS_META_BOX, $side_meta_box['id'] ); - $this->assertEquals( 'Status', $side_meta_box['title'] ); - $this->assertEquals( - [ - self::TESTED_CLASS, - 'print_status_meta_box', - ], - $side_meta_box['callback'] - ); - $this->assertEquals( - [ '__back_compat_meta_box' => true ], - $side_meta_box['args'] - ); - - foreach ( $wp_meta_boxes[ AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ]['side'] as $context ) { - $this->assertFalse( $context['submitdiv'] ); - } - foreach ( $wp_meta_boxes[ AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ]['advanced'] as $context ) { - $this->assertFalse( $context['bogus'] ); - } - } - - /** - * Test for get_terms_per_page() - * - * @covers \AMP_Validated_URL_Post_Type::get_terms_per_page() - */ - public function test_get_terms_per_page() { - $initial_counts = [ 0, 22, 1000 ]; - - // If 'post.php' === $pagenow, this method should return the same value, no matter what argument is passed to it. - $GLOBALS['pagenow'] = 'post.php'; - foreach ( $initial_counts as $initial_count ) { - $this->assertEquals( - PHP_INT_MAX, - AMP_Validated_URL_Post_Type::get_terms_per_page( $initial_count ) - ); - } - - // If 'post.php' !== $pagenow, this method should return the same value that is passed to it. - $GLOBALS['pagenow'] = 'edit-tags.php'; - foreach ( $initial_counts as $initial_count ) { - $this->assertEquals( - $initial_count, - AMP_Validated_URL_Post_Type::get_terms_per_page( $initial_count ) - ); - } - } - - /** - * Test for add_taxonomy() - * - * @covers \AMP_Validated_URL_Post_Type::add_taxonomy() - */ - public function test_add_taxonomy() { - // The 'pagenow' value is incorrect, so this should not add the taxonomy. - $GLOBALS['pagenow'] = 'edit.php'; - AMP_Validated_URL_Post_Type::add_taxonomy(); - $this->assertFalse( isset( $_REQUEST['taxonomy'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Though the 'pagenow' value is correct, the $_REQUEST['post'] is not set, and this should not add the taxonomy. - $GLOBALS['pagenow'] = 'post.php'; - AMP_Validated_URL_Post_Type::add_taxonomy(); - $this->assertFalse( isset( $_REQUEST['taxonomy'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Though the $_REQUEST['post'] is set, it is for a post of the wrong type. - $wrong_post_type = self::factory()->post->create(); - $_REQUEST['post'] = $wrong_post_type; - AMP_Validated_URL_Post_Type::add_taxonomy(); - $this->assertFalse( isset( $_REQUEST['taxonomy'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - - // Now that the post type is correct, this should add the taxonomy to $_REQUEST. - $correct_post_type = self::factory()->post->create( [ 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ] ); - $_REQUEST['post'] = $correct_post_type; - AMP_Validated_URL_Post_Type::add_taxonomy(); - $this->assertEquals( AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, $_REQUEST['taxonomy'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended - } - - /** - * Test for print_status_meta_box() - * - * @covers \AMP_Validated_URL_Post_Type::print_status_meta_box() - */ - public function test_print_status_meta_box() { - AMP_Validation_Manager::init(); - wp_set_current_user( self::factory()->user->create( [ 'role' => 'administrator' ] ) ); - - $invalid_url_post_id = AMP_Validated_URL_Post_Type::store_validation_errors( - [ - [ 'code' => 'foo' ], - ], - home_url( '/' ) - ); - - $post_storing_error = get_post( $invalid_url_post_id ); - - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'print_status_meta_box' ], [ get_post( $invalid_url_post_id ) ] ); - - $this->assertStringContainsString( date_i18n( 'M j, Y @ H:i', strtotime( $post_storing_error->post_date ) ), $output ); - $this->assertStringContainsString( 'Last checked:', $output ); - $this->assertStringContainsString( 'Forget', $output ); - $this->assertStringContainsString( esc_url( get_delete_post_link( $post_storing_error->ID, '', true ) ), $output ); - $this->assertStringContainsString( 'misc-pub-section', $output ); - } - - /** - * Test for render_single_url_list_table() - * - * @covers \AMP_Validated_URL_Post_Type::render_single_url_list_table() - */ - public function test_render_single_url_list_table() { - AMP_Validation_Error_Taxonomy::register(); - $post_correct_post_type = self::factory()->post->create_and_get( [ 'post_type' => AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ] ); - $post_wrong_post_type = self::factory()->post->create_and_get( [ 'post_type' => 'page' ] ); - $GLOBALS['hook_suffix'] = 'post.php'; - $this->go_to( admin_url( 'post.php' ) ); - set_current_screen( 'post.php' ); - $GLOBALS['current_screen']->taxonomy = AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG; - - // If the post type is wrong, so the conditional should be false, and this should not echo anything. - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_single_url_list_table' ], [ $post_wrong_post_type ] ); - $this->assertEmpty( $output ); - - // Now that the current user has permissions, this should output the correct markup. - $output = get_echo( [ AMP_Validated_URL_Post_Type::class, 'render_single_url_list_table' ], [ $post_correct_post_type ] ); - $this->assertStringContainsString( '
        ', $output ); - $this->assertStringContainsString( '