From 814c99a1c2540cd7a65efbf130c6abadf6eb94e9 Mon Sep 17 00:00:00 2001 From: reiern70 Date: Tue, 31 Mar 2026 14:56:33 -0500 Subject: [PATCH 1/2] [WICKET-7179] add support for jQuery 4.0.0 for wicket 10.x --- testing/wicket-js-tests/Gruntfile.js | 22 +- testing/wicket-js-tests/package-lock.json | 494 +- testing/wicket-js-tests/package.json | 2 +- testing/wicket-js-tests/pom.xml | 12 +- .../testing/jstest/StartJavaScriptTests.java | 13 +- .../util/license/ApacheLicenceHeaderTest.java | 2 - .../basic/SimplePageExpectedResult_13.html | 2 +- .../markup/html/basic/SimplePage_13.html | 2 +- .../wicket/ajax/res/js/wicket-ajax-jquery.js | 38 +- .../JQueryMigrateResourceReference.java | 68 + .../resource/JQueryResourceReference.java | 7 + .../wicket/resource/jquery/jquery-4.0.0.js | 9680 +++++++++++++++++ .../resource/jquery/jquery-4.0.0.min.js | 2 + .../resource/jquery/jquery-migrate-4.0.2.js | 1086 ++ .../jquery/jquery-migrate-4.0.2.min.js | 2 + .../settings/JavaScriptLibrarySettings.java | 2 +- wicket-core/src/test/js/ajax.js | 45 +- wicket-core/src/test/js/all.html | 2 +- wicket-core/src/test/js/amd.html | 43 - wicket-core/src/test/js/amd.js | 54 - wicket-core/src/test/js/amd/require.js | 37 - wicket-core/src/test/js/dom.js | 2 +- wicket-core/src/test/js/form.js | 4 +- .../src/test/js/qunit/jquery.mockjax.js | 67 +- wicket-core/src/test/js/qunit/qunit.css | 14 +- wicket-core/src/test/js/qunit/qunit.js | 7052 ++++++------ .../main/webapp/js-test/tests/ajax/form.js | 4 +- .../html/autocomplete/wicket-autocomplete.js | 2 +- .../ajax/markup/html/modal/trap-focus.js | 10 +- .../markup/html/form/palette/palette.js | 2 +- 30 files changed, 14948 insertions(+), 3824 deletions(-) create mode 100644 wicket-core/src/main/java/org/apache/wicket/resource/JQueryMigrateResourceReference.java create mode 100644 wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-4.0.0.js create mode 100644 wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-4.0.0.min.js create mode 100644 wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-migrate-4.0.2.js create mode 100644 wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-migrate-4.0.2.min.js delete mode 100644 wicket-core/src/test/js/amd.html delete mode 100644 wicket-core/src/test/js/amd.js delete mode 100644 wicket-core/src/test/js/amd/require.js diff --git a/testing/wicket-js-tests/Gruntfile.js b/testing/wicket-js-tests/Gruntfile.js index b92ccc74f93..85eda6ed714 100644 --- a/testing/wicket-js-tests/Gruntfile.js +++ b/testing/wicket-js-tests/Gruntfile.js @@ -43,8 +43,7 @@ module.exports = function(grunt) { "../../wicket-core/src/test/js/dom.js", "../../wicket-core/src/test/js/channels.js", "../../wicket-core/src/test/js/event.js", - "../../wicket-core/src/test/js/timer.js", - "../../wicket-core/src/test/js/amd.js" + "../../wicket-core/src/test/js/timer.js" ], gymTestsJs = [ "../../wicket-examples/src/main/webapp/js-test/tests/ajax/form.js", @@ -107,19 +106,12 @@ module.exports = function(grunt) { all: { options: { urls: [ - 'http://localhost:38887/test/js/all.html?3.7.1' - ] - } - }, - - /** - * Run Asynchronous module definition tests - */ - amd: { - options: { - urls: [ - 'http://localhost:38887/test/js/amd.html?3.7.1' - ] + 'http://localhost:38887/test/js/all.html?4.0.0' + ], + puppeteer: { + headless: true, + args: ['--no-sandbox'] + } } } }, diff --git a/testing/wicket-js-tests/package-lock.json b/testing/wicket-js-tests/package-lock.json index 6542ff0442d..dc5edf4654f 100644 --- a/testing/wicket-js-tests/package-lock.json +++ b/testing/wicket-js-tests/package-lock.json @@ -14,7 +14,7 @@ "grunt-contrib-connect": "5.0.1", "grunt-contrib-jshint": "3.2.0", "grunt-contrib-nodeunit": "5.0.0", - "grunt-contrib-qunit": "9.1.1" + "grunt-contrib-qunit": "10.2.0" } }, "node_modules/@ampproject/remapping": { @@ -610,19 +610,18 @@ } }, "node_modules/@puppeteer/browsers": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.3.0.tgz", - "integrity": "sha512-ioXoq9gPxkss4MYhD+SFaU9p1IHFUX0ILAWFPyjGaBdjLsYAlZw6j1iLA0N/m12uVHLFDfSYNF7EQccjinIMDA==", + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.13.0.tgz", + "integrity": "sha512-46BZJYJjc/WwmKjsvDFykHtXrtomsCIrwYQPOP7VfMJoZY2bsDF9oROBABR3paDjDcmkUye1Pb1BqdcdiipaWA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "debug": "^4.3.5", + "debug": "^4.4.3", "extract-zip": "^2.0.1", "progress": "^2.0.3", - "proxy-agent": "^6.4.0", - "semver": "^7.6.3", - "tar-fs": "^3.0.6", - "unbzip2-stream": "^1.4.3", + "proxy-agent": "^6.5.0", + "semver": "^7.7.4", + "tar-fs": "^3.1.1", "yargs": "^17.7.2" }, "bin": { @@ -633,9 +632,9 @@ } }, "node_modules/@puppeteer/browsers/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -658,9 +657,9 @@ "license": "MIT" }, "node_modules/@puppeteer/browsers/node_modules/semver": { - "version": "7.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", - "integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", "dev": true, "license": "ISC", "bin": { @@ -678,14 +677,14 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "22.13.17", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.17.tgz", - "integrity": "sha512-nAJuQXoyPj04uLgu+obZcSmsfOenUg6DxPKogeUy6yNCFwWaj5sBF8/G/pNo8EtBJjAfSVgfIlugR/BCOleO+g==", + "version": "25.6.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz", + "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "undici-types": "~6.20.0" + "undici-types": "~7.19.0" } }, "node_modules/@types/yauzl": { @@ -719,9 +718,9 @@ } }, "node_modules/agent-base": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", - "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", "dev": true, "license": "MIT", "engines": { @@ -852,11 +851,19 @@ } }, "node_modules/b4a": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.6.7.tgz", - "integrity": "sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.0.tgz", + "integrity": "sha512-qRuSmNSkGQaHwNbM7J78Wwy+ghLEYF1zNrSeMxj4Kgw6y33O3mXcQ6Ie9fRvfU/YnxWkOchPXbaLb73TkIsfdg==", "dev": true, - "license": "Apache-2.0" + "license": "Apache-2.0", + "peerDependencies": { + "react-native-b4a": "*" + }, + "peerDependenciesMeta": { + "react-native-b4a": { + "optional": true + } + } }, "node_modules/balanced-match": { "version": "1.0.2", @@ -865,24 +872,32 @@ "dev": true }, "node_modules/bare-events": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz", - "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==", + "version": "2.8.2", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.8.2.tgz", + "integrity": "sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==", "dev": true, "license": "Apache-2.0", - "optional": true + "peerDependencies": { + "bare-abort-controller": "*" + }, + "peerDependenciesMeta": { + "bare-abort-controller": { + "optional": true + } + } }, "node_modules/bare-fs": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.0.2.tgz", - "integrity": "sha512-S5mmkMesiduMqnz51Bfh0Et9EX0aTCJxhsI4bvzFFLs8Z1AV8RDHadfY5CyLwdoLHgXbNBEN1gQcbEtGwuvixw==", + "version": "4.7.1", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.7.1.tgz", + "integrity": "sha512-WDRsyVN52eAx/lBamKD6uyw8H4228h/x0sGGGegOamM2cd7Pag88GfMQalobXI+HaEUxpCkbKQUDOQqt9wawRw==", "dev": true, "license": "Apache-2.0", - "optional": true, "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", - "bare-stream": "^2.6.4" + "bare-stream": "^2.6.4", + "bare-url": "^2.2.2", + "fast-fifo": "^1.3.2" }, "engines": { "bare": ">=1.16.0" @@ -897,12 +912,11 @@ } }, "node_modules/bare-os": { - "version": "3.6.1", - "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz", - "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==", + "version": "3.8.7", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.8.7.tgz", + "integrity": "sha512-G4Gr1UsGeEy2qtDTZwL7JFLo2wapUarz7iTMcYcMFdS89AIQuBoyjgXZz0Utv7uHs3xA9LckhVbeBi8lEQrC+w==", "dev": true, "license": "Apache-2.0", - "optional": true, "engines": { "bare": ">=1.14.0" } @@ -913,26 +927,29 @@ "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==", "dev": true, "license": "Apache-2.0", - "optional": true, "dependencies": { "bare-os": "^3.0.1" } }, "node_modules/bare-stream": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz", - "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==", + "version": "2.13.0", + "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.0.tgz", + "integrity": "sha512-3zAJRZMDFGjdn+RVnNpF9kuELw+0Fl3lpndM4NcEOhb9zwtSo/deETfuIwMSE5BXanA0FrN1qVjffGwAg2Y7EA==", "dev": true, "license": "Apache-2.0", - "optional": true, "dependencies": { - "streamx": "^2.21.0" + "streamx": "^2.25.0", + "teex": "^1.0.1" }, "peerDependencies": { + "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "peerDependenciesMeta": { + "bare-abort-controller": { + "optional": true + }, "bare-buffer": { "optional": true }, @@ -941,26 +958,15 @@ } } }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "node_modules/bare-url": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.4.0.tgz", + "integrity": "sha512-NSTU5WN+fy/L0DDenfE8SXQna4voXuW0FHM7wH8i3/q9khUSchfPbPezO4zSFMnDGIf9YE+mt/RWhZgNRKRIXA==", "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" + "license": "Apache-2.0", + "dependencies": { + "bare-path": "^3.0.0" + } }, "node_modules/basic-auth": { "version": "2.0.1", @@ -975,9 +981,9 @@ } }, "node_modules/basic-ftp": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", - "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.0.tgz", + "integrity": "sha512-5K9eNNn7ywHPsYnFwjKgYH8Hf8B5emh7JKcPaVjjrMJFQQwGpwowEnZNEtHs7DfR7hCZsmaK3VA4HUK0YarT+w==", "dev": true, "license": "MIT", "engines": { @@ -1062,31 +1068,6 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, "node_modules/buffer-crc32": { "version": "0.2.13", "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", @@ -1123,6 +1104,7 @@ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -1200,15 +1182,14 @@ } }, "node_modules/chromium-bidi": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.6.3.tgz", - "integrity": "sha512-qXlsCmpCZJAnoTYI83Iu6EdYQpMYdVkCfq08KDh2pmlVqK5t5IA9mGs4/LwCwp4fqisSOMXZxP3HIh8w8aRn0A==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-14.0.0.tgz", + "integrity": "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "mitt": "3.0.1", - "urlpattern-polyfill": "10.0.0", - "zod": "3.23.8" + "mitt": "^3.0.1", + "zod": "^3.24.1" }, "peerDependencies": { "devtools-protocol": "*" @@ -1341,10 +1322,11 @@ "dev": true }, "node_modules/cosmiconfig": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", - "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.1.tgz", + "integrity": "sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==", "dev": true, + "license": "MIT", "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", @@ -1370,7 +1352,8 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true + "dev": true, + "license": "Python-2.0" }, "node_modules/cosmiconfig/node_modules/js-yaml": { "version": "4.1.1", @@ -1510,9 +1493,9 @@ } }, "node_modules/devtools-protocol": { - "version": "0.0.1312386", - "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz", - "integrity": "sha512-DPnhUXvmvKT2dFA/j7B+riVLUt9Q6RKJlcppojL5CoRywJJKLDYnRlw0gTFKfgDPHP5E04UoB71SxoJlVZy8FA==", + "version": "0.0.1595872", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1595872.tgz", + "integrity": "sha512-kRfgp8vWVjBu/fbYCiVFiOqsCk3CrMKEo3WbgGT2NXK2dG7vawWPBljixajVgGK9II8rDO9G0oD0zLt3I1daRg==", "dev": true, "license": "BSD-3-Clause" }, @@ -1624,9 +1607,9 @@ } }, "node_modules/end-of-stream": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", - "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", "dev": true, "license": "MIT", "dependencies": { @@ -1644,15 +1627,17 @@ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } }, "node_modules/error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", "dev": true, + "license": "MIT", "dependencies": { "is-arrayish": "^0.2.1" } @@ -1763,6 +1748,16 @@ "integrity": "sha512-inRWzRY7nG+aXZxBzEqYKB3HPgwflZRopAjDCHv0whhRx+MTUr1ei0ICZUypdyE0HRm4L2d5VEcIqLD6yl+BFA==", "dev": true }, + "node_modules/events-universal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz", + "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bare-events": "^2.7.0" + } + }, "node_modules/exit": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", @@ -1812,9 +1807,9 @@ } }, "node_modules/extract-zip/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -2137,9 +2132,9 @@ } }, "node_modules/get-uri": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.4.tgz", - "integrity": "sha512-E1b1lFFLvLgak2whF2xDBcOy6NLVGZBqqjJjsIhvopKfWWEi64pLVTWWehV8KlLerZkfNTA95sTe2OdJKm1OzQ==", + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz", + "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==", "dev": true, "license": "MIT", "dependencies": { @@ -2152,9 +2147,9 @@ } }, "node_modules/get-uri/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -2382,13 +2377,14 @@ } }, "node_modules/grunt-contrib-qunit": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/grunt-contrib-qunit/-/grunt-contrib-qunit-9.1.1.tgz", - "integrity": "sha512-bzDpYgw3le3N6FuTvI28A5kkk1D14GC1wrj8kzykflAfjg+IYm9euoG9AwgixIYmBSdq3pqBNQbQAlOI8hW0wg==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/grunt-contrib-qunit/-/grunt-contrib-qunit-10.2.0.tgz", + "integrity": "sha512-pOvHgMgDfwUFWvnd2FIksQ+jfEI7lZ1voabDiE5GtU+3Bi2Zuq70vRCSeiKSIbI2vZpVHK0zXpUKzFT4LbNIKw==", "dev": true, + "license": "MIT", "dependencies": { "eventemitter2": "^6.4.9", - "puppeteer": "^22.0.0" + "puppeteer": "^24.0.0" }, "engines": { "node": ">=18" @@ -2621,9 +2617,9 @@ } }, "node_modules/http-proxy-agent/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -2673,9 +2669,9 @@ } }, "node_modules/https-proxy-agent/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -2709,32 +2705,12 @@ "node": ">=0.10.0" } }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/import-fresh": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", - "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", "dev": true, + "license": "MIT", "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" @@ -2793,26 +2769,15 @@ "dev": true }, "node_modules/ip-address": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", - "integrity": "sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz", + "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", "dev": true, "license": "MIT", - "dependencies": { - "jsbn": "1.1.0", - "sprintf-js": "^1.1.3" - }, "engines": { "node": ">= 12" } }, - "node_modules/ip-address/node_modules/sprintf-js": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", - "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", - "dev": true, - "license": "BSD-3-Clause" - }, "node_modules/is-absolute": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", @@ -2830,7 +2795,8 @@ "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/is-binary-path": { "version": "2.1.0", @@ -3236,13 +3202,6 @@ "js-yaml": "bin/js-yaml.js" } }, - "node_modules/jsbn": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz", - "integrity": "sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==", - "dev": true, - "license": "MIT" - }, "node_modules/jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", @@ -3277,7 +3236,8 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json5": { "version": "2.2.3", @@ -3365,7 +3325,8 @@ "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/locate-path": { "version": "5.0.0", @@ -3566,9 +3527,9 @@ } }, "node_modules/netmask": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", - "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz", + "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==", "dev": true, "license": "MIT", "engines": { @@ -3953,9 +3914,9 @@ } }, "node_modules/pac-proxy-agent/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -4011,6 +3972,7 @@ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", "dev": true, + "license": "MIT", "dependencies": { "callsites": "^3.0.0" }, @@ -4037,6 +3999,7 @@ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", @@ -4225,9 +4188,9 @@ } }, "node_modules/proxy-agent/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -4257,9 +4220,9 @@ "license": "MIT" }, "node_modules/pump": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.2.tgz", - "integrity": "sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", "dev": true, "license": "MIT", "dependencies": { @@ -4277,46 +4240,50 @@ } }, "node_modules/puppeteer": { - "version": "22.15.0", - "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-22.15.0.tgz", - "integrity": "sha512-XjCY1SiSEi1T7iSYuxS82ft85kwDJUS7wj1Z0eGVXKdtr5g4xnVcbjwxhq5xBnpK/E7x1VZZoJDxpjAOasHT4Q==", + "version": "24.41.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.41.0.tgz", + "integrity": "sha512-W6Fk0J3TPjjtwjXOyR/qf+YaL0H/Uq8HIgHcXG4mNM/IgbKMCH/HPyK0Fi2qbTU/QpSl9bCte2yBpGHKejTpIw==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "@puppeteer/browsers": "2.3.0", + "@puppeteer/browsers": "2.13.0", + "chromium-bidi": "14.0.0", "cosmiconfig": "^9.0.0", - "devtools-protocol": "0.0.1312386", - "puppeteer-core": "22.15.0" + "devtools-protocol": "0.0.1595872", + "puppeteer-core": "24.41.0", + "typed-query-selector": "^2.12.1" }, "bin": { - "puppeteer": "lib/esm/puppeteer/node/cli.js" + "puppeteer": "lib/cjs/puppeteer/node/cli.js" }, "engines": { "node": ">=18" } }, "node_modules/puppeteer-core": { - "version": "22.15.0", - "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-22.15.0.tgz", - "integrity": "sha512-cHArnywCiAAVXa3t4GGL2vttNxh7GqXtIYGym99egkNJ3oG//wL9LkvO4WE8W1TJe95t1F1ocu9X4xWaGsOKOA==", + "version": "24.41.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.41.0.tgz", + "integrity": "sha512-rLIUri7E/NQ3APSEYCCozaSJx0u8Tu9wxO6BJwnvXmIgILSK3L0TombaVh3izp1njAGrO6H2ru0hcIrLF+gWLw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@puppeteer/browsers": "2.3.0", - "chromium-bidi": "0.6.3", - "debug": "^4.3.6", - "devtools-protocol": "0.0.1312386", - "ws": "^8.18.0" + "@puppeteer/browsers": "2.13.0", + "chromium-bidi": "14.0.0", + "debug": "^4.4.3", + "devtools-protocol": "0.0.1595872", + "typed-query-selector": "^2.12.1", + "webdriver-bidi-protocol": "0.4.1", + "ws": "^8.19.0" }, "engines": { "node": ">=18" } }, "node_modules/puppeteer-core/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -4463,6 +4430,7 @@ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -4669,13 +4637,13 @@ } }, "node_modules/socks": { - "version": "2.8.4", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.4.tgz", - "integrity": "sha512-D3YaD0aRxR3mEcqnidIs7ReYJFVzWdd6fXJYUM8ixcQcJRGTka/b3saV0KflYhyVJXKhb947GndU35SxYNResQ==", + "version": "2.8.7", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", + "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", "dev": true, "license": "MIT", "dependencies": { - "ip-address": "^9.0.5", + "ip-address": "^10.0.1", "smart-buffer": "^4.2.0" }, "engines": { @@ -4699,9 +4667,9 @@ } }, "node_modules/socks-proxy-agent/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -4787,17 +4755,15 @@ } }, "node_modules/streamx": { - "version": "2.22.0", - "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.22.0.tgz", - "integrity": "sha512-sLh1evHOzBy/iWRiR6d1zRcLao4gGZr3C1kzNz4fopCOKJb6xD9ub8Mpi9Mr1R6id5o43S+d93fI48UC5uM9aw==", + "version": "2.25.0", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.25.0.tgz", + "integrity": "sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg==", "dev": true, "license": "MIT", "dependencies": { + "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" - }, - "optionalDependencies": { - "bare-events": "^2.2.0" } }, "node_modules/string_decoder": { @@ -6919,9 +6885,9 @@ } }, "node_modules/tar-fs": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.1.tgz", - "integrity": "sha512-LZA0oaPOc2fVo82Txf3gw+AkEd38szODlptMYejQUhndHMLQ9M059uXR+AfS7DNo0NpINvSqDsvyaCrBVkptWg==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.2.tgz", + "integrity": "sha512-QGxxTxxyleAdyM3kpFs14ymbYmNFrfY+pHj7Z8FgtbZ7w2//VAgLMac7sT6nRpIHjppXO2AwwEOg0bPFVRcmXw==", "dev": true, "license": "MIT", "dependencies": { @@ -6934,13 +6900,14 @@ } }, "node_modules/tar-stream": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.7.tgz", - "integrity": "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.8.tgz", + "integrity": "sha512-U6QpVRyCGHva435KoNWy9PRoi2IFYCgtEhq9nmrPPpbRacPs9IH4aJ3gbrFC8dPcXvdSZ4XXfXT5Fshbp2MtlQ==", "dev": true, "license": "MIT", "dependencies": { "b4a": "^1.6.4", + "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } @@ -6957,6 +6924,16 @@ "node": ">=10" } }, + "node_modules/teex": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", + "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "streamx": "^2.12.5" + } + }, "node_modules/test-exclude": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", @@ -6972,22 +6949,15 @@ } }, "node_modules/text-decoder": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.3.tgz", - "integrity": "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz", + "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==", "dev": true, "license": "Apache-2.0", "dependencies": { "b4a": "^1.6.4" } }, - "node_modules/through": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", - "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", - "dev": true, - "license": "MIT" - }, "node_modules/to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", @@ -7043,6 +7013,13 @@ "node": ">=8" } }, + "node_modules/typed-query-selector": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.1.tgz", + "integrity": "sha512-uzR+FzI8qrUEIu96oaeBJmd9E7CFEiQ3goA5qCVgc4s5llSubcfGHq9yUstZx/k4s9dXHVKsE35YWoFyvEqEHA==", + "dev": true, + "license": "MIT" + }, "node_modules/typedarray-to-buffer": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", @@ -7052,17 +7029,6 @@ "is-typedarray": "^1.0.0" } }, - "node_modules/unbzip2-stream": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", - "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer": "^5.2.1", - "through": "^2.3.8" - } - }, "node_modules/unc-path-regex": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", @@ -7092,9 +7058,9 @@ "dev": true }, "node_modules/undici-types": { - "version": "6.20.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", - "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", + "version": "7.19.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz", + "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", "dev": true, "license": "MIT", "optional": true @@ -7147,13 +7113,6 @@ "browserslist": ">= 4.21.0" } }, - "node_modules/urlpattern-polyfill": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-10.0.0.tgz", - "integrity": "sha512-H/A06tKD7sS1O1X2SshBVeA5FLycRpjqiBeqGKmBwBDBy28EnRjORxTNe269KSSr5un5qyWi1iL61wLxpd+ZOg==", - "dev": true, - "license": "MIT" - }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", @@ -7187,6 +7146,13 @@ "node": ">= 10.13.0" } }, + "node_modules/webdriver-bidi-protocol": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz", + "integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -7244,9 +7210,9 @@ } }, "node_modules/ws": { - "version": "8.18.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.1.tgz", - "integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==", + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", "dev": true, "license": "MIT", "engines": { @@ -7346,9 +7312,9 @@ } }, "node_modules/zod": { - "version": "3.23.8", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", - "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==", + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "dev": true, "license": "MIT", "funding": { diff --git a/testing/wicket-js-tests/package.json b/testing/wicket-js-tests/package.json index 2bad01b4468..705dca49905 100644 --- a/testing/wicket-js-tests/package.json +++ b/testing/wicket-js-tests/package.json @@ -13,7 +13,7 @@ "grunt-contrib-connect": "5.0.1", "grunt-contrib-jshint": "3.2.0", "grunt-contrib-nodeunit": "5.0.0", - "grunt-contrib-qunit": "9.1.1" + "grunt-contrib-qunit": "10.2.0" }, "scripts": { "test": "grunt --verbose" diff --git a/testing/wicket-js-tests/pom.xml b/testing/wicket-js-tests/pom.xml index d50f0ddb244..1d0d20bcf91 100644 --- a/testing/wicket-js-tests/pom.xml +++ b/testing/wicket-js-tests/pom.xml @@ -1,4 +1,4 @@ - + - + 4.0.0 org.apache.wicket @@ -101,8 +105,8 @@ generate-resources - 9.6.1 - v18.15.0 + 11.12.1 + v24.15.0 diff --git a/testing/wicket-js-tests/src/test/java/org/apache/wicket/testing/jstest/StartJavaScriptTests.java b/testing/wicket-js-tests/src/test/java/org/apache/wicket/testing/jstest/StartJavaScriptTests.java index 3979abeba0d..9088e44e9cd 100644 --- a/testing/wicket-js-tests/src/test/java/org/apache/wicket/testing/jstest/StartJavaScriptTests.java +++ b/testing/wicket-js-tests/src/test/java/org/apache/wicket/testing/jstest/StartJavaScriptTests.java @@ -38,7 +38,7 @@ * -Dcom.sun.management.jmxremote to startup JMX (and e.g. connect with jconsole). * * - * @see JavaScript tests + * @see JavaScript tests */ public class StartJavaScriptTests { @@ -126,16 +126,9 @@ public static void main(String[] args) } } - private static void browse() + private static void browse() throws Exception { - try - { - Desktop.getDesktop().browse(new URI("http://localhost:8080/ajax-tests/test/js/all.html?3.6.4")); - } - catch (Exception e) - { - System.out.println("can not open browser " + e); - } + Desktop.getDesktop().browse(new URI("http://localhost:8080/ajax-tests/test/js/all.html?3.7.1")); } /** diff --git a/wicket-core-tests/src/test/java/org/apache/wicket/core/util/license/ApacheLicenceHeaderTest.java b/wicket-core-tests/src/test/java/org/apache/wicket/core/util/license/ApacheLicenceHeaderTest.java index 5426729976f..ed9e9def94a 100644 --- a/wicket-core-tests/src/test/java/org/apache/wicket/core/util/license/ApacheLicenceHeaderTest.java +++ b/wicket-core-tests/src/test/java/org/apache/wicket/core/util/license/ApacheLicenceHeaderTest.java @@ -44,7 +44,6 @@ class ApacheLicenceHeaderTest extends ApacheLicenseHeaderTestCase // the licence header breaks the tests in IE htmlIgnore.add("src/test/js/all.html"); - htmlIgnore.add("src/test/js/amd.html"); /* * See NOTICE.txt @@ -107,7 +106,6 @@ class ApacheLicenceHeaderTest extends ApacheLicenseHeaderTestCase javaScriptIgnore.add("src/test/js/qunit/qunit.js"); javaScriptIgnore.add("src/test/js/qunit/jquery.mockjax.js"); javaScriptIgnore.add("src/test/js/qunit/blanket.min.js"); - javaScriptIgnore.add("src/test/js/amd/require.js"); javaScriptIgnore.add("src/test/js/data/ajax/nonWicketResponse.json"); // no way to add licence in JSON } diff --git a/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePageExpectedResult_13.html b/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePageExpectedResult_13.html index 08f96dbc254..65944097e1c 100644 --- a/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePageExpectedResult_13.html +++ b/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePageExpectedResult_13.html @@ -25,4 +25,4 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePage_13.html b/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePage_13.html index 606a3c5dab3..cc72acdf440 100644 --- a/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePage_13.html +++ b/wicket-core-tests/src/test/java/org/apache/wicket/markup/html/basic/SimplePage_13.html @@ -4,4 +4,4 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js index 1f29dbc0c7e..67a31111165 100644 --- a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js +++ b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js @@ -183,6 +183,14 @@ } }; + Wicket.isFunction = function (f) { + return typeof(f) === 'function'; + }; + + Wicket.isWindow = function (obj) { + return typeof(obj) !== 'undefined' && obj !== null && obj === obj.window; + }; + /** * Logging functionality. */ @@ -413,7 +421,7 @@ attrs.async = true; } - if (!jQuery.isNumeric(attrs.rt)) { + if (!Number.isFinite(attrs.rt)) { attrs.rt = 0; } @@ -443,7 +451,7 @@ var target; if (attrs.event) { target = attrs.event.target; - } else if (!jQuery.isWindow(attrs.c)) { + } else if (!Wicket.isWindow(attrs.c)) { target = Wicket.$(attrs.c); } else { target = window; @@ -458,7 +466,7 @@ * @private */ _executeHandlers: function (handlers) { - if (jQuery.isArray(handlers)) { + if (Array.isArray(handlers)) { // cut the handlers argument var args = Array.prototype.slice.call(arguments).slice(1); @@ -469,7 +477,7 @@ for (var i = 0; i < handlers.length; i++) { var handler = handlers[i]; - if (jQuery.isFunction(handler)) { + if (Wicket.isFunction(handler)) { handler.apply(that, args); } else { new Function(handler).apply(that, args); @@ -492,7 +500,7 @@ var result = [], value, name; - if (jQuery.isArray(parameters)) { + if (Array.isArray(parameters)) { result = parameters; } else if (jQuery.isPlainObject(parameters)) { @@ -529,7 +537,7 @@ for (var i = 0; i < deps.length; i++) { var dep = deps[i], extraParam; - if (jQuery.isFunction(dep)) { + if (Wicket.isFunction(dep)) { extraParam = dep(attrs); } else { extraParam = new Function('attrs', dep)(attrs); @@ -619,7 +627,7 @@ var preconditions = attrs.pre || []; preconditions = defaultPrecondition.concat(preconditions); - if (jQuery.isArray(preconditions)) { + if (Array.isArray(preconditions)) { var that = this._getTarget(attrs); @@ -627,7 +635,7 @@ var precondition = preconditions[p]; var result; - if (jQuery.isFunction(precondition)) { + if (Wicket.isFunction(precondition)) { result = precondition.call(that, attrs); } else { result = new Function(precondition).call(that, attrs); @@ -652,14 +660,14 @@ var scName = attrs.sc; data = data.concat({name: scName, value: 1}); } - } else if (attrs.c && !jQuery.isWindow(attrs.c)) { + } else if (attrs.c && !Wicket.isWindow(attrs.c)) { // serialize just the form component with id == attrs.c var el = Wicket.$(attrs.c); data = data.concat(Wicket.Form.serializeElement(el, attrs.sr)); } // collect the dynamic extra parameters - if (jQuery.isArray(attrs.dep)) { + if (Array.isArray(attrs.dep)) { var dynamicData = this._calculateDynamicParameters(attrs); if (attrs.m.toLowerCase() === 'post') { data = data.concat(dynamicData); @@ -1148,7 +1156,7 @@ if ($select.length > 0 && $select.prop('disabled') === false) { var name = $select.prop('name'); var values = $select.val(); - if (jQuery.isArray(values)) { + if (Array.isArray(values)) { for (var v = 0; v < values.length; v++) { var value = values[v]; result.push( { name: name, value: value } ); @@ -1458,7 +1466,7 @@ return; } else { // jQuery 1.9+ expects '<' as the very first character in text - var cleanedText = jQuery.trim(text); + var cleanedText = text.trim(); var $newElement = jQuery(cleanedText); jQuery(element).replaceWith($newElement); @@ -1475,7 +1483,7 @@ var topic = we.Topic; // jQuery 1.9+ expects '<' as the very first character in text - var cleanedText = jQuery.trim(text); + var cleanedText = text.trim(); var $newElement = jQuery(cleanedText); jQuery(element).append($newElement); @@ -1665,7 +1673,7 @@ attrs.c = attrs.c || window; attrs.e = attrs.e || [ 'domready' ]; - if (!jQuery.isArray(attrs.e)) { + if (!Array.isArray(attrs.e)) { attrs.e = [ attrs.e ]; } @@ -2194,7 +2202,7 @@ var safeFocus = function() { try { - toFocus.focus(); + toFocus.trigger('focus'); } catch (ignore) { // WICKET-6209 IE fails if toFocus is disabled } diff --git a/wicket-core/src/main/java/org/apache/wicket/resource/JQueryMigrateResourceReference.java b/wicket-core/src/main/java/org/apache/wicket/resource/JQueryMigrateResourceReference.java new file mode 100644 index 00000000000..9215bd78e7b --- /dev/null +++ b/wicket-core/src/main/java/org/apache/wicket/resource/JQueryMigrateResourceReference.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.wicket.resource; + +import java.util.List; +import org.apache.wicket.Application; +import org.apache.wicket.markup.head.HeaderItem; +import org.apache.wicket.markup.head.JavaScriptHeaderItem; +import org.apache.wicket.request.resource.JavaScriptResourceReference; +import org.apache.wicket.request.resource.ResourceReference; + + +/** + * The jQuery migrate library + */ +public class JQueryMigrateResourceReference extends JavaScriptResourceReference +{ + private static final long serialVersionUID = 1L; + + + public static final String VERSION_4 = "jquery/jquery-migrate-4.0.2.js"; + + public static final JQueryMigrateResourceReference INSTANCE_4 = new JQueryMigrateResourceReference(VERSION_4); + + + public static JQueryMigrateResourceReference get() + { + return INSTANCE_4; + } + + protected JQueryMigrateResourceReference(final String version) + { + super(JQueryMigrateResourceReference.class, version); + } + + @Override + public List getDependencies() + { + final ResourceReference backingLibraryReference; + if (Application.exists()) + { + backingLibraryReference = Application.get() + .getJavaScriptLibrarySettings() + .getJQueryReference(); + } + else + { + backingLibraryReference = JQueryResourceReference.getV4(); + } + List dependencies = super.getDependencies(); + dependencies.add(JavaScriptHeaderItem.forReference(backingLibraryReference)); + return dependencies; + } +} diff --git a/wicket-core/src/main/java/org/apache/wicket/resource/JQueryResourceReference.java b/wicket-core/src/main/java/org/apache/wicket/resource/JQueryResourceReference.java index ba1c0224cb3..75e4ea33eaf 100644 --- a/wicket-core/src/main/java/org/apache/wicket/resource/JQueryResourceReference.java +++ b/wicket-core/src/main/java/org/apache/wicket/resource/JQueryResourceReference.java @@ -36,14 +36,21 @@ public class JQueryResourceReference extends JavaScriptResourceReference * Note: Might not work with old jQuery plugins! */ public static final String VERSION_3 = "jquery/jquery-3.7.1.js"; + public static final String VERSION_4 = "jquery/jquery-4.0.0.js"; public static final JQueryResourceReference INSTANCE_3 = new JQueryResourceReference(VERSION_3); + public static final JQueryResourceReference INSTANCE_4 = new JQueryResourceReference(VERSION_4); public static JQueryResourceReference getV3() { return INSTANCE_3; } + public static JQueryResourceReference getV4() + { + return INSTANCE_4; + } + protected JQueryResourceReference(final String version) { super(JQueryResourceReference.class, version); diff --git a/wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-4.0.0.js b/wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-4.0.0.js new file mode 100644 index 00000000000..097b0883448 --- /dev/null +++ b/wicket-core/src/main/java/org/apache/wicket/resource/jquery/jquery-4.0.0.js @@ -0,0 +1,9680 @@ +/*! + * jQuery JavaScript Library v4.0.0 + * https://jquery.com/ + * + * Copyright OpenJS Foundation and other contributors + * Released under the MIT license + * https://jquery.com/license/ + * + * Date: 2026-01-18T00:20Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + module.exports = factory( global, true ); + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +"use strict"; + +if ( !window.document ) { + throw new Error( "jQuery requires a window with a document" ); +} + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +// Support: IE 11+ +// IE doesn't have Array#flat; provide a fallback. +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + +var push = arr.push; + +var indexOf = arr.indexOf; + +// [[Class]] -> type pairs +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +// All support tests are defined in their respective modules. +var support = {}; + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + return typeof obj === "object" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} + +function isWindow( obj ) { + return obj != null && obj === obj.window; +} + +function isArrayLike( obj ) { + + var length = !!obj && obj.length, + type = toType( obj ); + + if ( typeof obj === "function" || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} + +var document$1 = window.document; + +var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true +}; + +function DOMEval( code, node, doc ) { + doc = doc || document$1; + + var i, + script = doc.createElement( "script" ); + + script.text = code; + for ( i in preservedScriptAttributes ) { + if ( node && node[ i ] ) { + script[ i ] = node[ i ]; + } + } + + if ( doc.head.appendChild( script ).parentNode ) { + script.parentNode.removeChild( script ); + } +} + +var version = "4.0.0", + + rhtmlSuffix = /HTML$/i, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + } +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && typeof target !== "function" ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + + // Retrieve the text value of an array of DOM nodes + text: function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += jQuery.text( node ); + } + } + if ( nodeType === 1 || nodeType === 11 ) { + return elem.textContent; + } + if ( nodeType === 9 ) { + return elem.documentElement.textContent; + } + if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; + }, + + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + isXMLDoc: function( elem ) { + var namespace = elem && elem.namespaceURI, + docElem = elem && ( elem.ownerDocument || elem ).documentElement; + + // Assume HTML when documentElement doesn't yet exist, such as inside + // document fragments. + return !rhtmlSuffix.test( namespace || docElem && docElem.nodeName || "HTML" ); + }, + + // Note: an element does not contain itself + contains: function( a, b ) { + var bup = b && b.parentNode; + + return a === bup || !!( bup && bup.nodeType === 1 && ( + + // Support: IE 9 - 11+ + // IE doesn't have `contains` on SVG. + a.contains ? + a.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), + function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); + } ); + +function nodeName( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); +} + +var pop = arr.pop; + +// https://www.w3.org/TR/css3-selectors/#whitespace +var whitespace = "[\\x20\\t\\r\\n\\f]"; + +var isIE = document$1.documentMode; + +var rbuggyQSA = isIE && new RegExp( + + // Support: IE 9 - 11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + ":enabled|:disabled|" + + + // Support: IE 11+ + // IE 11 doesn't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" + +); + +var rtrimCSS = new RegExp( + "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", + "g" +); + +// https://www.w3.org/TR/css-syntax-3/#ident-token-diagram +var identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+"; + +var rleadingCombinator = new RegExp( "^" + whitespace + "*([>+~]|" + + whitespace + ")" + whitespace + "*" ); + +var rdescend = new RegExp( whitespace + "|>" ); + +var rsibling = /[+~]/; + +var documentElement$1 = document$1.documentElement; + +// Support: IE 9 - 11+ +// IE requires a prefix. +var matches = documentElement$1.matches || documentElement$1.msMatchesSelector; + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + + // Use (key + " ") to avoid collision with native prototype properties + // (see https://github.com/jquery/sizzle/issues/157) + if ( keys.push( key + " " ) > jQuery.expr.cacheLength ) { + + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return ( cache[ key + " " ] = value ); + } + return cache; +} + +/** + * Checks a node for validity as a jQuery selector context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Attribute selectors: https://www.w3.org/TR/selectors/#attribute-selectors +var attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]"; + +var pseudos = ":(" + identifier + ")(?:\\((" + + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + + // 3. anything else (capture 2) + ".*" + + ")\\)|)"; + +var filterMatchExpr = { + ID: new RegExp( "^#(" + identifier + ")" ), + CLASS: new RegExp( "^\\.(" + identifier + ")" ), + TAG: new RegExp( "^(" + identifier + "|[*])" ), + ATTR: new RegExp( "^" + attributes ), + PSEUDO: new RegExp( "^" + pseudos ), + CHILD: new RegExp( + "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ) +}; + +var rpseudo = new RegExp( pseudos ); + +// CSS escapes +// https://www.w3.org/TR/CSS21/syndata.html#escaped-characters + +var runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + if ( nonHex ) { + + // Strip the backslash prefix from a non-hex escape sequence + return nonHex; + } + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + return high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +function unescapeSelector( sel ) { + return sel.replace( runescape, funescape ); +} + +function selectorError( msg ) { + jQuery.error( "Syntax error, unrecognized expression: " + msg ); +} + +var rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ); + +var tokenCache = createCache(); + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = jQuery.expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || ( match = rcomma.exec( soFar ) ) ) { + if ( match ) { + + // Don't consume trailing commas as valid + soFar = soFar.slice( match[ 0 ].length ) || soFar; + } + groups.push( ( tokens = [] ) ); + } + + matched = false; + + // Combinators + if ( ( match = rleadingCombinator.exec( soFar ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + + // Cast descendant combinators to space + type: match[ 0 ].replace( rtrimCSS, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in filterMatchExpr ) { + if ( ( match = jQuery.expr.match[ type ].exec( soFar ) ) && ( !preFilters[ type ] || + ( match = preFilters[ type ]( match ) ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + if ( parseOnly ) { + return soFar.length; + } + + return soFar ? + selectorError( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +var preFilter = { + ATTR: function( match ) { + match[ 1 ] = unescapeSelector( match[ 1 ] ); + + // Move the given value to match[3] whether quoted or unquoted + match[ 3 ] = unescapeSelector( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ); + + if ( match[ 2 ] === "~=" ) { + match[ 3 ] = " " + match[ 3 ] + " "; + } + + return match.slice( 0, 4 ); + }, + + CHILD: function( match ) { + + /* matches from filterMatchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[ 1 ] = match[ 1 ].toLowerCase(); + + if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { + + // nth-* requires argument + if ( !match[ 3 ] ) { + selectorError( match[ 0 ] ); + } + + // numeric x and y parameters for jQuery.expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[ 4 ] = +( match[ 4 ] ? + match[ 5 ] + ( match[ 6 ] || 1 ) : + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) + ); + match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); + + // other types prohibit arguments + } else if ( match[ 3 ] ) { + selectorError( match[ 0 ] ); + } + + return match; + }, + + PSEUDO: function( match ) { + var excess, + unquoted = !match[ 6 ] && match[ 2 ]; + + if ( filterMatchExpr.CHILD.test( match[ 0 ] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[ 3 ] ) { + match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + + // Get excess from tokenize (recursively) + ( excess = tokenize( unquoted, true ) ) && + + // advance to the next closing parenthesis + ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - + unquoted.length ) ) { + + // excess is a negative index + match[ 0 ] = match[ 0 ].slice( 0, excess ); + match[ 2 ] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[ i ].value; + } + return selector; +} + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +function access( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( typeof value !== "function" ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, _key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +} + +// Only count HTML whitespace +// Other whitespace should count in values +// https://infra.spec.whatwg.org/#ascii-whitespace +var rnothtmlwhite = /[^\x20\t\r\n\f]+/g; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ]; + } + + if ( value !== undefined ) { + if ( value === null || + + // For compat with previous handling of boolean attributes, + // remove when `false` passed. For ARIA attributes - + // many of which recognize a `"false"` value - continue to + // set the `"false"` value as jQuery <4 did. + ( value === false && name.toLowerCase().indexOf( "aria-" ) !== 0 ) ) { + + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: {}, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Support: IE <=11+ +// An input loses its value after becoming a radio +if ( isIE ) { + jQuery.attrHooks.type = { + set: function( elem, value ) { + if ( value === "radio" && nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }; +} + +// CSS string/identifier serialization +// https://drafts.csswg.org/cssom/#common-serializing-idioms +var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g; + +function fcssescape( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; +} + +jQuery.escapeSelector = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + +var sort = arr.sort; + +var splice = arr.splice; + +var hasDuplicate; + +// Document order sorting +function sortOrder( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 ) { + + // Choose the first element that is related to the document + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a == document$1 || a.ownerDocument == document$1 && + jQuery.contains( document$1, a ) ) { + return -1; + } + + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b == document$1 || b.ownerDocument == document$1 && + jQuery.contains( document$1, b ) ) { + return 1; + } + + // Maintain original order + return 0; + } + + return compare & 4 ? -1 : 1; +} + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +jQuery.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + hasDuplicate = false; + + sort.call( results, sortOrder ); + + if ( hasDuplicate ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + splice.call( results, duplicates[ j ], 1 ); + } + } + + return results; +}; + +jQuery.fn.uniqueSort = function() { + return this.pushStack( jQuery.uniqueSort( slice.apply( this ) ) ); +}; + +var i, + outermostContext, + + // Local document vars + document, + documentElement, + documentIsHTML, + + // Instance-specific data + dirruns = 0, + done = 0, + classCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + + // Regular expressions + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = jQuery.extend( { + + // For use in libraries implementing .is() + // We use this for POS matching in `select` + needsContext: new RegExp( "^" + whitespace + + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, filterMatchExpr ), + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr$1 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + // Used for iframes; see `setDocument`. + // Support: IE 9 - 11+ + // Removing the function wrapper causes a "Permission Denied" + // error in IE. + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && nodeName( elem, "fieldset" ); + }, + { dir: "parentNode", next: "legend" } + ); + +function find( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr$1.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + push.call( results, elem ); + } + return results; + + // Element context + } else { + if ( newContext && ( elem = newContext.getElementById( m ) ) && + jQuery.contains( context, elem ) ) { + + push.call( results, elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && + testContext( context.parentNode ) || + context; + + // Outside of IE, if we're not changing the context we can + // use :scope instead of an ID. + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( newContext != context || isIE ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = jQuery.escapeSelector( nid ); + } else { + context.setAttribute( "id", ( nid = jQuery.expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === jQuery.expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + + // All others + return select( selector.replace( rtrimCSS, "$1" ), context, results, seed ); +} + +/** + * Mark a function for special use by jQuery selector module + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ jQuery.expando ] = true; + return fn; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + return nodeName( elem, "input" ) && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + return ( nodeName( elem, "input" ) || nodeName( elem, "button" ) ) && + elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11+ + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction( function( argument ) { + argument = +argument; + return markFunction( function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ ( j = matchIndexes[ i ] ) ] ) { + seed[ j ] = !( matches[ j ] = seed[ j ] ); + } + } + } ); + } ); +} + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [node] An element or document object to use to set the document + */ +function setDocument( node ) { + var subWindow, + doc = node ? node.ownerDocument || node : document$1; + + // Return early if doc is invalid or already selected + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 ) { + return; + } + + // Update global variables + document = doc; + documentElement = document.documentElement; + documentIsHTML = !jQuery.isXMLDoc( document ); + + // Support: IE 9 - 11+ + // Accessing iframe documents after unload throws "permission denied" errors (see trac-13936) + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( isIE && document$1 != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + subWindow.addEventListener( "unload", unloadHandler ); + } +} + +find.matches = function( expr, elements ) { + return find( expr, null, null, elements ); +}; + +find.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + return matches.call( elem, expr ); + } catch ( e ) { + nonnativeSelectorCache( expr, true ); + } + } + + return find( expr, document, null, [ elem ] ).length > 0; +}; + +jQuery.expr = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + find: { + ID: function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }, + + TAG: function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else { + return context.querySelectorAll( tag ); + } + }, + + CLASS: function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + } + }, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: preFilter, + + filter: { + ID: function( id ) { + var attrId = unescapeSelector( id ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }, + + TAG: function( nodeNameSelector ) { + var expectedNodeName = unescapeSelector( nodeNameSelector ).toLowerCase(); + return nodeNameSelector === "*" ? + + function() { + return true; + } : + + function( elem ) { + return nodeName( elem, expectedNodeName ); + }; + }, + + CLASS: function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + ( pattern = new RegExp( "(^|" + whitespace + ")" + className + + "(" + whitespace + "|$)" ) ) && + classCache( className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); + } ); + }, + + ATTR: function( name, operator, check ) { + return function( elem ) { + var result = jQuery.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + if ( operator === "=" ) { + return result === check; + } + if ( operator === "!=" ) { + return result !== check; + } + if ( operator === "^=" ) { + return check && result.indexOf( check ) === 0; + } + if ( operator === "*=" ) { + return check && result.indexOf( check ) > -1; + } + if ( operator === "$=" ) { + return check && result.slice( -check.length ) === check; + } + if ( operator === "~=" ) { + return ( " " + result.replace( rwhitespace, " " ) + " " ) + .indexOf( check ) > -1; + } + if ( operator === "|=" ) { + return result === check || result.slice( 0, check.length + 1 ) === check + "-"; + } + + return false; + }; + }, + + CHILD: function( type, what, _argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, _context, xml ) { + var cache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( ( node = node[ dir ] ) ) { + if ( ofType ? + nodeName( node, name ) : + node.nodeType === 1 ) { + + return false; + } + } + + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + outerCache = parent[ jQuery.expando ] || + ( parent[ jQuery.expando ] = {} ); + cache = outerCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( ( node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + outerCache = elem[ jQuery.expando ] || + ( elem[ jQuery.expando ] = {} ); + cache = outerCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // Use the same loop as above to seek `elem` from the start + while ( ( node = ++nodeIndex && node && node[ dir ] || + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + if ( ( ofType ? + nodeName( node, name ) : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ jQuery.expando ] || + ( node[ jQuery.expando ] = {} ); + outerCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + PSEUDO: function( pseudo, argument ) { + + // pseudo-class names are case-insensitive + // https://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var fn = jQuery.expr.pseudos[ pseudo ] || + jQuery.expr.setFilters[ pseudo.toLowerCase() ] || + selectorError( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as jQuery does + if ( fn[ jQuery.expando ] ) { + return fn( argument ); + } + + return fn; + } + }, + + pseudos: { + + // Potentially complex pseudos + not: markFunction( function( selector ) { + + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrimCSS, "$1" ) ); + + return matcher[ jQuery.expando ] ? + markFunction( function( seed, matches, _context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( ( elem = unmatched[ i ] ) ) { + seed[ i ] = !( matches[ i ] = elem ); + } + } + } ) : + function( elem, _context, xml ) { + input[ 0 ] = elem; + matcher( input, null, xml, results ); + + // Don't keep the element + // (see https://github.com/jquery/sizzle/issues/299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + has: markFunction( function( selector ) { + return function( elem ) { + return find( selector, elem ).length > 0; + }; + } ), + + contains: markFunction( function( text ) { + text = unescapeSelector( text ); + return function( elem ) { + return ( elem.textContent || jQuery.text( elem ) ).indexOf( text ) > -1; + }; + } ), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // https://www.w3.org/TR/selectors/#lang-pseudo + lang: markFunction( function( lang ) { + + // lang value must be a valid identifier + if ( !ridentifier.test( lang || "" ) ) { + selectorError( "unsupported lang: " + lang ); + } + lang = unescapeSelector( lang ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( ( elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); + return false; + }; + } ), + + // Miscellaneous + target: function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + root: function( elem ) { + return elem === documentElement; + }, + + focus: function( elem ) { + return elem === document.activeElement && + document.hasFocus() && + !!( elem.type || elem.href || ~elem.tabIndex ); + }, + + // Boolean properties + enabled: createDisabledPseudo( false ), + disabled: createDisabledPseudo( true ), + + checked: function( elem ) { + + // In CSS3, :checked should return both checked and selected elements + // https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + return ( nodeName( elem, "input" ) && !!elem.checked ) || + ( nodeName( elem, "option" ) && !!elem.selected ); + }, + + selected: function( elem ) { + + // Support: IE <=11+ + // Accessing the selectedIndex property + // forces the browser to treat the default option as + // selected when in an optgroup. + if ( isIE && elem.parentNode ) { + // eslint-disable-next-line no-unused-expressions + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + empty: function( elem ) { + + // https://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + parent: function( elem ) { + return !jQuery.expr.pseudos.empty( elem ); + }, + + // Element/input types + header: function( elem ) { + return rheader.test( elem.nodeName ); + }, + + input: function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + button: function( elem ) { + return nodeName( elem, "input" ) && elem.type === "button" || + nodeName( elem, "button" ); + }, + + text: function( elem ) { + return nodeName( elem, "input" ) && elem.type === "text"; + }, + + // Position-in-collection + first: createPositionalPseudo( function() { + return [ 0 ]; + } ), + + last: createPositionalPseudo( function( _matchIndexes, length ) { + return [ length - 1 ]; + } ), + + eq: createPositionalPseudo( function( _matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + } ), + + even: createPositionalPseudo( function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + odd: createPositionalPseudo( function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + lt: createPositionalPseudo( function( matchIndexes, length, argument ) { + var i; + + if ( argument < 0 ) { + i = argument + length; + } else if ( argument > length ) { + i = length; + } else { + i = argument; + } + + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + gt: createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ) + } +}; + +jQuery.expr.pseudos.nth = jQuery.expr.pseudos.eq; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + jQuery.expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + jQuery.expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = jQuery.expr.pseudos; +jQuery.expr.setFilters = new setFilters(); + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ jQuery.expando ] || ( elem[ jQuery.expando ] = {} ); + + if ( skip && nodeName( elem, skip ) ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = outerCache[ key ] ) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return ( newCache[ 2 ] = oldCache[ 2 ] ); + } else { + + // Reuse newcache so results back-propagate to previous elements + outerCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[ i ]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[ 0 ]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + find( selector, contexts[ i ], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( ( elem = unmatched[ i ] ) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ jQuery.expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ jQuery.expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction( function( seed, results, context, xml ) { + var temp, i, elem, matcherOut, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || + multipleContexts( selector || "*", + context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems; + + if ( matcher ) { + + // If we have a postFinder, or filtered seed, or non-seed postFilter + // or preexisting results, + matcherOut = postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results; + + // Find primary matches + matcher( matcherIn, matcherOut, context, xml ); + } else { + matcherOut = matcherIn; + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( ( elem = temp[ i ] ) ) { + matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) ) { + + // Restore matcherIn since elem is not yet a final match + temp.push( ( matcherIn[ i ] = elem ) ); + } + } + postFinder( null, ( matcherOut = [] ), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) && + ( temp = postFinder ? indexOf.call( seed, elem ) : preMap[ i ] ) > -1 ) { + + seed[ temp ] = !( results[ temp ] = elem ); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + } ); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = jQuery.expr.relative[ tokens[ 0 ].type ], + implicitRelative = leadingRelative || jQuery.expr.relative[ " " ], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + var ret = ( !leadingRelative && ( xml || context != outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element + // (see https://github.com/jquery/sizzle/issues/299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( ( matcher = jQuery.expr.relative[ tokens[ i ].type ] ) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = jQuery.expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ jQuery.expando ] ) { + + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( jQuery.expr.relative[ tokens[ j ].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrimCSS, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + + // We must always have either seed elements or outermost context + elems = seed || byElement && jQuery.expr.find.TAG( "*", outermost ), + + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ); + + if ( outermost ) { + + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + for ( ; ( elem = elems[ i ] ) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + + // Support: IE 11+ + // IE sometimes throws a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, xml ) ) { + push.call( results, elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + + // They will have gone through all possible matchers + if ( ( elem = !matcher && elem ) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( ( matcher = setMatchers[ j++ ] ) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !( unmatched[ i ] || setMatched[ i ] ) ) { + setMatched[ i ] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + jQuery.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +function compile( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[ i ] ); + if ( cached[ jQuery.expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +} + +/** + * A low-level selection function that works with jQuery's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with jQuery selector compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( ( selector = compiled.selector || selector ) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + context.nodeType === 9 && documentIsHTML && + jQuery.expr.relative[ tokens[ 1 ].type ] ) { + + context = ( jQuery.expr.find.ID( + unescapeSelector( token.matches[ 0 ] ), + context + ) || [] )[ 0 ]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr.needsContext.test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[ i ]; + + // Abort if we hit a combinator + if ( jQuery.expr.relative[ ( type = token.type ) ] ) { + break; + } + if ( ( find = jQuery.expr.find[ type ] ) ) { + + // Search, expanding context for leading sibling combinators + if ( ( seed = find( + unescapeSelector( token.matches[ 0 ] ), + rsibling.test( tokens[ 0 ].type ) && + testContext( context.parentNode ) || context + ) ) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +} + +// Initialize against the default document +setDocument(); + +jQuery.find = find; + +// These have always been private, but they used to be documented as part of +// Sizzle so let's maintain them for now for backwards compatibility purposes. +find.compile = compile; +find.select = select; +find.setDocument = setDocument; +find.tokenize = tokenize; + +function dir( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +} + +function siblings( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +} + +var rneedsContext = jQuery.expr.match.needsContext; + +// rsingleTag matches a string consisting of a single HTML element with no attributes +// and captures the element's name +var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i; + +function isObviousHtml( input ) { + return input[ 0 ] === "<" && + input[ input.length - 1 ] === ">" && + input.length >= 3; +} + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( typeof qualifier === "function" ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + +// Initialize a jQuery object + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (trac-9521) + // Strict HTML recognition (trac-11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // HANDLE: $(DOMElement) + if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( typeof selector === "function" ) { + return rootjQuery.ready !== undefined ? + rootjQuery.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + + } else { + + // Handle obvious HTML strings + match = selector + ""; + if ( isObviousHtml( match ) ) { + + // Assume that strings that start and end with <> are HTML and skip + // the regex check. This also handles browser-supported HTML wrappers + // like TrustedHTML. + match = [ null, selector, null ]; + + // Handle HTML strings or selectors + } else if ( typeof selector === "string" ) { + match = rquickExpr.exec( selector ); + } else { + return jQuery.makeArray( selector, this ); + } + + // Match html or make sure no context is specified for #id + // Note: match[1] may be a string or a TrustedHTML wrapper + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document$1, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( typeof this[ match ] === "function" ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document$1.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr) & $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + } + + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document$1 ); + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to jQuery#find + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11+ + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( typeof arg === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && typeof( method = value.promise ) === "function" ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && typeof( method = value.then ) === "function" ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + reject( value ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + catch: function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = typeof fns[ tuple[ 4 ] ] === "function" && + fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && typeof returned.promise === "function" ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( typeof then === "function" ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.error ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the error, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getErrorHook ) { + process.error = jQuery.Deferred.getErrorHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + typeof onProgress === "function" ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + typeof onFulfilled === "function" ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + typeof onRejected === "function" ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the primary Deferred + primary = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + primary.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( primary.state() === "pending" || + typeof( resolveValues[ i ] && resolveValues[ i ].then ) === "function" ) { + + return primary.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); + } + + return primary.promise(); + } +} ); + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +// If `jQuery.Deferred.getErrorHook` is defined, `asyncError` is an error +// captured before the async barrier to get the original error cause +// which may otherwise be hidden. +jQuery.Deferred.exceptionHook = function( error, asyncError ) { + + if ( error && rerrorNames.test( error.name ) ) { + window.console.warn( + "jQuery.Deferred exception", + error, + asyncError + ); + } +}; + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See trac-6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document$1, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document$1.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +if ( document$1.readyState !== "loading" ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document$1.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + +// Matches dashed string for camelizing +var rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase +function camelCase( string ) { + return string.replace( rdashAlpha, fcamelCase ); +} + +/** + * Determines whether an object can have data + */ +function acceptData( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +} + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = Object.create( null ); + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see trac-8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return value; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45+ + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; + +var dataPriv = new Data(); + +var dataUser = new Data(); + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11+ + // The attrs elements can be null (trac-14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.set( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.set( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); + +var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +// isHiddenWithinTree reports if an element has a non-"none" display style (inline and/or +// through the CSS cascade), which is useful in deciding whether or not to make it visible. +// It differs from the :hidden selector (jQuery.expr.pseudos.hidden) in two important ways: +// * A hidden ancestor does not force an element to be classified as hidden. +// * Being disconnected from the document does not force an element to be classified as hidden. +// These differences improve the behavior of .toggle() et al. when applied to elements that are +// detached or contained within hidden ancestors (gh-2404, gh-2863). +function isHiddenWithinTree( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + jQuery.css( elem, "display" ) === "none"; +} + +var ralphaStart = /^[a-z]/, + + // The regex visualized: + // + // /----------\ + // | | /-------\ + // | / Top \ | | | + // /--- Border ---+-| Right |-+---+- Width -+---\ + // | | Bottom | | + // | \ Left / | + // | | + // | /----------\ | + // | /-------------\ | | |- END + // | | | | / Top \ | | + // | | / Margin \ | | | Right | | | + // |---------+-| |-+---+-| Bottom |-+----| + // | \ Padding / \ Left / | + // BEGIN -| | + // | /---------\ | + // | | | | + // | | / Min \ | / Width \ | + // \--------------+-| |-+---| |---/ + // \ Max / \ Height / + rautoPx = /^(?:Border(?:Top|Right|Bottom|Left)?(?:Width|)|(?:Margin|Padding)?(?:Top|Right|Bottom|Left)?|(?:Min|Max)?(?:Width|Height))$/; + +function isAutoPx( prop ) { + + // The first test is used to ensure that: + // 1. The prop starts with a lowercase letter (as we uppercase it for the second regex). + // 2. The prop is not empty. + return ralphaStart.test( prop ) && + rautoPx.test( prop[ 0 ].toUpperCase() + prop.slice( 1 ) ); +} + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( isAutoPx( prop ) ? "px" : "" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( !isAutoPx( prop ) || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 - 66+ + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/; + +// Convert dashed to camelCase, handle vendor prefixes. +// Used by the css & effects modules. +// Support: IE <=9 - 11+ +// Microsoft forgot to hump their vendor prefix (trac-9572) +function cssCamelCase( string ) { + return camelCase( string.replace( rmsPrefix, "ms-" ) ); +} + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); + +var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }, + composed = { composed: true }; + +// Support: IE 9 - 11+ +// Check attachment across shadow DOM boundaries when possible (gh-3504). +// Provide a fallback for browsers without Shadow DOM v1 support. +if ( !documentElement$1.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }; +} + +// rtagName captures the name from the first start tag in a string of HTML +// https://html.spec.whatwg.org/multipage/syntax.html#tag-open-state +// https://html.spec.whatwg.org/multipage/syntax.html#tag-name-state +var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i; + +var wrapMap = { + + // Table parts need to be wrapped with `` or they're + // stripped to their contents when put in a div. + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do, so we cannot shorten + // this by omitting or other required elements. + thead: [ "table" ], + col: [ "colgroup", "table" ], + tr: [ "tbody", "table" ], + td: [ "tr", "tbody", "table" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function getAll( context, tag ) { + + // Support: IE <=9 - 11+ + // Use typeof to avoid zero-argument method invocation on host objects (trac-15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + + // Use slice to snapshot the live collection from gEBTN + ret = arr.slice.call( context.getElementsByTagName( tag || "*" ) ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + +var rscriptType = /^$|^module$|\/(?:java|ecma)script/i; + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" && ( elem.nodeType || isArrayLike( elem ) ) ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || arr; + + // Create wrappers & descend into them. + j = wrap.length; + while ( --j > -1 ) { + tmp = tmp.appendChild( context.createElement( wrap[ j ] ) ); + } + + tmp.innerHTML = jQuery.htmlPrefilter( elem ); + + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (trac-12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = typeof value === "function"; + + if ( valueIsFunction ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + args[ 0 ] = value.call( this, index, self.html() ); + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (trac-8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Re-enable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.get( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce, + crossOrigin: node.crossOrigin + }, doc ); + } + } else { + DOMEval( node.textContent, node, doc ); + } + } + } + } + } + } + + return collection; +} + +var rcheckableType = /^(?:checkbox|radio)$/i; + +var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement$1, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: Firefox <=42 - 66+ + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11+ + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (trac-13208) + // Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (trac-13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: typeof hook === "function" ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: jQuery.extend( Object.create( null ), { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", true ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + if ( event.result !== undefined ) { + + // Setting `event.originalEvent.returnValue` in modern + // browsers does the same as just calling `preventDefault()`, + // the browsers ignore the value anyway. + // Incidentally, IE 11 is the only browser from our supported + // ones which respects the value returned from a `beforeunload` + // handler attached by `addEventListener`; other browsers do + // so only for inline handlers, so not setting the value + // directly shouldn't reduce any functionality. + event.preventDefault(); + } + } + } + } ) +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, isSetup ) { + + // Missing `isSetup` indicates a trigger call, which must force setup through jQuery.event.add + if ( !isSetup ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var result, + saved = dataPriv.get( this, type ); + + // This controller function is invoked under multiple circumstances, + // differentiated by the stored value in `saved`: + // 1. For an outer synthetic `.trigger()`ed event (detected by + // `event.isTrigger & 1` and non-array `saved`), it records arguments + // as an array and fires an [inner] native event to prompt state + // changes that should be observed by registered listeners (such as + // checkbox toggling and focus updating), then clears the stored value. + // 2. For an [inner] native event (detected by `saved` being + // an array), it triggers an inner synthetic event, records the + // result, and preempts propagation to further jQuery listeners. + // 3. For an inner synthetic event (detected by `event.isTrigger & 1` and + // array `saved`), it prevents double-propagation of surrogate events + // but otherwise allows everything to proceed (particularly including + // further listeners). + // Possible `saved` data shapes: `[...], `{ value }`, `false`. + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + if ( !saved.length ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), + // so this array will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + this[ type ](); + result = dataPriv.get( this, type ); + dataPriv.set( this, type, false ); + + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + + // Support: Chrome 86+ + // In Chrome, if an element having a focusout handler is + // blurred by clicking outside of it, it invokes the handler + // synchronously. If that handler calls `.remove()` on + // the element, the data is cleared, leaving `result` + // undefined. We need to guard against this. + return result && result.value; + } + + // If this is an inner synthetic event for an event with a bubbling + // surrogate (focus or blur), assume that the surrogate already + // propagated from triggering the native event and prevent that + // from happening again here. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order. + // Fire an inner synthetic event with the original arguments. + } else if ( saved.length ) { + + // ...and capture the result + dataPriv.set( this, type, { + value: jQuery.event.trigger( + saved[ 0 ], + saved.slice( 1 ), + this + ) + } ); + + // Abort handling of the native event by all jQuery handlers while allowing + // native handlers on the same element to run. On target, this is achieved + // by stopping immediate propagation just on the jQuery event. However, + // the native event is re-wrapped by a jQuery one on each level of the + // propagation so the only way to stop it for jQuery is to stop it for + // everyone via native `stopPropagation()`. This is not a problem for + // focus/blur which don't bubble, but it does also stop click on checkboxes + // and radios. We accept this limitation. + event.stopPropagation(); + event.isImmediatePropagationStopped = returnTrue; + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented ? + returnTrue : + returnFalse; + + // Create target properties + this.target = src.target; + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + which: true +}, jQuery.event.addProp ); + +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + + // Support: IE 11+ + // Attach a single focusin/focusout handler on the document while someone wants focus/blur. + // This is because the former are synchronous in IE while the latter are async. In other + // browsers, all those handlers are invoked synchronously. + function focusMappedHandler( nativeEvent ) { + + // `eventHandle` would already wrap the event, but we need to change the `type` here. + var event = jQuery.event.fix( nativeEvent ); + event.type = nativeEvent.type === "focusin" ? "focus" : "blur"; + event.isSimulated = true; + + // focus/blur don't bubble while focusin/focusout do; simulate the former by only + // invoking the handler at the lower level. + if ( event.target === event.currentTarget ) { + + // The setup part calls `leverageNative`, which, in turn, calls + // `jQuery.event.add`, so event handle will already have been set + // by this point. + dataPriv.get( this, "handle" )( event ); + } + } + + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, true ); + + if ( isIE ) { + this.addEventListener( delegateType, focusMappedHandler ); + } else { + + // Return false to allow normal processing in the caller + return false; + } + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + teardown: function() { + if ( isIE ) { + this.removeEventListener( delegateType, focusMappedHandler ); + } else { + + // Return false to indicate standard teardown should be applied + return false; + } + }, + + // Suppress native focus or blur if we're currently inside + // a leveraged native-event stack + _default: function( event ) { + return dataPriv.get( event.target, type ); + }, + + delegateType: delegateType + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + +var + + // Support: IE <=10 - 11+ + // In IE using regex groups here causes severe slowdowns. + rnoInnerhtml = / 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + push.apply( ret, elems ); + } + + return this.pushStack( ret ); + }; +} ); + +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var rcustomProp = /^--/; + +function getStyles( elem ) { + + // Support: IE <=11+ (trac-14150) + // In IE popup's `window` is the opener window which makes `window.getComputedStyle( elem )` + // break. Using `elem.ownerDocument.defaultView` avoids the issue. + var view = elem.ownerDocument.defaultView; + + // `document.implementation.createHTMLDocument( "" )` has a `null` `defaultView` + // property; check `defaultView` truthiness to fallback to window in such a case. + if ( !view ) { + view = window; + } + + return view.getComputedStyle( elem ); +} + +// A method for quickly swapping in/out CSS properties to get correct calculations. +function swap( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +} + +function curCSS( elem, name, computed ) { + var ret, + isCustomProp = rcustomProp.test( name ); + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for `.css('--customProperty')` (gh-3144) + if ( computed ) { + + // A fallback to direct property access is needed as `computed`, being + // the output of `getComputedStyle`, contains camelCased keys and + // `getPropertyValue` requires kebab-case ones. + // + // Support: IE <=9 - 11+ + // IE only supports `"float"` in `getPropertyValue`; in computed styles + // it's only available as `"cssFloat"`. We no longer modify properties + // sent to `.css()` apart from camelCasing, so we need to check both. + // Normally, this would create difference in behavior: if + // `getPropertyValue` returns an empty string, the value returned + // by `.css()` would be `undefined`. This is usually the case for + // disconnected elements. However, in IE even disconnected elements + // with no styles return `"none"` for `getPropertyValue( "float" )` + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( isCustomProp && ret ) { + + // Support: Firefox 105 - 135+ + // Spec requires trimming whitespace for custom properties (gh-4926). + // Firefox only trims leading whitespace. + // + // Fall back to `undefined` if empty string returned. + // This collapses a missing definition with property defined + // and set to an empty string but there's no standard API + // allowing us to differentiate them without a performance penalty + // and returning `undefined` aligns with older jQuery. + // + // rtrimCSS treats U+000D CARRIAGE RETURN and U+000C FORM FEED + // as whitespace while CSS does not, but this is not a problem + // because CSS preprocessing replaces them with U+000A LINE FEED + // (which *is* CSS whitespace) + // https://www.w3.org/TR/css-syntax-3/#input-preprocessing + ret = ret.replace( rtrimCSS, "$1" ) || undefined; + } + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11+ + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document$1.createElement( "div" ).style; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped vendor prefixed property +function finalPropName( name ) { + if ( name in emptyStyle ) { + return name; + } + return vendorPropName( name ) || name; +} + +var reliableTrDimensionsVal, reliableColDimensionsVal, + table = document$1.createElement( "table" ); + +// Executing table tests requires only one layout, so they're executed +// at the same time to save the second computation. +function computeTableStyleTests() { + if ( + + // This is a singleton, we need to execute it only once + !table || + + // Finish early in limited (non-browser) environments + !table.style + ) { + return; + } + + var trStyle, + col = document$1.createElement( "col" ), + tr = document$1.createElement( "tr" ), + td = document$1.createElement( "td" ); + + table.style.cssText = "position:absolute;left:-11111px;" + + "border-collapse:separate;border-spacing:0"; + tr.style.cssText = "box-sizing:content-box;border:1px solid;height:1px"; + td.style.cssText = "height:9px;width:9px;padding:0"; + + col.span = 2; + + documentElement$1 + .appendChild( table ) + .appendChild( col ) + .parentNode + .appendChild( tr ) + .appendChild( td ) + .parentNode + .appendChild( td.cloneNode( true ) ); + + // Don't run until window is visible + if ( table.offsetWidth === 0 ) { + documentElement$1.removeChild( table ); + return; + } + + trStyle = window.getComputedStyle( tr ); + + // Support: Firefox 135+ + // Firefox always reports computed width as if `span` was 1. + // Support: Safari 18.3+ + // In Safari, computed width for columns is always 0. + // In both these browsers, using `offsetWidth` solves the issue. + // Support: IE 11+ + // In IE, `` computed width is `"auto"` unless `width` is set + // explicitly via CSS so measurements there remain incorrect. Because of + // the lack of a proper workaround, we accept this limitation, treating + // IE as passing the test. + reliableColDimensionsVal = isIE || Math.round( parseFloat( + window.getComputedStyle( col ).width ) + ) === 18; + + // Support: IE 10 - 11+ + // IE misreports `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Support: Firefox 70 - 135+ + // Only Firefox includes border widths + // in computed dimensions for table rows. (gh-4529) + reliableTrDimensionsVal = Math.round( parseFloat( trStyle.height ) + + parseFloat( trStyle.borderTopWidth ) + + parseFloat( trStyle.borderBottomWidth ) ) === tr.offsetHeight; + + documentElement$1.removeChild( table ); + + // Nullify the table so it wouldn't be stored in the memory; + // it will also be a sign that checks were already performed. + table = null; +} + +jQuery.extend( support, { + reliableTrDimensions: function() { + computeTableStyleTests(); + return reliableTrDimensionsVal; + }, + + reliableColDimensions: function() { + computeTableStyleTests(); + return reliableColDimensionsVal; + } +} ); + +var cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0, + marginDelta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + // Count margin delta separately to only add it after scroll gutter adjustment. + // This is needed to make negative margins work with `outerHeight( true )` (gh-3982). + if ( box === "margin" ) { + marginDelta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta + marginDelta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = isIE || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + if ( + ( + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: IE 9 - 11+ + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + ( isIE && isBorderBox ) || + + ( !support.reliableColDimensions() && nodeName( elem, "col" ) ) || + + ( !support.reliableTrDimensions() && nodeName( elem, "tr" ) ) + ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = cssCamelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (trac-7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug trac-9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (trac-7116) + if ( value == null || value !== value ) { + return; + } + + // If the value is a number, add `px` for certain CSS properties + if ( type === "number" ) { + value += ret && ret[ 3 ] || ( isAutoPx( origName ) ? "px" : "" ); + } + + // Support: IE <=9 - 11+ + // background-* props of a cloned element affect the source element (trac-8908) + if ( isIE && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = cssCamelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Elements with `display: none` can have dimension info if + // we invisibly show them. + return jQuery.css( elem, "display" ) === "none" ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + isBorderBox = extra && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( isAutoPx( prop ) ? "px" : "" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document$1.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, 13 ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11+ + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.set( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + // eslint-disable-next-line no-loop-func + anim.done( function() { + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = cssCamelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + percent = 1 - ( remaining / animation.duration || 0 ), + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( typeof result.stop === "function" ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( typeof animation.opts.start === "function" ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( typeof props === "function" ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || easing || + typeof speed === "function" && speed, + duration: speed, + easing: fn && easing || easing && typeof easing !== "function" && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( typeof opt.old === "function" ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + +// Based off of the plugin by Clint Helfers, with permission. +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11+ + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // Use proper attribute retrieval (trac-12072) + var tabindex = elem.getAttribute( "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + + // href-less anchor's `tabIndex` property value is `0` and + // the `tabindex` attribute value: `null`. We want `-1`. + rclickable.test( elem.nodeName ) && elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11+ +// Accessing the selectedIndex property forces the browser to respect +// setting selected on the option. The getter ensures a default option +// is selected when in an optgroup. ESLint rule "no-unused-expressions" +// is disabled for this code since it considers such accessions noop. +if ( isIE ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + // eslint-disable-next-line no-unused-expressions + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + + var parent = elem.parentNode; + if ( parent ) { + // eslint-disable-next-line no-unused-expressions + parent.selectedIndex; + + if ( parent.parentNode ) { + // eslint-disable-next-line no-unused-expressions + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + +// Strip and collapse whitespace according to HTML spec +// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace +function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); +} + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( typeof value === "function" ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + if ( cur.indexOf( " " + className + " " ) < 0 ) { + cur += className + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + removeClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( typeof value === "function" ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + + // This expression is here for better compressibility (see addClass) + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Remove *all* instances + while ( cur.indexOf( " " + className + " " ) > -1 ) { + cur = cur.replace( " " + className + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var classNames, className, i, self; + + if ( typeof value === "function" ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + if ( typeof stateVal === "boolean" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + + // Toggle individual class names + self = jQuery( this ); + + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + } ); + } + + return this; + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = typeof value === "function"; + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + if ( option.selected && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + if ( ( option.selected = + jQuery.inArray( jQuery( option ).val(), values ) > -1 + ) ) { + optionSet = true; + } + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +if ( isIE ) { + jQuery.valHooks.option = { + get: function( elem ) { + + var val = elem.getAttribute( "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11+ + // option.text throws exceptions (trac-14686, trac-14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }; +} + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; +} ); + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document$1 ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document$1; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (trac-9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document$1 ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (trac-6170) + if ( ontype && typeof elem[ type ] === "function" && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = /\?/; + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml, parserErrorElem; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11+ + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) {} + + parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; + if ( !xml || parserErrorElem ) { + jQuery.error( "Invalid XML: " + ( + parserErrorElem ? + jQuery.map( parserErrorElem.childNodes, function( el ) { + return el.textContent; + } ).join( "\n" ) : + data + ) ); + } + return xml; +}; + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = typeof valueOrFunction === "function" ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ).filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ).map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // trac-7653, trac-8125, trac-8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document$1.createElement( "a" ); + +originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( typeof func === "function" ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes trac-9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + + // Support: IE 11+ + // `getResponseHeader( key )` in IE doesn't combine all header + // values for the provided key into a single result with values + // joined by commas as other browsers do. Instead, it returns + // them on separate lines. + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (trac-10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket trac-12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document$1.createElement( "a" ); + + // Support: IE <=8 - 11+ + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11+ + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an ESM-usage scenario (trac-15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // trac-9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + + ( nonce.guid++ ) + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script but not if jsonp + if ( !isSuccess && + jQuery.inArray( "script", s.dataTypes ) > -1 && + jQuery.inArray( "json", s.dataTypes ) < 0 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted. + // Handle the null callback placeholder. + if ( typeof data === "function" || data === null ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (trac-11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + scriptAttrs: options.crossOrigin ? { "crossOrigin": options.crossOrigin } : undefined, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( typeof html === "function" ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( typeof html === "function" ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = typeof html === "function"; + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + +jQuery.ajaxSettings.xhr = function() { + return new window.XMLHttpRequest(); +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200 +}; + +jQuery.ajaxTransport( function( options ) { + var callback; + + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + complete( + + // File: protocol always yields status 0; see trac-8605, trac-14207 + xhr.status, + xhr.statusText + ); + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) === "text" ? + { text: xhr.responseText } : + { binary: xhr.response }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + xhr.onabort = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // trac-14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; +} ); + +function canUseScriptTag( s ) { + + // A script tag can only be used for async, cross domain or forced-by-attrs requests. + // Requests with headers cannot use a script tag. However, when both `scriptAttrs` & + // `headers` options are specified, both are impossible to satisfy together; we + // prefer `scriptAttrs` then. + // Sync requests remain handled differently to preserve strict script ordering. + return s.scriptAttrs || ( + !s.headers && + ( + s.crossDomain || + + // When dealing with JSONP (`s.dataTypes` include "json" then) + // don't use a script tag so that error responses still may have + // `responseJSON` set. Continue using a script tag for JSONP requests that: + // * are cross-domain as AJAX requests won't work without a CORS setup + // * have `scriptAttrs` set as that's a script-only functionality + // Note that this means JSONP requests violate strict CSP script-src settings. + // A proper solution is to migrate from using JSONP to a CORS setup. + ( s.async && jQuery.inArray( "json", s.dataTypes ) < 0 ) + ) + ); +} + +// Install script dataType. Don't specify `contents.script` so that an explicit +// `dataType: "script"` is required (see gh-2432, gh-4822) +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + + // These types of requests are handled via a script tag + // so force their methods to GET. + if ( canUseScriptTag( s ) ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + if ( canUseScriptTag( s ) ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " diff --git a/wicket-core/src/test/js/amd.html b/wicket-core/src/test/js/amd.html deleted file mode 100644 index dfd314cffca..00000000000 --- a/wicket-core/src/test/js/amd.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - Asynchronous module tests - - - - - - - - - - -
- -
- -
-
- - diff --git a/wicket-core/src/test/js/amd.js b/wicket-core/src/test/js/amd.js deleted file mode 100644 index b036e9e2149..00000000000 --- a/wicket-core/src/test/js/amd.js +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/*global ok: true, start: true, test: true, equal: true, deepEqual: true, - QUnit: true, module: true, expect: true, define: true, console: true */ - -define( - [ - "jquery", - "Wicket", - "qunit" - ], - function ($, w, qunit) { - "use strict"; - - return { - runTests: function () { - qunit.test("Wicket object is successfully loaded via RequireJs", assert => { - assert.expect(13); - - // test for one member for each Wicket.** module - assert.ok($.isFunction(w.Event.fix), "Wicket Event (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.Ajax.ajax), "Wicket Ajax (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.DOM.get), "Wicket DOM (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.Form.serialize), "Wicket Form (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(new w.Channel("blah|s").done), "Wicket Channel (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(new w.ChannelManager().done), "Wicket ChannelManager (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.Class.create), "Wicket Class (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.Head.addElement), "Wicket Head (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.Focus.focusin), "Wicket Focus (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(w.Log.error), "Wicket Log (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(new w.Throttler().throttle), "Wicket Throttler (from wicket-ajax-jquery.js) is imported"); - assert.ok($.isFunction(new w.ThrottlerEntry().getFunc), "Wicket ThrottlerEntry (from wicket-ajax-jquery.js) is imported"); - - assert.equal('div', w.DOM.get('amdElement').tagName.toLowerCase(), "Wicket.DOM.get() works"); - }); - } - }; - } -); diff --git a/wicket-core/src/test/js/amd/require.js b/wicket-core/src/test/js/amd/require.js deleted file mode 100644 index 651902f2172..00000000000 --- a/wicket-core/src/test/js/amd/require.js +++ /dev/null @@ -1,37 +0,0 @@ -/* - RequireJS 2.1.22 Copyright (c) 2010-2015, The Dojo Foundation All Rights Reserved. - Available via the MIT or new BSD license. - see: http://github.com/jrburke/requirejs for details -*/ -var requirejs,require,define; -(function(ha){function L(b){return"[object Function]"===R.call(b)}function M(b){return"[object Array]"===R.call(b)}function x(b,c){if(b){var d;for(d=0;dthis.depCount&&!this.defined){if(L(l)){try{f=h.execCb(c,l,b,f)}catch(d){a=d}this.map.isDefine&&void 0===f&&((b=this.module)?f=b.exports: -this.usingExports&&(f=this.exports));if(a){if(this.events.error&&this.map.isDefine||k.onError!==ia)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",B(this.error=a);if("undefined"!==typeof console&&console.error)console.error(a);else k.onError(a)}}else f=l;this.exports=f;if(this.map.isDefine&&!this.ignore&&(r[c]=f,k.onResourceLoad)){var e=[];x(this.depMaps,function(a){e.push(a.normalizedMap||a)});k.onResourceLoad(h, -this.map,e)}D(c);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}},callPlugin:function(){var a=this.map,b=a.id,d=q(a.prefix);this.depMaps.push(d);v(d,"defined",y(this,function(f){var l,d,e=g(ga,this.map.id),N=this.map.name,p=this.map.parentMap?this.map.parentMap.name:null,r=h.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(N=f.normalize(N,function(a){return c(a, -p,!0)})||""),d=q(a.prefix+"!"+N,this.map.parentMap),v(d,"defined",y(this,function(a){this.map.normalizedMap=d;this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),f=g(t,d.id)){this.depMaps.push(d);if(this.events.error)f.on("error",y(this,function(a){this.emit("error",a)}));f.enable()}}else e?(this.map.url=h.nameToUrl(e),this.load()):(l=y(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),l.error=y(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b]; -E(t,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&D(a.map.id)});B(a)}),l.fromText=y(this,function(f,c){var d=a.name,e=q(d),N=T;c&&(f=c);N&&(T=!1);u(e);w(m.config,b)&&(m.config[d]=m.config[b]);try{k.exec(f)}catch(g){return B(G("fromtexteval","fromText eval for "+b+" failed: "+g,g,[b]))}N&&(T=!0);this.depMaps.push(e);h.completeLoad(d);r([d],l)}),f.load(a.name,r,l,m))}));h.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){aa[this.map.id]=this;this.enabling=this.enabled=!0;x(this.depMaps, -y(this,function(a,b){var c,f;if("string"===typeof a){a=q(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=g(S,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;v(a,"defined",y(this,function(a){this.undefed||(this.defineDep(b,a),this.check())}));this.errback?v(a,"error",y(this,this.errback)):this.events.error&&v(a,"error",y(this,function(a){this.emit("error",a)}))}c=a.id;f=t[c];w(S,c)||!f||f.enabled||h.enable(a,this)}));E(this.pluginMaps,y(this,function(a){var b= -g(t,a.id);b&&!b.enabled&&h.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){x(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};h={config:m,contextName:b,registry:t,defined:r,urlFetched:X,defQueue:H,defQueueMap:{},Module:ea,makeModuleMap:q,nextTick:k.nextTick,onError:B,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=m.shim,c={paths:!0, -bundles:!0,config:!0,map:!0};E(a,function(a,b){c[b]?(m[b]||(m[b]={}),Z(m[b],a,!0,!0)):m[b]=a});a.bundles&&E(a.bundles,function(a,b){x(a,function(a){a!==b&&(ga[a]=b)})});a.shim&&(E(a.shim,function(a,c){M(a)&&(a={deps:a});!a.exports&&!a.init||a.exportsFn||(a.exportsFn=h.makeShimExports(a));b[c]=a}),m.shim=b);a.packages&&x(a.packages,function(a){var b;a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(m.paths[b]=a.location);m.pkgs[b]=a.name+"/"+(a.main||"main").replace(na,"").replace(V,"")});E(t, -function(a,b){a.inited||a.map.unnormalized||(a.map=q(b,null,!0))});(a.deps||a.callback)&&h.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ha,arguments));return b||a.exports&&ja(a.exports)}},makeRequire:function(a,n){function e(c,d,g){var m,p;n.enableBuildCallback&&d&&L(d)&&(d.__requireJsBuild=!0);if("string"===typeof c){if(L(d))return B(G("requireargs","Invalid require call"),g);if(a&&w(S,c))return S[c](t[a.id]);if(k.get)return k.get(h, -c,a,e);m=q(c,a,!1,!0);m=m.id;return w(r,m)?r[m]:B(G("notloaded",'Module name "'+m+'" has not been loaded yet for context: '+b+(a?"":". Use require([])")))}Q();h.nextTick(function(){Q();p=u(q(null,a));p.skipMap=n.skipMap;p.init(c,d,g,{enabled:!0});I()});return e}n=n||{};Z(e,{isBrowser:F,toUrl:function(b){var d,e=b.lastIndexOf("."),n=b.split("/")[0];-1!==e&&("."!==n&&".."!==n||1e.attachEvent.toString().indexOf("[native code")||da?(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)):(T=!0,e.attachEvent("onreadystatechange",b.onScriptLoad));e.src=d;Q=e;I?D.insertBefore(e,I):D.appendChild(e);Q=null;return e}if(ka)try{importScripts(d),b.completeLoad(c)}catch(q){b.onError(G("importscripts","importScripts failed for "+ -c+" at "+d,q,[c]))}};F&&!v.skipDataMain&&Y(document.getElementsByTagName("script"),function(b){D||(D=b.parentNode);if(P=b.getAttribute("data-main"))return u=P,v.baseUrl||(J=u.split("/"),u=J.pop(),U=J.length?J.join("/")+"/":"./",v.baseUrl=U),u=u.replace(V,""),k.jsExtRegExp.test(u)&&(u=P),v.deps=v.deps?v.deps.concat(u):[u],!0});define=function(b,c,d){var g,e;"string"!==typeof b&&(d=c,c=b,b=null);M(c)||(d=c,c=null);!c&&L(d)&&(c=[],d.length&&(d.toString().replace(qa,"").replace(ra,function(b,d){c.push(d)}), -c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));T&&(g=Q||pa())&&(b||(b=g.getAttribute("data-requiremodule")),e=K[g.getAttribute("data-requirecontext")]);e?(e.defQueue.push([b,c,d]),e.defQueueMap[b]=!0):W.push([b,c,d])};define.amd={jQuery:!0};k.exec=function(b){return eval(b)};k(v)}})(this); diff --git a/wicket-core/src/test/js/dom.js b/wicket-core/src/test/js/dom.js index 405bfcaaac3..56181b12c18 100644 --- a/wicket-core/src/test/js/dom.js +++ b/wicket-core/src/test/js/dom.js @@ -97,7 +97,7 @@ jQuery(document).ready(function() { assert.equal($deserialized[0].tagName.toLowerCase(), 'div', 'The serialized element name should be
'); assert.equal($deserialized.prop('id'), complexElementId, 'The serialized element id should be ' + complexElementId); assert.equal($deserialized.children()[0].tagName.toLowerCase(), 'a', 'The serialized element should have one child '); - assert.equal(jQuery.trim($deserialized.text()), 'Link', 'The serialized element should have text "Link"'); + assert.equal($deserialized.text().trim(), 'Link', 'The serialized element should have text "Link"'); }); test("show() an element", assert => { diff --git a/wicket-core/src/test/js/form.js b/wicket-core/src/test/js/form.js index 2edeaa2b134..59caa5b53ca 100644 --- a/wicket-core/src/test/js/form.js +++ b/wicket-core/src/test/js/form.js @@ -187,7 +187,7 @@ jQuery(document).ready(function() { }); queryString = jQuery.param(queryString, true); - var space = jQuery.fn.jquery.indexOf("3") === 0 ? "%20" : "+"; + var space = jQuery.fn.jquery.startsWith("2") ? "+" : "%20"; assert.equal(queryString, 'textInput=textValue&textUTFInput=%D0%BD%D0%B5%D1%89%D0%BE'+space+'%D0%BD%D0%B0'+space+'%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8&checkBoxInput1=cbValue1&checkBoxInput3=cbValue3&radioInput=radioValue1&emailInput=m%40g.com&urlInput=http%3A%2F%2Fexample.com&searchInput=wicket&rangeInput=67&numberInput=16&colorInput=%23123456&multipleSelect=0&multipleSelect=2&select=0&textArea=some'+space+'text', 'Wicket.Form.serialize should serialize the whole form when an element is passed and the parent form should be searched'); }); @@ -202,7 +202,7 @@ jQuery(document).ready(function() { }); queryString = jQuery.param(queryString, true); - var space = jQuery.fn.jquery.indexOf("3") === 0 ? "%20" : "+"; + var space = jQuery.fn.jquery.startsWith("2") ? "+" : "%20"; assert.equal(queryString, 'textInput=textValue&textUTFInput=%D0%BD%D0%B5%D1%89%D0%BE'+space+'%D0%BD%D0%B0'+space+'%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8&checkBoxInput1=cbValue1&checkBoxInput3=cbValue3&radioInput=radioValue1&emailInput=m%40g.com&urlInput=http%3A%2F%2Fexample.com&searchInput=wicket&rangeInput=67&numberInput=16&colorInput=%23123456&multipleSelect=0&multipleSelect=2&select=0&textArea=some'+space+'text', 'Wicket.Form.serialize should serialize the whole form when a the form itself is passed'); }); diff --git a/wicket-core/src/test/js/qunit/jquery.mockjax.js b/wicket-core/src/test/js/qunit/jquery.mockjax.js index 6fc1b6aa7a0..b3755846a75 100644 --- a/wicket-core/src/test/js/qunit/jquery.mockjax.js +++ b/wicket-core/src/test/js/qunit/jquery.mockjax.js @@ -1,13 +1,12 @@ /*! jQuery Mockjax * A Plugin providing simple and flexible mocking of ajax requests and responses * - * Version: 2.5.0 + * Version: 2.7.0 * Home: https://github.com/jakerella/jquery-mockjax - * Copyright (c) 2018 Jordan Kasper, formerly appendTo; + * Copyright (c) 2026 Jordan Kasper, formerly appendTo; * NOTE: This repository was taken over by Jordan Kasper (@jakerella) October, 2014 * - * Dual licensed under the MIT or GPL licenses. - * http://opensource.org/licenses/MIT OR http://www.gnu.org/licenses/gpl-2.0.html + * Licensed under the MIT license: http://opensource.org/licenses/MIT */ (function(root, factory) { 'use strict'; @@ -79,14 +78,14 @@ logger.debug( mock, ['Checking mock data against request data', mock, live] ); var identical = true; - if ( $.isFunction(mock) ) { + if (typeof mock === 'function') { return !!mock(live); } // Test for situations where the data is a querystring (not an object) if (typeof live === 'string') { // Querystring may be a regex - if ($.isFunction( mock.test )) { + if (typeof mock.test === 'function') { return mock.test(live); } else if (typeof mock === 'object') { live = getQueryParams(live); @@ -101,12 +100,12 @@ return identical; } else { if ( typeof live[k] === 'object' && live[k] !== null ) { - if ( identical && $.isArray( live[k] ) ) { - identical = $.isArray( mock[k] ) && live[k].length === mock[k].length; + if ( identical && Array.isArray( live[k] ) ) { + identical = Array.isArray( mock[k] ) && live[k].length === mock[k].length; } identical = identical && isMockDataEqual(mock[k], live[k]); } else { - if ( mock[k] && $.isFunction( mock[k].test ) ) { + if ( mock[k] && typeof mock[k].test === 'function') { identical = identical && mock[k].test(live[k]); } else { identical = identical && ( mock[k] === live[k] ); @@ -161,36 +160,42 @@ function getMockForRequest( handler, requestSettings ) { // If the mock was registered with a function, let the function decide if we // want to mock this request - if ( $.isFunction(handler) ) { + if (typeof handler === 'function') { return handler( requestSettings ); } + // Apply namespace prefix to the mock handler's url. + var namespace = handler.namespace || (typeof(handler.namespace) === 'undefined' && $.mockjaxSettings.namespace); + // Inspect the URL of the request and check if the mock handler's url // matches the url for this ajax request - if ( $.isFunction(handler.url.test) ) { + if (typeof handler.url.test === 'function') { + // namespace exists prepend handler.url with namespace + if (!!namespace) { + namespace = namespace.replace(/(\/+)$/, ''); + var pattern = handler.url.source.replace(/^(\^+)/, '').replace(/^/, '^(' + namespace + ')?\/?'); + handler.url = new RegExp(pattern); + } // The user provided a regex for the url, test it if ( !handler.url.test( requestSettings.url ) ) { return null; } } else { - var effecitveUrl = handler.url; - - // Apply namespace prefix to the mock handler's url. - var namespace = handler.namespace || (typeof(handler.namespace) === 'undefined' && $.mockjaxSettings.namespace); + var effectiveUrl = handler.url; if (!!namespace) { var namespacedUrl = [ namespace.replace(/(\/+)$/, ''), handler.url.replace(/^(\/+)/, '') ].join('/'); - effecitveUrl = namespacedUrl; + effectiveUrl = namespacedUrl; } // Look for a simple wildcard '*' or a direct URL match - var star = effecitveUrl.indexOf('*'); - if (effecitveUrl !== requestSettings.url && star === -1 || - !new RegExp(effecitveUrl.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, '.+')).test(requestSettings.url)) { + var star = effectiveUrl.indexOf('*'); + if (effectiveUrl !== requestSettings.url && star === -1 || + !new RegExp(effectiveUrl.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, '.+')).test(requestSettings.url)) { return null; } } @@ -238,7 +243,7 @@ } function parseResponseTimeOpt(responseTime) { - if ($.isArray(responseTime) && responseTime.length === 2) { + if (Array.isArray(responseTime) && responseTime.length === 2) { var min = responseTime[0]; var max = responseTime[1]; if(isPosNum(min) && isPosNum(max)) { @@ -287,7 +292,7 @@ this.responseText = mockHandler.responseText; } - if ($.isArray(mockHandler.status)) { + if (Array.isArray(mockHandler.status)) { var idxStatus = Math.floor(Math.random() * mockHandler.status.length); this.status = mockHandler.status[idxStatus]; } else if (typeof mockHandler.status === 'number' || typeof mockHandler.status === 'string') { @@ -301,7 +306,7 @@ onReady = this.onload || this.onreadystatechange; // jQuery < 1.4 doesn't have onreadystate change for xhr - if ( $.isFunction( onReady ) ) { + if (typeof onReady === 'function') { if( mockHandler.isTimeout) { this.status = -1; } @@ -314,7 +319,7 @@ // We have an executable function, call it to give // the mock handler a chance to update it's data - if ( $.isFunction(mockHandler.response) ) { + if (typeof mockHandler.response === 'function') { // Wait for it to finish if ( mockHandler.response.length === 2 ) { mockHandler.response(origSettings, function () { @@ -424,7 +429,7 @@ var headers = ''; // since jQuery 1.9 responseText type has to match contentType if (mockHandler.contentType) { - mockHandler.headers['Content-Type'] = mockHandler.contentType; + mockHandler.headers['content-type'] = mockHandler.contentType; } $.each(mockHandler.headers, function(k, v) { headers += k + ': ' + v + '\n'; @@ -490,7 +495,7 @@ newMock = ($.Deferred) ? (new $.Deferred()) : null; // If the response handler on the moock is a function, call it - if ( mockHandler.response && $.isFunction(mockHandler.response) ) { + if ( mockHandler.response && typeof mockHandler.response === 'function' ) { mockHandler.response(origSettings); @@ -540,7 +545,7 @@ if ( newMock ) { try { - json = $.parseJSON( mockHandler.responseText ); + json = JSON.parse( mockHandler.responseText ); } catch (err) { /* just checking... */ } newMock.resolveWith( callbackContext, [json || mockHandler.responseText] ); @@ -636,7 +641,7 @@ overrideCallback = function(action, mockHandler) { var origHandler = origSettings[action.toLowerCase()]; return function() { - if ( $.isFunction(origHandler) ) { + if (typeof origHandler === 'function') { origHandler.apply(this, [].slice.call(arguments)); } mockHandler['onAfter' + action](); @@ -720,13 +725,13 @@ } // Set up onAfter[X] callback functions - if ( $.isFunction( mockHandler.onAfterSuccess ) ) { + if (typeof mockHandler.onAfterSuccess === 'function') { origSettings.success = overrideCallback('Success', mockHandler); } - if ( $.isFunction( mockHandler.onAfterError ) ) { + if (typeof mockHandler.onAfterError === 'function') { origSettings.error = overrideCallback('Error', mockHandler); } - if ( $.isFunction( mockHandler.onAfterComplete ) ) { + if (typeof mockHandler.onAfterComplete === 'function') { origSettings.complete = overrideCallback('Complete', mockHandler); } @@ -930,7 +935,7 @@ */ $.mockjax = function(settings) { // Multiple mocks. - if ( $.isArray(settings) ) { + if (Array.isArray(settings)) { return $.map(settings, function(s) { return $.mockjax(s); }); diff --git a/wicket-core/src/test/js/qunit/qunit.css b/wicket-core/src/test/js/qunit/qunit.css index d445a567b73..d074bb78e5f 100644 --- a/wicket-core/src/test/js/qunit/qunit.css +++ b/wicket-core/src/test/js/qunit/qunit.css @@ -1,5 +1,5 @@ /*! - * QUnit 2.19.4 + * QUnit 2.25.0 * https://qunitjs.com/ * * Copyright OpenJS Foundation and other contributors @@ -45,10 +45,10 @@ @media (min-height: 500px) { #qunit { position: fixed; - left: 0px; - right: 0px; - top: 0px; - bottom: 0px; + left: 0; + right: 0; + top: 0; + bottom: 0; padding: 8px; display: -webkit-box; display: flex; @@ -329,11 +329,11 @@ margin: 0; } -#qunit-tests li strong { +#qunit-tests li .qunit-test-name { cursor: pointer; } -#qunit-tests li.skipped strong { +#qunit-tests li.skipped .qunit-test-name { cursor: default; } diff --git a/wicket-core/src/test/js/qunit/qunit.js b/wicket-core/src/test/js/qunit/qunit.js index 5e48b79303e..058aae0b0d8 100644 --- a/wicket-core/src/test/js/qunit/qunit.js +++ b/wicket-core/src/test/js/qunit/qunit.js @@ -1,5 +1,5 @@ /*! - * QUnit 2.19.4 + * QUnit 2.25.0 * https://qunitjs.com/ * * Copyright OpenJS Foundation and other contributors @@ -9,145 +9,102 @@ (function () { 'use strict'; - function _typeof(obj) { - "@babel/helpers - typeof"; - - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { - return typeof obj; - } : function (obj) { - return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }, _typeof(obj); - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } + function _arrayLikeToArray(r, a) { + (null == a || a > r.length) && (a = r.length); + for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; + return n; } - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { - writable: false - }); - return Constructor; + function _arrayWithHoles(r) { + if (Array.isArray(r)) return r; } - function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); + function _arrayWithoutHoles(r) { + if (Array.isArray(r)) return _arrayLikeToArray(r); } - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + function _classCallCheck(a, n) { + if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); + function _defineProperties(e, r) { + for (var t = 0; t < r.length; t++) { + var o = r[t]; + o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); + } } - function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; + function _createClass(e, r, t) { + return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { + writable: !1 + }), e; } - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); + function _iterableToArray(r) { + if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } - function _iterableToArrayLimit(arr, i) { - var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; - if (_i == null) return; - var _arr = []; - var _n = true; - var _d = false; - var _s, _e; - try { - for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { + function _iterableToArrayLimit(r, l) { + var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; + if (null != t) { + var e, + n, + i, + u, + a = [], + f = !0, + o = !1; try { - if (!_n && _i["return"] != null) _i["return"](); + if (i = (t = t.call(r)).next, 0 === l) { + if (Object(t) !== t) return; + f = !1; + } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); + } catch (r) { + o = !0, n = r; } finally { - if (_d) throw _e; + try { + if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; + } finally { + if (o) throw n; + } } + return a; } - return _arr; } - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + function _slicedToArray(r, e) { + return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } - function _createForOfIteratorHelper(o, allowArrayLike) { - var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; - if (!it) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - var F = function () {}; - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + function _toConsumableArray(r) { + return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); + } + function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || "default"); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); + } + function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; + } + function _typeof(o) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { + return typeof o; + } : function (o) { + return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; + }, _typeof(o); + } + function _unsupportedIterableToArray(r, a) { + if (r) { + if ("string" == typeof r) return _arrayLikeToArray(r, a); + var t = {}.toString.call(r).slice(8, -1); + return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } - var normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = it.call(o); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; } // We don't use global-this-polyfill [1], because it modifies @@ -191,10 +148,15 @@ // This avoids a simple `export const` assignment as that would lead Rollup // to change getGlobalThis and use the same (generated) variable name there. var g = getGlobalThis(); - var window$1 = g.window; + + // These optional globals are undefined in one or more environments: + // modern browser, old browser, Node.js, SpiderMonkey. + // Calling code must check these for truthy-ness before use. var console$1 = g.console; var setTimeout$1 = g.setTimeout; var clearTimeout = g.clearTimeout; + var process$1 = g.process; + var window$1 = g.window; var document = window$1 && window$1.document; var navigator = window$1 && window$1.navigator; var localSessionStorage = function () { @@ -280,53 +242,15 @@ }; }; - // Support: IE 9 - // Detect if the console object exists and no-op otherwise. - // This allows support for IE 9, which doesn't have a console - // object if the developer tools are not open. - - // Support: IE 9 - // Function#bind is supported, but no console.log.bind(). - - // Support: SpiderMonkey (mozjs 68+) - // The console object has a log method, but no warn method. - - var Logger = { - warn: console$1 ? Function.prototype.bind.call(console$1.warn || console$1.log, console$1) : function () {} - }; - var toString = Object.prototype.toString; var hasOwn$1 = Object.prototype.hasOwnProperty; - var nativePerf = getNativePerf(); - - // TODO: Consider using globalThis instead so that perf marks work - // in Node.js as well. As they can have overhead, we should also - // have a way to disable these, and/or make them an opt-in reporter - // in QUnit 3 and then support globalThis. - // For example: `QUnit.addReporter(QUnit.reporters.perf)`. - function getNativePerf() { - if (window$1 && typeof window$1.performance !== 'undefined' && typeof window$1.performance.mark === 'function' && typeof window$1.performance.measure === 'function') { - return window$1.performance; - } else { - return undefined; - } - } var performance = { - now: nativePerf ? nativePerf.now.bind(nativePerf) : Date.now, - measure: nativePerf ? function (comment, startMark, endMark) { - // `performance.measure` may fail if the mark could not be found. - // reasons a specific mark could not be found include: outside code invoking `performance.clearMarks()` - try { - nativePerf.measure(comment, startMark, endMark); - } catch (ex) { - Logger.warn('performance.measure could not be executed because of ', ex.message); - } - } : function () {}, - mark: nativePerf ? nativePerf.mark.bind(nativePerf) : function () {} + // eslint-disable-next-line compat/compat -- Checked + now: window$1 && window$1.performance && window$1.performance.now ? window$1.performance.now.bind(window$1.performance) : Date.now }; // Returns a new Array with the elements that are in a but not in b - function diff(a, b) { + function diff$1(a, b) { return a.filter(function (a) { return b.indexOf(a) === -1; }); @@ -340,9 +264,11 @@ * @param {Array} array * @return {boolean} */ - function inArray(elem, array) { + var inArray = Array.prototype.includes ? function (elem, array) { + return array.includes(elem); + } : function (elem, array) { return array.indexOf(elem) !== -1; - } + }; /** * Recursively clone an object into a plain array or object, taking only the @@ -478,6 +404,27 @@ return resultErrorString; } } + function escapeText(str) { + if (!str) { + return ''; + } + + // Both single quotes and double quotes (for attributes) + return ('' + str).replace(/['"<>&]/g, function (s) { + switch (s) { + case "'": + return '''; + case '"': + return '"'; + case '<': + return '<'; + case '>': + return '>'; + case '&': + return '&'; + } + }); + } var BOXABLE_TYPES = new StringSet(['boolean', 'number', 'string']); @@ -748,14 +695,25 @@ var config = { // HTML Reporter: Modify document.title when suite is done altertitle: true, + // TODO: Move here from /src/core.js in QUnit 3. + // autostart: true, + // HTML Reporter: collapse every test except the first failing test // If false, all failing tests will be expanded collapse: true, + countStepsAsOne: false, + // TODO: Make explicit in QUnit 3. + // current: undefined, + // whether or not to fail when there are zero tests // defaults to `true` failOnZeroTests: true, // Select by pattern or case-insensitive substring match against "moduleName: testName" filter: undefined, + testFilter: null, + // TODO: Make explicit in QUnit 3. + // fixture: undefined, + // Depth up-to which object will be dumped maxDepth: 5, // Select case-insensitive match of the module name @@ -765,13 +723,25 @@ // By default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, + reporters: {}, // When enabled, all tests must call expect() requireExpects: false, // By default, scroll to top of the page when suite is done scrolltop: true, + // TODO: Make explicit in QUnit 3. + // seed: undefined, + // The storage module to use for reordering tests storage: localSessionStorage, testId: undefined, + // The updateRate controls how often QUnit will yield the main thread + // between tests. This is mainly for the benefit of the HTML Reporter, + // so that the browser can visually paint DOM changes with test results. + // This also helps avoid causing browsers to prompt a warning about + // long-running scripts. + // TODO: Move here from /src/core.js in QUnit 3. + // updateRate: 1000, + // HTML Reporter: List of URL parameters that are given visual controls urlConfig: [], // Internal: The first unnamed module @@ -823,7 +793,17 @@ // Internal: Exposed to make resets easier // Ref https://github.com/qunitjs/qunit/pull/1598 globalHooks: {}, + // Internal: ProcessingQueue singleton, created in /src/core.js + pq: null, + // Internal: Created in /src/core.js + // TODO: Move definitions here in QUnit 3.0. + // started: 0, + // Internal state + _event_listeners: Object.create(null), + _event_memory: {}, + _deprecated_timeout_shown: false, + _deprecated_countEachStep_shown: false, blocking: true, callbacks: {}, modules: [], @@ -834,6 +814,67 @@ testCount: 0 } }; + function readFlatPreconfigBoolean(val, dest) { + if (typeof val === 'boolean' || typeof val === 'string' && val !== '') { + config[dest] = val === true || val === 'true'; + } + } + function readFlatPreconfigNumber(val, dest) { + if (typeof val === 'number' || typeof val === 'string' && /^[0-9]+$/.test(val)) { + config[dest] = +val; + } + } + function readFlatPreconfigString(val, dest) { + if (typeof val === 'string' && val !== '') { + config[dest] = val; + } + } + function readFlatPreconfigStringOrBoolean(val, dest) { + if (typeof val === 'boolean' || typeof val === 'string' && val !== '') { + config[dest] = val; + } + } + function readFlatPreconfigStringArray(val, dest) { + if (typeof val === 'string' && val !== '') { + config[dest] = [val]; + } + } + function readFlatPreconfig(obj) { + readFlatPreconfigBoolean(obj.qunit_config_altertitle, 'altertitle'); + readFlatPreconfigBoolean(obj.qunit_config_autostart, 'autostart'); + readFlatPreconfigBoolean(obj.qunit_config_collapse, 'collapse'); + readFlatPreconfigBoolean(obj.qunit_config_failonzerotests, 'failOnZeroTests'); + readFlatPreconfigString(obj.qunit_config_filter, 'filter'); + readFlatPreconfigString(obj.qunit_config_fixture, 'fixture'); + readFlatPreconfigBoolean(obj.qunit_config_hidepassed, 'hidepassed'); + readFlatPreconfigNumber(obj.qunit_config_maxdepth, 'maxDepth'); + readFlatPreconfigString(obj.qunit_config_module, 'module'); + readFlatPreconfigStringArray(obj.qunit_config_moduleid, 'moduleId'); + readFlatPreconfigBoolean(obj.qunit_config_noglobals, 'noglobals'); + readFlatPreconfigBoolean(obj.qunit_config_notrycatch, 'notrycatch'); + readFlatPreconfigBoolean(obj.qunit_config_reorder, 'reorder'); + readFlatPreconfigBoolean(obj.qunit_config_requireexpects, 'requireExpects'); + readFlatPreconfigBoolean(obj.qunit_config_scrolltop, 'scrolltop'); + readFlatPreconfigStringOrBoolean(obj.qunit_config_seed, 'seed'); + readFlatPreconfigStringArray(obj.qunit_config_testid, 'testId'); + readFlatPreconfigNumber(obj.qunit_config_testtimeout, 'testTimeout'); + var reporterKeys = { + qunit_config_reporters_console: 'console', + qunit_config_reporters_tap: 'tap' + }; + for (var key in reporterKeys) { + var val = obj[key]; + // Based on readFlatPreconfigBoolean + if (typeof val === 'boolean' || typeof val === 'string' && val !== '') { + var dest = reporterKeys[key]; + config.reporters[dest] = val === true || val === 'true' || val === '1'; + } + } + } + if (process$1 && 'env' in process$1) { + readFlatPreconfig(process$1.env); + } + readFlatPreconfig(g); // Apply a predefined QUnit.config object // @@ -846,6 +887,12 @@ // Push a loose unnamed module to the modules collection config.modules.push(config.currentModule); + if (config.seed === 'true' || config.seed === true) { + // Generate a random seed + // Length of `Math.random()` fraction, in base 36, may vary from 6-14. + // Pad and take slice to a consistent 10-digit value. + config.seed = (Math.random().toString(36) + '0000000000').slice(2, 12); + } var dump = (function () { function quote(str) { @@ -1089,6 +1136,21 @@ return dump; })(); + // Support: IE 9 + // Detect if the console object exists and no-op otherwise. + // This allows support for IE 9, which doesn't have a console + // object if the developer tools are not open. + + // Support: IE 9 + // Function#bind is supported, but no console.log.bind(). + + // Support: SpiderMonkey (mozjs 68+) + // The console object has a log method, but no warn method. + + var Logger = { + warn: console$1 ? Function.prototype.bind.call(console$1.warn || console$1.log, console$1) : function () {} + }; + var SuiteReport = /*#__PURE__*/function () { function SuiteReport(name, parentSuite) { _classCallCheck(this, SuiteReport); @@ -1105,13 +1167,11 @@ parentSuite.pushChildSuite(this); } } - _createClass(SuiteReport, [{ + return _createClass(SuiteReport, [{ key: "start", value: function start(recordTime) { if (recordTime) { this._startTime = performance.now(); - var suiteLevel = this.fullName.length; - performance.mark("qunit_suite_".concat(suiteLevel, "_start")); } return { name: this.name, @@ -1132,10 +1192,6 @@ value: function end(recordTime) { if (recordTime) { this._endTime = performance.now(); - var suiteLevel = this.fullName.length; - var suiteName = this.fullName.join(' – '); - performance.mark("qunit_suite_".concat(suiteLevel, "_end")); - performance.measure(suiteLevel === 0 ? 'QUnit Test Run' : "QUnit Test Suite: ".concat(suiteName), "qunit_suite_".concat(suiteLevel, "_start"), "qunit_suite_".concat(suiteLevel, "_end")); } return { name: this.name, @@ -1210,7 +1266,6 @@ } } }]); - return SuiteReport; }(); var moduleStack = []; @@ -1284,10 +1339,10 @@ module.hooks[hookName].push(callback); }; } - function processModule(name, options, executeNow) { + function processModule(name, options, scope) { var modifiers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (typeof options === 'function') { - executeNow = options; + scope = options; options = undefined; } var module = createModule(name, options, modifiers); @@ -1307,10 +1362,10 @@ }; var prevModule = config.currentModule; config.currentModule = module; - if (typeof executeNow === 'function') { + if (typeof scope === 'function') { moduleStack.push(module); try { - var cbReturnValue = executeNow.call(module.testEnvironment, moduleFns); + var cbReturnValue = scope.call(module.testEnvironment, moduleFns); if (cbReturnValue && typeof cbReturnValue.then === 'function') { Logger.warn('Returning a promise from a module callback is not supported. ' + 'Instead, use hooks for async behavior. ' + 'This will become an error in QUnit 3.0.'); } @@ -1324,11 +1379,45 @@ } } } + + /** + * Clear the SuiteReport tree of all tests and leave only current module as child suite + * + * This should be called before defining the first module.only() or test.only() + * because otherwise: + * - `runEnd.testCounts` is too high. + * - UI (HtmlReporter) and TAP (TapReporter) display totals too high. + * - Test runners like QTap might timeout because the TAP plan + * would be printed as "1..9" even if only 2 tests are run, + * which means tap-finished will wait for 3-9. + */ + function clearSuiteReports(currentModule) { + var childSuite = null; + var suiteReport = currentModule.suiteReport; + while (suiteReport) { + suiteReport.tests.length = 0; + var i = suiteReport.childSuites.indexOf(childSuite); + if (i === -1) { + suiteReport.childSuites.length = 0; + } else { + // Reduce in-place to just currentModule.suiteReport or its intermediary + suiteReport.childSuites.splice(0, i); + suiteReport.childSuites.splice(1); + } + if (suiteReport === runSuite) { + suiteReport = null; + } else { + childSuite = suiteReport; + currentModule = currentModule.parentModule; + suiteReport = currentModule && currentModule.suiteReport || runSuite; + } + } + } var focused$1 = false; // indicates that the "only" filter was used - function module$1(name, options, executeNow) { + function module$1(name, options, scope) { var ignored = focused$1 && !isParentModuleInQueue(); - processModule(name, options, executeNow, { + processModule(name, options, scope, { ignored: ignored }); } @@ -1338,6 +1427,7 @@ // delete any and all previously registered modules and tests. config.modules.length = 0; config.queue.length = 0; + clearSuiteReports(config.currentModule); // Ignore any tests declared after this block within the same // module parent. https://github.com/qunitjs/qunit/issues/1645 @@ -1346,33 +1436,147 @@ focused$1 = true; processModule.apply(void 0, arguments); }; - module$1.skip = function (name, options, executeNow) { + module$1.skip = function (name, options, scope) { if (focused$1) { return; } - processModule(name, options, executeNow, { + processModule(name, options, scope, { skip: true }); }; - module$1.todo = function (name, options, executeNow) { + module$1.if = function (name, condition, options, scope) { + if (focused$1) { + return; + } + processModule(name, options, scope, { + skip: !condition + }); + }; + module$1.todo = function (name, options, scope) { if (focused$1) { return; } - processModule(name, options, executeNow, { + processModule(name, options, scope, { todo: true }); }; - // Doesn't support IE9, it will return undefined on these browsers - // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack - var fileName = (sourceFromStacktrace(0) || '').replace(/(:\d+)+\)?/, '') - // Remove anything prior to the last slash (Unix/Windows) - // from the last frame - .replace(/.+[/\\]/, ''); + // Stacktrace cleaner to focus on the path from error source to test suite. + // + // This should reduce a raw stack trace like this: + // + // > foo.broken()@/example/foo.js + // > Bar@/example/bar.js + // > @/test/bar.test.js + // > @/lib/qunit.js:500:12 + // > @/lib/qunit.js:100:28 + // > @/lib/qunit.js:200:56 + // > setTimeout@ + // > @/dist/vendor.js + // + // and shorten it to show up until the end of the user's bar.test.js code. + // + // > foo.broken()@/example/foo.js + // > Bar@/example/bar.js + // > @/test/bar.test.js + // + // QUnit will obtain one example trace (once per process/pageload suffices), + // strip off any : and ::, and use that as match needle, + // to the first QUnit-internal frames, and then stop at that point. + // Any later frames, including those that are outside QUnit again, will be ommitted + // as being uninteresting to the test, since QUnit will have either started or + // resumed the test. This we also clean away browser built-ins, or other + // vendor/bundler that may be higher up the stack. + // + // Stripping :: is not for prettyness, it is essential for the + // match needle to work, since this sample trace will by definitin not be the + // same line as e.g. the QUnit.test() call we're trying to identify. + // + // See also: + // - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack + + function qunitFileName() { + var error = new Error(); + if (!error.stack) { + // Copy of sourceFromStacktrace() to avoid circular dependency + // Support: IE 9-11 + try { + throw error; + } catch (err) { + error = err; + } + } + return (error.stack || '' + // Copy of extractStacktrace() to avoid circular dependency + // Support: V8/Chrome + ).replace(/^error$\n/im, '').split('\n')[0] + // Global replace, because a frame like localhost:4000/lib/qunit.js:1234:50, + // would otherwise (harmlessly, but uselessly) remove only the port (first match). + // https://github.com/qunitjs/qunit/issues/1769 + .replace(/(:\d+)+\)?/g, '') + // Remove anything prior to the last slash (Unix/Windows) from the last frame, + // leaving only "qunit.js". + .replace(/.+[/\\]/, ''); + } + var fileName = qunitFileName(); + + /** + * Responsibilities: + * - For internal errors from QUnit itself, remove the first qunit.js frames. + * - For errors in Node.js, format any remaining qunit.js and node:internal + * frames as internal (i.e. grey out). + * + * @param {string} stack Error#stack + * @param {Function} formatInternal Format a string in an "internal" color + * @param {string|null} [eToString] Error#toString() to help remove + * noise from Node.js/V8 stack traces. + */ + function annotateStacktrace(stack, formatInternal) { + var eToString = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + var frames = stack.split('\n'); + var annotated = []; + if (eToString && eToString.indexOf(frames[0]) !== -1) { + // In Firefox and Safari e.stack starts with frame 0, but in V8 (Chrome/Node.js), + // e.stack starts first stringified message. Preserve this separately, + // so that, below, we can distinguish between internal frames on top + // (to remove) vs later internal frames (to format differently). + annotated.push(frames.shift()); + } + var initialInternal = true; + for (var i = 0; i < frames.length; i++) { + var frame = frames[i]; + var isInternal = fileName && frame.indexOf(fileName) !== -1 || + // Support Node 16+: ESM-style + // "at wrap (node:internal/modules/cjs/loader:1)" + frame.indexOf('node:internal/') !== -1 || + // Support Node 12-14 (CJS-style) + // "at load (internal/modules/cjs/loader.js:7)" + frame.match(/^\s+at .+\(internal[^)]*\)$/) || + // Support Node 10 + // "at listOnTimeout (timers.js:263)" + // Avoid matching "(C:)" on Windows + // Avoid matching "(http:)" + frame.match(/^\s+at .+\([a-z]+\.js[:\d]*\)$/); + if (!isInternal) { + initialInternal = false; + } + // Remove initial internal frames entirely. + if (!initialInternal) { + annotated.push(isInternal ? formatInternal(frame) : frame); + } + } + return annotated.join('\n'); + } function extractStacktrace(e, offset) { offset = offset === undefined ? 4 : offset; + + // Support: IE9, e.stack is not supported, we will return undefined if (e && e.stack) { var stack = e.stack.split('\n'); + // In Firefox and Safari, e.stack starts immediately with the first frame. + // + // In V8 (Chrome/Node.js), the stack starts first with a stringified error message, + // and the real stack starting on line 2. if (/^error$/i.test(stack[0])) { stack.shift(); } @@ -1394,8 +1598,9 @@ function sourceFromStacktrace(offset) { var error = new Error(); - // Support: Safari <=7 only, IE <=10 - 11 only - // Not all browsers generate the `stack` property for `new Error()`, see also #636 + // Support: IE 9-11, iOS 7 + // Not all browsers generate the `stack` property for `new Error()` + // See also https://github.com/qunitjs/qunit/issues/636 if (!error.stack) { try { throw error; @@ -1411,7 +1616,7 @@ _classCallCheck(this, Assert); this.test = testContext; } - _createClass(Assert, [{ + return _createClass(Assert, [{ key: "timeout", value: function timeout(duration) { if (typeof duration !== 'number') { @@ -1455,6 +1660,7 @@ // Since the steps array is just string values, we can clone with slice var actualStepsClone = this.test.steps.slice(); this.deepEqual(actualStepsClone, steps, message); + this.test.stepsCount += this.test.steps.length; this.test.steps.length = 0; } }, { @@ -1471,16 +1677,32 @@ }, { key: "async", value: function async(count) { - var requiredCalls = count === undefined ? 1 : count; + if (count === undefined) { + count = 1; + } else if (typeof count !== 'number') { + throw new TypeError('async takes number as an input'); + } + var requiredCalls = count; return this.test.internalStop(requiredCalls); } + }, { + key: "closeTo", + value: function closeTo(actual, expected, delta, message) { + if (typeof delta !== 'number') { + throw new TypeError('closeTo() requires a delta argument'); + } + this.pushResult({ + result: Math.abs(actual - expected) <= delta, + actual: actual, + expected: expected, + message: message || "value should be within ".concat(delta, " inclusive") + }); + } - // Exports test.push() to the user API // Alias of pushResult. }, { key: "push", value: function push(result, actual, expected, message, negative) { - Logger.warn('assert.push is deprecated and will be removed in QUnit 3.0.' + ' Please use assert.pushResult instead (https://api.qunitjs.com/assert/pushResult).'); var currentAssert = this instanceof Assert ? this : config.current.assert; return currentAssert.pushResult({ result: result, @@ -1490,6 +1712,8 @@ negative: negative }); } + + // Public API to internal test.pushResult() }, { key: "pushResult", value: function pushResult(resultInfo) { @@ -1759,7 +1983,6 @@ }); } }]); - return Assert; }(); function validateExpectedExceptionArgs(expected, message, assertionMethod) { var expectedType = objectType(expected); @@ -1831,8 +2054,8 @@ // eslint-disable-next-line dot-notation Assert.prototype.raises = Assert.prototype['throws']; - var LISTENERS = Object.create(null); var SUPPORTED_EVENTS = ['error', 'runStart', 'suiteStart', 'testStart', 'assertion', 'testEnd', 'suiteEnd', 'runEnd']; + var MEMORY_EVENTS = ['error', 'runEnd']; /** * Emits an event with the specified data to all currently registered listeners. @@ -1852,11 +2075,14 @@ } // Clone the callbacks in case one of them registers a new callback - var originalCallbacks = LISTENERS[eventName]; + var originalCallbacks = config._event_listeners[eventName]; var callbacks = originalCallbacks ? _toConsumableArray(originalCallbacks) : []; for (var i = 0; i < callbacks.length; i++) { callbacks[i](data); } + if (inArray(eventName, MEMORY_EVENTS)) { + config._event_memory[eventName] = data; + } } /** @@ -1877,13 +2103,14 @@ } else if (typeof callback !== 'function') { throw new TypeError('callback must be a function when registering a listener'); } - if (!LISTENERS[eventName]) { - LISTENERS[eventName] = []; - } + var listeners = config._event_listeners[eventName] || (config._event_listeners[eventName] = []); // Don't register the same callback more than once - if (!inArray(callback, LISTENERS[eventName])) { - LISTENERS[eventName].push(callback); + if (!inArray(callback, listeners)) { + listeners.push(callback); + if (config._event_memory[eventName] !== undefined) { + callback(config._event_memory[eventName]); + } } } @@ -2185,20 +2412,23 @@ }; // Use polyfill for setImmediate for performance gains - Promise._immediateFn = // @ts-ignore - typeof setImmediate === 'function' && function (fn) { + if (typeof setImmediate === 'function') { // @ts-ignore - setImmediate(fn); - } || function (fn) { - setTimeoutFunc(fn, 0); - }; + var setImmediateFunc = setImmediate; + Promise._immediateFn = function (fn) { + setImmediateFunc(fn); + }; + } else { + Promise._immediateFn = function (fn) { + setTimeoutFunc(fn, 0); + }; + } Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { if (typeof console !== 'undefined' && console) { console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console } }; - promisePolyfill.exports = Promise; })(); var _Promise = promisePolyfill.exports; @@ -2248,248 +2478,44 @@ return promiseChain; } - var priorityCount = 0; - var unitSampler; - - // This is a queue of functions that are tasks within a single test. - // After tests are dequeued from config.queue they are expanded into - // a set of tasks in this queue. - var taskQueue = []; - - /** - * Advances the taskQueue to the next task. If the taskQueue is empty, - * process the testQueue - */ - function advance() { - advanceTaskQueue(); - if (!taskQueue.length && !config.blocking && !config.current) { - advanceTestQueue(); + var TestReport = /*#__PURE__*/function () { + function TestReport(name, suite, options) { + _classCallCheck(this, TestReport); + this.name = name; + this.suiteName = suite.name; + this.fullName = suite.fullName.concat(name); + this.runtime = 0; + this.assertions = []; + this.skipped = !!options.skip; + this.todo = !!options.todo; + this.valid = options.valid; + this._startTime = 0; + this._endTime = 0; + suite.pushTest(this); } - } - - /** - * Advances the taskQueue with an increased depth - */ - function advanceTaskQueue() { - var start = performance.now(); - config.depth = (config.depth || 0) + 1; - processTaskQueue(start); - config.depth--; - } - - /** - * Process the first task on the taskQueue as a promise. - * Each task is a function added by Test#queue() in /src/test.js - */ - function processTaskQueue(start) { - if (taskQueue.length && !config.blocking) { - var elapsedTime = performance.now() - start; - - // The updateRate ensures that a user interface (HTML Reporter) can be updated - // at least once every second. This can also prevent browsers from prompting - // a warning about long running scripts. - if (!setTimeout$1 || config.updateRate <= 0 || elapsedTime < config.updateRate) { - var task = taskQueue.shift(); - _Promise.resolve(task()).then(function () { - if (!taskQueue.length) { - advance(); - } else { - processTaskQueue(start); - } - }); - } else { - setTimeout$1(advance); - } - } - } - - /** - * Advance the testQueue to the next test to process. Call done() if testQueue completes. - */ - function advanceTestQueue() { - if (!config.blocking && !config.queue.length && config.depth === 0) { - done(); - return; - } - var testTasks = config.queue.shift(); - addToTaskQueue(testTasks()); - if (priorityCount > 0) { - priorityCount--; - } - advance(); - } - - /** - * Enqueue the tasks for a test into the task queue. - * @param {Array} tasksArray - */ - function addToTaskQueue(tasksArray) { - taskQueue.push.apply(taskQueue, _toConsumableArray(tasksArray)); - } - - /** - * Return the number of tasks remaining in the task queue to be processed. - * @return {number} - */ - function taskQueueLength() { - return taskQueue.length; - } - - /** - * Adds a test to the TestQueue for execution. - * @param {Function} testTasksFunc - * @param {boolean} prioritize - * @param {string} seed - */ - function addToTestQueue(testTasksFunc, prioritize, seed) { - if (prioritize) { - config.queue.splice(priorityCount++, 0, testTasksFunc); - } else if (seed) { - if (!unitSampler) { - unitSampler = unitSamplerGenerator(seed); - } - - // Insert into a random position after all prioritized items - var index = Math.floor(unitSampler() * (config.queue.length - priorityCount + 1)); - config.queue.splice(priorityCount + index, 0, testTasksFunc); - } else { - config.queue.push(testTasksFunc); - } - } - - /** - * Creates a seeded "sample" generator which is used for randomizing tests. - */ - function unitSamplerGenerator(seed) { - // 32-bit xorshift, requires only a nonzero seed - // https://excamera.com/sphinx/article-xorshift.html - var sample = parseInt(generateHash(seed), 16) || -1; - return function () { - sample ^= sample << 13; - sample ^= sample >>> 17; - sample ^= sample << 5; - - // ECMAScript has no unsigned number type - if (sample < 0) { - sample += 0x100000000; - } - return sample / 0x100000000; - }; - } - - /** - * This function is called when the ProcessingQueue is done processing all - * items. It handles emitting the final run events. - */ - function done() { - // We have reached the end of the processing queue and are about to emit the - // "runEnd" event after which reporters typically stop listening and exit - // the process. First, check if we need to emit one final test. - if (config.stats.testCount === 0 && config.failOnZeroTests === true) { - var error; - if (config.filter && config.filter.length) { - error = new Error("No tests matched the filter \"".concat(config.filter, "\".")); - } else if (config.module && config.module.length) { - error = new Error("No tests matched the module \"".concat(config.module, "\".")); - } else if (config.moduleId && config.moduleId.length) { - error = new Error("No tests matched the moduleId \"".concat(config.moduleId, "\".")); - } else if (config.testId && config.testId.length) { - error = new Error("No tests matched the testId \"".concat(config.testId, "\".")); - } else { - error = new Error('No tests were run.'); - } - test('global failure', extend(function (assert) { - assert.pushResult({ - result: false, - message: error.message, - source: error.stack - }); - }, { - validTest: true - })); - - // We do need to call `advance()` in order to resume the processing queue. - // Once this new test is finished processing, we'll reach `done` again, and - // that time the above condition will evaluate to false. - advance(); - return; - } - var storage = config.storage; - var runtime = Math.round(performance.now() - config.started); - var passed = config.stats.all - config.stats.bad; - ProcessingQueue.finished = true; - emit('runEnd', runSuite.end(true)); - runLoggingCallbacks('done', { - // @deprecated since 2.19.0 Use done() without `details` parameter, - // or use `QUnit.on('runEnd')` instead. Parameter to be replaced in - // QUnit 3.0 with test counts. - passed: passed, - failed: config.stats.bad, - total: config.stats.all, - runtime: runtime - }).then(function () { - // Clear own storage items if all tests passed - if (storage && config.stats.bad === 0) { - for (var i = storage.length - 1; i >= 0; i--) { - var key = storage.key(i); - if (key.indexOf('qunit-test-') === 0) { - storage.removeItem(key); - } - } - } - }); - } - var ProcessingQueue = { - finished: false, - add: addToTestQueue, - advance: advance, - taskCount: taskQueueLength - }; - - var TestReport = /*#__PURE__*/function () { - function TestReport(name, suite, options) { - _classCallCheck(this, TestReport); - this.name = name; - this.suiteName = suite.name; - this.fullName = suite.fullName.concat(name); - this.runtime = 0; - this.assertions = []; - this.skipped = !!options.skip; - this.todo = !!options.todo; - this.valid = options.valid; - this._startTime = 0; - this._endTime = 0; - suite.pushTest(this); - } - _createClass(TestReport, [{ - key: "start", - value: function start(recordTime) { - if (recordTime) { - this._startTime = performance.now(); - performance.mark('qunit_test_start'); - } - return { - name: this.name, - suiteName: this.suiteName, - fullName: this.fullName.slice() - }; - } - }, { - key: "end", - value: function end(recordTime) { - if (recordTime) { - this._endTime = performance.now(); - if (performance) { - performance.mark('qunit_test_end'); - var testName = this.fullName.join(' – '); - performance.measure("QUnit Test: ".concat(testName), 'qunit_test_start', 'qunit_test_end'); - } - } - return extend(this.start(), { - runtime: this.getRuntime(), - status: this.getStatus(), - errors: this.getFailedAssertions(), - assertions: this.getAssertions() + return _createClass(TestReport, [{ + key: "start", + value: function start(recordTime) { + if (recordTime) { + this._startTime = performance.now(); + } + return { + name: this.name, + suiteName: this.suiteName, + fullName: this.fullName.slice() + }; + } + }, { + key: "end", + value: function end(recordTime) { + if (recordTime) { + this._endTime = performance.now(); + } + return extend(this.start(), { + runtime: this.getRuntime(), + status: this.getStatus(), + errors: this.getFailedAssertions(), + assertions: this.getAssertions() }); } }, { @@ -2542,7 +2568,6 @@ }); } }]); - return TestReport; }(); function Test(settings) { @@ -2550,6 +2575,9 @@ this.assertions = []; this.module = config.currentModule; this.steps = []; + // This powers the QUnit.config.countStepsAsOne feature. + // https://github.com/qunitjs/qunit/pull/1775 + this.stepsCount = 0; this.timeout = undefined; this.data = undefined; this.withData = false; @@ -2585,7 +2613,7 @@ // Queuing a late test after the run has ended is not allowed. // This was once supported for internal use by QUnit.onError(). // Ref https://github.com/qunitjs/qunit/issues/1377 - if (ProcessingQueue.finished) { + if (config.pq.finished) { // Using this for anything other than onError(), such as testing in QUnit.done(), // is unstable and will likely result in the added tests being ignored by CI. // (Meaning the CI passes irregardless of the added tests). @@ -2632,7 +2660,7 @@ skip: !!this.skip }); if (this.skip) { - // Skipped tests will fully ignore any sent callback + // Skipped tests will fully ignore (and dereference for garbage collect) any sent callback this.callback = function () {}; this.async = false; this.expected = 0; @@ -2771,7 +2799,7 @@ // The 'after' hook should only execute when there are not tests left and // when the 'after' and 'finish' tasks are the only tasks left to process - if (hookName === 'after' && !lastTestWithinModuleExecuted(hookOwner) && (config.queue.length > 0 || ProcessingQueue.taskCount() > 2)) { + if (hookName === 'after' && !lastTestWithinModuleExecuted(hookOwner) && (config.queue.length > 0 || config.pq.taskCount() > 2)) { return; } config.current = _this3; @@ -2839,11 +2867,24 @@ var stepsList = this.steps.join(', '); this.pushFailure('Expected assert.verifySteps() to be called before end of test ' + "after using assert.step(). Unverified steps: ".concat(stepsList), this.stack); } + if (!config._deprecated_countEachStep_shown && !config.countStepsAsOne && this.expected !== null && this.stepsCount) { + config._deprecated_countEachStep_shown = true; + if (config.requireExpects) { + Logger.warn('Counting each assert.step() for assert.expect() is changing in QUnit 3.0. You can enable QUnit.config.countStepsAsOne to prepare for the upgrade. https://qunitjs.com/api/assert/expect/'); + } else { + Logger.warn('Counting each assert.step() for assert.expect() is changing in QUnit 3.0. Omit assert.expect() from tests that use assert.step(), or enable QUnit.config.countStepsAsOne to prepare for the upgrade. https://qunitjs.com/api/assert/expect/'); + } + } + var actualCountForExpect = config.countStepsAsOne ? this.assertions.length - this.stepsCount : this.assertions.length; if (config.requireExpects && this.expected === null) { this.pushFailure('Expected number of assertions to be defined, but expect() was ' + 'not called.', this.stack); - } else if (this.expected !== null && this.expected !== this.assertions.length) { - this.pushFailure('Expected ' + this.expected + ' assertions, but ' + this.assertions.length + ' were run', this.stack); - } else if (this.expected === null && !this.assertions.length) { + } else if (this.expected !== null && this.expected !== actualCountForExpect && this.stepsCount && this.expected === this.assertions.length - this.stepsCount && !config.countStepsAsOne) { + this.pushFailure('Expected ' + this.expected + ' assertions, but ' + actualCountForExpect + ' were run\nIt looks like you might prefer to enable QUnit.config.countStepsAsOne, which will become the default in QUnit 3.0. https://qunitjs.com/api/assert/expect/', this.stack); + } else if (this.expected !== null && this.expected !== actualCountForExpect && this.stepsCount && this.expected === this.assertions.length && config.countStepsAsOne) { + this.pushFailure('Expected ' + this.expected + ' assertions, but ' + actualCountForExpect + ' were run\nRemember that with QUnit.config.countStepsAsOne and in QUnit 3.0, steps no longer count as separate assertions. https://qunitjs.com/api/assert/expect/', this.stack); + } else if (this.expected !== null && this.expected !== actualCountForExpect) { + this.pushFailure('Expected ' + this.expected + ' assertions, but ' + actualCountForExpect + ' were run', this.stack); + } else if (this.expected === null && !actualCountForExpect) { this.pushFailure('Expected at least one assertion, but none were run - call ' + 'expect(0) to accept zero assertions.', this.stack); } var module = this.module; @@ -2988,7 +3029,7 @@ // Prioritize previously failed tests, detected from storage var prioritize = config.reorder && !!previousFailCount; this.previousFailure = !!previousFailCount; - ProcessingQueue.add(runTest, prioritize, config.seed); + config.pq.add(runTest, prioritize); }, pushResult: function pushResult(resultInfo) { if (this !== config.current) { @@ -3025,14 +3066,13 @@ message: resultInfo.message }); }, - pushFailure: function pushFailure(message, source, actual) { + pushFailure: function pushFailure(message, source) { if (!(this instanceof Test)) { throw new Error('pushFailure() assertion outside test context, was ' + sourceFromStacktrace(2)); } this.pushResult({ result: false, message: message || 'error', - actual: actual || null, source: source }); }, @@ -3170,11 +3210,20 @@ pause.cancelled = true; test.pauses.delete(pauseId); test.pushFailure("Test took longer than ".concat(timeout, "ms; test timed out."), sourceFromStacktrace(2)); - internalStart(test); + internalRecover(test); }; }; clearTimeout(config.timeout); config.timeout = setTimeout$1(config.timeoutHandler(timeoutDuration), timeoutDuration); + } else { + clearTimeout(config.timeout); + config.timeout = setTimeout$1(function () { + config.timeout = null; + if (!config._deprecated_timeout_shown) { + config._deprecated_timeout_shown = true; + Logger.warn("Test \"".concat(test.testName, "\" took longer than 3000ms, but no timeout was set. Set QUnit.config.testTimeout or call assert.timeout() to avoid a timeout in QUnit 3. https://qunitjs.com/api/config/testTimeout/")); + } + }, 3000); } } return release; @@ -3242,12 +3291,32 @@ return false; } var filter = config.filter; - if (!filter) { - return true; + if (filter) { + var regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter); + var fullName = this.module.name + ': ' + this.testName; + if (regexFilter) { + if (!this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName)) { + return false; + } + } else if (!this.stringFilter(filter, fullName)) { + return false; + } + } + if (typeof config.testFilter === 'function') { + var testInfo = { + testId: this.testId, + testName: this.testName, + module: this.module.name, + skip: !!this.skip + }; + try { + return !!config.testFilter(testInfo); + } catch (error) { + Logger.warn('Error in QUnit.config.testFilter callback: ', error); + return false; + } } - var regexFilter = /^(!?)\/([\w\W]*)\/(i?$)/.exec(filter); - var fullName = this.module.name + ': ' + this.testName; - return regexFilter ? this.regexFilter(!!regexFilter[1], regexFilter[2], regexFilter[3], fullName) : this.stringFilter(filter, fullName); + return true; }, regexFilter: function regexFilter(exclude, pattern, flags, fullName) { var regex = new RegExp(pattern, flags); @@ -3297,11 +3366,11 @@ function checkPollution() { var old = config.pollution; saveGlobal(); - var newGlobals = diff(config.pollution, old); + var newGlobals = diff$1(config.pollution, old); if (newGlobals.length > 0) { pushFailure('Introduced global variable(s): ' + newGlobals.join(', ')); } - var deletedGlobals = diff(old, config.pollution); + var deletedGlobals = diff$1(old, config.pollution); if (deletedGlobals.length > 0) { pushFailure('Deleted global variable(s): ' + deletedGlobals.join(', ')); } @@ -3321,6 +3390,7 @@ } if (!focused) { config.queue.length = 0; + clearSuiteReports(config.currentModule); focused = true; } var newTest = new Test(settings); @@ -3337,10 +3407,54 @@ function makeEachTestName(testName, argument) { return "".concat(testName, " [").concat(argument, "]"); } + + // Characters to avoid in test names especially CLI/AP output: + // * x00-1F: e.g. NULL, backspace (\b), line breaks (\r\n), ESC. + // * x74: DEL. + // * xA0: non-breaking space. + // + // See https://en.wikipedia.org/wiki/ASCII#Character_order + // + // eslint-disable-next-line no-control-regex + var rNonObviousStr = /[\x00-\x1F\x7F\xA0]/; function runEach(data, eachFn) { if (Array.isArray(data)) { for (var i = 0; i < data.length; i++) { - eachFn(data[i], i); + var value = data[i]; + + // Create automatic labels for primitive data in arrays passed to test.each(). + // We want to avoid the default "example [0], example [1]" where possible since + // these are not self-explanatory in results, and are also tedious to locate + // the source of since the numerical key of an array isn't literally in the + // code (you have to count). + // + // Design requirements: + // * Unique. Each label must be unique and correspond 1:1 with a data value. + // This way each test name will hash to a unique testId with Rerun link, + // without having to rely on Test class enforcing uniqueness with invisible + // space hack. + // * Unambigious. While technical uniqueness is a hard requirement above, + // we also want the labels to be obvious and unambiguous to humans. + // For example, abbrebating "foobar" and "foobaz" to "f" and "fo" is + // technically unique, but ambigious to humans which one is which. + // * Short and readable. Where possible we omit the array index numbers + // so that in most cases, the value is simply shown as-is. + // We prefer "example [foo], example [bar]" + // over "example [0: foo], example [2: bar]". + // This also has the benefit of being stable and robust against e.g. + // re-ordering data or adding new items during development, without + // invalidating a previous filter or rerun link immediately. + var valueType = _typeof(value); + var testKey = i; + if (valueType === 'string' && value.length <= 40 && !rNonObviousStr.test(value) && !/\s*\d+: /.test(value)) { + testKey = value; + } else if (valueType === 'string' || valueType === 'number' || valueType === 'boolean' || valueType === 'undefined' || value === null) { + var valueForName = String(value); + if (!rNonObviousStr.test(valueForName)) { + testKey = i + ': ' + (valueForName.length <= 30 ? valueForName : valueForName.slice(0, 29) + '…'); + } + } + eachFn(value, testKey); } } else if (_typeof(data) === 'object' && data !== null) { for (var key in data) { @@ -3364,6 +3478,13 @@ skip: true }); }, + if: function _if(testName, condition, callback) { + addTest({ + testName: testName, + callback: callback, + skip: !condition + }); + }, only: function only(testName, callback) { addOnlyTest({ testName: testName, @@ -3403,6 +3524,18 @@ }); }); }; + test.if.each = function (testName, condition, dataset, callback) { + runEach(dataset, function (data, testKey) { + addTest({ + testName: makeEachTestName(testName, testKey), + callback: callback, + withData: true, + stackOffset: 5, + skip: !condition, + data: condition ? data : undefined + }); + }); + }; test.only.each = function (testName, dataset, callback) { runEach(dataset, function (data, testKey) { addOnlyTest({ @@ -3441,11 +3574,11 @@ clearTimeout(config.timeout); config.timeout = null; config.blocking = false; - ProcessingQueue.advance(); + config.pq.advance(); }); } else { config.blocking = false; - ProcessingQueue.advance(); + config.pq.advance(); } } function collectTests(module) { @@ -3549,7 +3682,7 @@ runner.on('testEnd', this.onTestEnd.bind(this)); runner.on('runEnd', this.onRunEnd.bind(this)); } - _createClass(ConsoleReporter, [{ + return _createClass(ConsoleReporter, [{ key: "onError", value: function onError(error) { this.log('error', error); @@ -3580,7 +3713,88 @@ return new ConsoleReporter(runner, options); } }]); - return ConsoleReporter; + }(); + + // TODO: Consider using globalThis instead of window, so that the reporter + // works for Node.js as well. As this can add overhead, we should make + // this opt-in before we enable it for CLI. + // + // QUnit 3 will switch from `window` to `globalThis` and then make it + // no longer an implicit feature of the HTML Reporter, but rather let + // it be opt-in via `QUnit.config.reporters = ['perf']` or something + // like that. + var nativePerf = window$1 && typeof window$1.performance !== 'undefined' && + // eslint-disable-next-line compat/compat -- Checked + typeof window$1.performance.mark === 'function' && + // eslint-disable-next-line compat/compat -- Checked + typeof window$1.performance.measure === 'function' ? window$1.performance : undefined; + var perf = { + measure: nativePerf ? function (comment, startMark, endMark) { + // `performance.measure` may fail if the mark could not be found. + // reasons a specific mark could not be found include: outside code invoking `performance.clearMarks()` + try { + nativePerf.measure(comment, startMark, endMark); + } catch (ex) { + Logger.warn('performance.measure could not be executed because of ', ex.message); + } + } : function () {}, + mark: nativePerf ? nativePerf.mark.bind(nativePerf) : function () {} + }; + var PerfReporter = /*#__PURE__*/function () { + function PerfReporter(runner) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, PerfReporter); + this.perf = options.perf || perf; + runner.on('runStart', this.onRunStart.bind(this)); + runner.on('runEnd', this.onRunEnd.bind(this)); + runner.on('suiteStart', this.onSuiteStart.bind(this)); + runner.on('suiteEnd', this.onSuiteEnd.bind(this)); + runner.on('testStart', this.onTestStart.bind(this)); + runner.on('testEnd', this.onTestEnd.bind(this)); + } + return _createClass(PerfReporter, [{ + key: "onRunStart", + value: function onRunStart() { + this.perf.mark('qunit_suite_0_start'); + } + }, { + key: "onSuiteStart", + value: function onSuiteStart(suiteStart) { + var suiteLevel = suiteStart.fullName.length; + this.perf.mark("qunit_suite_".concat(suiteLevel, "_start")); + } + }, { + key: "onSuiteEnd", + value: function onSuiteEnd(suiteEnd) { + var suiteLevel = suiteEnd.fullName.length; + var suiteName = suiteEnd.fullName.join(' – '); + this.perf.mark("qunit_suite_".concat(suiteLevel, "_end")); + this.perf.measure("QUnit Test Suite: ".concat(suiteName), "qunit_suite_".concat(suiteLevel, "_start"), "qunit_suite_".concat(suiteLevel, "_end")); + } + }, { + key: "onTestStart", + value: function onTestStart() { + this.perf.mark('qunit_test_start'); + } + }, { + key: "onTestEnd", + value: function onTestEnd(testEnd) { + this.perf.mark('qunit_test_end'); + var testName = testEnd.fullName.join(' – '); + this.perf.measure("QUnit Test: ".concat(testName), 'qunit_test_start', 'qunit_test_end'); + } + }, { + key: "onRunEnd", + value: function onRunEnd() { + this.perf.mark('qunit_suite_0_end'); + this.perf.measure('QUnit Test Run', 'qunit_suite_0_start', 'qunit_suite_0_end'); + } + }], [{ + key: "init", + value: function init(runner, options) { + return new PerfReporter(runner, options); + } + }]); }(); var FORCE_COLOR, @@ -3691,8 +3905,6 @@ }; } - var hasOwn = Object.prototype.hasOwnProperty; - /** * Format a given value into YAML. * @@ -3726,7 +3938,7 @@ * "[Circular]" as they cannot otherwise be represented. */ function prettyYamlValue(value) { - var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4; + var indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; if (value === undefined) { // Not supported in JSON/YAML, turn into string // and let the below output it as bare string. @@ -3750,7 +3962,10 @@ // cause data loss or invalid YAML syntax. // // - Quotes, escapes, line breaks, or JSON-like stuff. - var rSpecialJson = /['"\\/[{}\]\r\n]/; + // - Not allowed in YAML unquoted strings per https://yaml.org/spec/1.2.2/#733-plain-style + // * ": " (colon followed by space) + // * " #" (space followed by hash) + var rSpecialJson = /['"\\/[{}\]\r\n|:#]/; // - Characters that are special at the start of a YAML value var rSpecialYaml = /[-?:,[\]{}#&*!|=>'"%@`]/; @@ -3776,7 +3991,7 @@ // See also // Support IE 9-11: Avoid ES6 String#repeat - var prefix = new Array(indent + 1).join(' '); + var _prefix = new Array(indent * 2 + 1).join(' '); var trailingLinebreakMatch = value.match(/\n+$/); var trailingLinebreaks = trailingLinebreakMatch ? trailingLinebreakMatch[0].length : 0; if (trailingLinebreaks === 1) { @@ -3787,14 +4002,14 @@ // Ignore the last new line, since we'll get that one for free // with the straight-forward Block syntax. .replace(/\n$/, '').split('\n').map(function (line) { - return prefix + line; + return _prefix + line; }); return '|\n' + lines.join('\n'); } else { // This has either no trailing new lines, or more than 1. // Use |+ so that YAML parsers will preserve it exactly. var _lines = value.split('\n').map(function (line) { - return prefix + line; + return _prefix + line; }); return '|+\n' + _lines.join('\n'); } @@ -3803,9 +4018,12 @@ return value; } } + var prefix = new Array(indent + 1).join(' '); // Handle null, boolean, array, and object - return JSON.stringify(decycledShallowClone(value), null, 2); + return JSON.stringify(decycledShallowClone(value), null, 2).split('\n').map(function (line, i) { + return i === 0 ? line : prefix + line; + }).join('\n'); } /** @@ -3850,6 +4068,7 @@ // Support IE 9: Function#bind is supported, but no console.log.bind(). this.log = options.log || Function.prototype.bind.call(console$1.log, console$1); this.testCount = 0; + this.started = false; this.ended = false; this.bailed = false; runner.on('error', this.onError.bind(this)); @@ -3857,10 +4076,13 @@ runner.on('testEnd', this.onTestEnd.bind(this)); runner.on('runEnd', this.onRunEnd.bind(this)); } - _createClass(TapReporter, [{ + return _createClass(TapReporter, [{ key: "onRunStart", value: function onRunStart(_runSuite) { - this.log('TAP version 13'); + if (!this.started) { + this.log('TAP version 13'); + this.started = true; + } } }, { key: "onError", @@ -3873,8 +4095,9 @@ // Imitate onTestEnd // Skip this if we're past "runEnd" as it would look odd if (!this.ended) { + this.onRunStart(); this.testCount = this.testCount + 1; - this.log($.red("not ok ".concat(this.testCount, " global failure"))); + this.log("not ok ".concat(this.testCount, " ").concat($.red('global failure'))); this.logError(error); } this.log('Bail out! ' + errorString(error).split('\n')[0]); @@ -3890,14 +4113,14 @@ if (test.status === 'passed') { this.log("ok ".concat(this.testCount, " ").concat(test.fullName.join(' > '))); } else if (test.status === 'skipped') { - this.log($.yellow("ok ".concat(this.testCount, " # SKIP ").concat(test.fullName.join(' > ')))); + this.log("ok ".concat(this.testCount, " ").concat($.yellow(test.fullName.join(' > ')), " # SKIP")); } else if (test.status === 'todo') { - this.log($.cyan("not ok ".concat(this.testCount, " # TODO ").concat(test.fullName.join(' > ')))); + this.log("not ok ".concat(this.testCount, " ").concat($.cyan(test.fullName.join(' > ')), " # TODO")); test.errors.forEach(function (error) { return _this.logAssertion(error, 'todo'); }); } else { - this.log($.red("not ok ".concat(this.testCount, " ").concat(test.fullName.join(' > ')))); + this.log("not ok ".concat(this.testCount, " ").concat($.red(test.fullName.join(' > ')))); test.errors.forEach(function (error) { return _this.logAssertion(error); }); @@ -3905,13 +4128,13 @@ } }, { key: "onRunEnd", - value: function onRunEnd(runSuite) { + value: function onRunEnd(runEnd) { this.ended = true; - this.log("1..".concat(runSuite.testCounts.total)); - this.log("# pass ".concat(runSuite.testCounts.passed)); - this.log($.yellow("# skip ".concat(runSuite.testCounts.skipped))); - this.log($.cyan("# todo ".concat(runSuite.testCounts.todo))); - this.log($.red("# fail ".concat(runSuite.testCounts.failed))); + this.log("1..".concat(runEnd.testCounts.total)); + this.log("# pass ".concat(runEnd.testCounts.passed)); + this.log("# ".concat($.yellow("skip ".concat(runEnd.testCounts.skipped)))); + this.log("# ".concat($.cyan("todo ".concat(runEnd.testCounts.todo)))); + this.log("# ".concat($.red("fail ".concat(runEnd.testCounts.failed)))); } }, { key: "logAssertion", @@ -3919,16 +4142,22 @@ var out = ' ---'; out += "\n message: ".concat(prettyYamlValue(error.message || 'failed')); out += "\n severity: ".concat(prettyYamlValue(severity || 'failed')); - if (hasOwn.call(error, 'actual')) { + + // When pushFailure() is used, actual/expected are initially unset but + // eventually in Test#logAssertion, for testReport#pushAssertion, these are + // forged into existence as undefined. + var hasAny = error.expected !== undefined || error.actual !== undefined; + if (hasAny) { out += "\n actual : ".concat(prettyYamlValue(error.actual)); - } - if (hasOwn.call(error, 'expected')) { out += "\n expected: ".concat(prettyYamlValue(error.expected)); } if (error.stack) { // Since stacks aren't user generated, take a bit of liberty by // adding a trailing new line to allow a straight-forward YAML Blocks. - out += "\n stack: ".concat(prettyYamlValue(error.stack + '\n')); + var fmtStack = annotateStacktrace(error.stack, $.grey); + if (fmtStack.length) { + out += "\n stack: ".concat(prettyYamlValue(fmtStack + '\n')); + } } out += '\n ...'; this.log(out); @@ -3940,7 +4169,10 @@ out += "\n message: ".concat(prettyYamlValue(errorString(error))); out += "\n severity: ".concat(prettyYamlValue('failed')); if (error && error.stack) { - out += "\n stack: ".concat(prettyYamlValue(error.stack + '\n')); + var fmtStack = annotateStacktrace(error.stack, $.grey, error.toString()); + if (fmtStack.length) { + out += "\n stack: ".concat(prettyYamlValue(fmtStack + '\n')); + } } out += '\n ...'; this.log(out); @@ -3951,11 +4183,11 @@ return new TapReporter(runner, options); } }]); - return TapReporter; }(); var reporters = { console: ConsoleReporter, + perf: PerfReporter, tap: TapReporter }; @@ -3973,3041 +4205,3257 @@ }; /** - * Handle a global error that should result in a failed test run. - * - * Summary: - * - * - If we're strictly inside a test (or one if its module hooks), the exception - * becomes a failed assertion. - * - * This has the important side-effect that uncaught exceptions (such as - * calling an undefined function) during a "todo" test do NOT result in - * a failed test run. - * - * - If we're anywhere outside a test (be it in early event callbacks, or - * internally between tests, or somewhere after "runEnd" if the process is - * still alive for some reason), then send an "error" event to the reporters. - * - * @since 2.17.0 - * @param {Error|any} error + * Creates a seeded "sample" generator which is used for randomizing tests. */ - function onUncaughtException(error) { - if (config.current) { - config.current.assert.pushResult({ - result: false, - message: "global failure: ".concat(errorString(error)), - // We could let callers specify an offset to subtract a number of frames via - // sourceFromStacktrace, in case they are a wrapper further away from the error - // handler, and thus reduce some noise in the stack trace. However, we're not - // doing this right now because it would almost never be used in practice given - // the vast majority of error values will be Error objects, and thus have their - // own stack trace already. - source: error && error.stack || sourceFromStacktrace(2) - }); - } else { - // The "error" event was added in QUnit 2.17. - // Increase "bad assertion" stats despite no longer pushing an assertion in this case. - // This ensures "runEnd" and "QUnit.done()" handlers behave as expected, since the "bad" - // count is typically how reporters decide on the boolean outcome of the test run. - runSuite.globalFailureCount++; - config.stats.bad++; - config.stats.all++; - emit('error', error); - } + function unitSamplerGenerator(seed) { + // 32-bit xorshift, requires only a nonzero seed + // https://excamera.com/sphinx/article-xorshift.html + var sample = parseInt(generateHash(seed), 16) || -1; + return function () { + sample ^= sample << 13; + sample ^= sample >>> 17; + sample ^= sample << 5; + + // ECMAScript has no unsigned number type + if (sample < 0) { + sample += 0x100000000; + } + return sample / 0x100000000; + }; } + var ProcessingQueue = /*#__PURE__*/function () { + /** + * @param {Function} test Reference to the QUnit.test() method + */ + function ProcessingQueue(test) { + _classCallCheck(this, ProcessingQueue); + this.test = test; + this.priorityCount = 0; + this.unitSampler = null; - /** - * Handle a window.onerror error. - * - * If there is a current test that sets the internal `ignoreGlobalErrors` field - * (such as during `assert.throws()`), then the error is ignored and native - * error reporting is suppressed as well. This is because in browsers, an error - * can sometimes end up in `window.onerror` instead of in the local try/catch. - * This ignoring of errors does not apply to our general onUncaughtException - * method, nor to our `unhandledRejection` handlers, as those are not meant - * to receive an "expected" error during `assert.throws()`. - * - * @see - * @deprecated since 2.17.0 Use QUnit.onUncaughtException instead. - * @param {Object} details - * @param {string} details.message - * @param {string} details.fileName - * @param {number} details.lineNumber - * @param {string|undefined} [details.stacktrace] - * @return {bool} True if native error reporting should be suppressed. - */ - function onWindowError(details) { - Logger.warn('QUnit.onError is deprecated and will be removed in QUnit 3.0.' + ' Please use QUnit.onUncaughtException instead.'); - if (config.current && config.current.ignoreGlobalErrors) { - return true; + // This is a queue of functions that are tasks within a single test. + // After tests are dequeued from config.queue they are expanded into + // a set of tasks in this queue. + this.taskQueue = []; + this.finished = false; } - var err = new Error(details.message); - err.stack = details.stacktrace || details.fileName + ':' + details.lineNumber; - onUncaughtException(err); - return false; - } - - var QUnit = {}; - - // The "currentModule" object would ideally be defined using the createModule() - // function. Since it isn't, add the missing suiteReport property to it now that - // we have loaded all source code required to do so. - // - // TODO: Consider defining currentModule in core.js or module.js in its entirely - // rather than partly in config.js and partly here. - config.currentModule.suiteReport = runSuite; - var globalStartCalled = false; - var runStarted = false; - // Figure out if we're running the tests from a server or not - QUnit.isLocal = window$1 && window$1.location && window$1.location.protocol === 'file:'; + /** + * Advances the taskQueue to the next task. If the taskQueue is empty, + * process the testQueue + */ + return _createClass(ProcessingQueue, [{ + key: "advance", + value: function advance() { + this.advanceTaskQueue(); + if (!this.taskQueue.length && !config.blocking && !config.current) { + this.advanceTestQueue(); + } + } - // Expose the current QUnit version - QUnit.version = '2.19.4'; - extend(QUnit, { - config: config, - dump: dump, - equiv: equiv, - reporters: reporters, - hooks: hooks, - is: is, - objectType: objectType, - on: on, - onError: onWindowError, - onUncaughtException: onUncaughtException, - pushFailure: pushFailure, - assert: Assert.prototype, - module: module$1, - test: test, - // alias other test flavors for easy access - todo: test.todo, - skip: test.skip, - only: test.only, - start: function start(count) { - if (config.current) { - throw new Error('QUnit.start cannot be called inside a test context.'); + /** + * Advances the taskQueue with an increased depth + */ + }, { + key: "advanceTaskQueue", + value: function advanceTaskQueue() { + var start = performance.now(); + config.depth = (config.depth || 0) + 1; + this.processTaskQueue(start); + config.depth--; } - var globalStartAlreadyCalled = globalStartCalled; - globalStartCalled = true; - if (runStarted) { - throw new Error('Called start() while test already started running'); + + /** + * Process the first task on the taskQueue as a promise. + * Each task is a function added by Test#queue() in /src/test.js + */ + }, { + key: "processTaskQueue", + value: function processTaskQueue(start) { + var _this = this; + if (this.taskQueue.length && !config.blocking) { + var elapsedTime = performance.now() - start; + if (!setTimeout$1 || config.updateRate <= 0 || elapsedTime < config.updateRate) { + var task = this.taskQueue.shift(); + _Promise.resolve(task()).then(function () { + if (!_this.taskQueue.length) { + _this.advance(); + } else { + _this.processTaskQueue(start); + } + }); + } else { + setTimeout$1(function () { + _this.advance(); + }); + } + } } - if (globalStartAlreadyCalled || count > 1) { - throw new Error('Called start() outside of a test context too many times'); + + /** + * Advance the testQueue to the next test to process. Call done() if testQueue completes. + */ + }, { + key: "advanceTestQueue", + value: function advanceTestQueue() { + if (!config.blocking && !config.queue.length && config.depth === 0) { + this.done(); + return; + } + var testTasks = config.queue.shift(); + this.addToTaskQueue(testTasks()); + if (this.priorityCount > 0) { + this.priorityCount--; + } + this.advance(); } - if (config.autostart) { - throw new Error('Called start() outside of a test context when ' + 'QUnit.config.autostart was true'); + + /** + * Enqueue the tasks for a test into the task queue. + * @param {Array} tasksArray + */ + }, { + key: "addToTaskQueue", + value: function addToTaskQueue(tasksArray) { + var _this$taskQueue; + (_this$taskQueue = this.taskQueue).push.apply(_this$taskQueue, _toConsumableArray(tasksArray)); } - if (!config.pageLoaded) { - // The page isn't completely loaded yet, so we set autostart and then - // load if we're in Node or wait for the browser's load event. - config.autostart = true; - // Starts from Node even if .load was not previously called. We still return - // early otherwise we'll wind up "beginning" twice. - if (!document) { - QUnit.load(); - } - return; + /** + * Return the number of tasks remaining in the task queue to be processed. + * @return {number} + */ + }, { + key: "taskCount", + value: function taskCount() { + return this.taskQueue.length; } - scheduleBegin(); - }, - onUnhandledRejection: function onUnhandledRejection(reason) { - Logger.warn('QUnit.onUnhandledRejection is deprecated and will be removed in QUnit 3.0.' + ' Please use QUnit.onUncaughtException instead.'); - onUncaughtException(reason); - }, - extend: function extend$1() { - Logger.warn('QUnit.extend is deprecated and will be removed in QUnit 3.0.' + ' Please use Object.assign instead.'); - // delegate to utility implementation, which does not warn and can be used elsewhere internally - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + /** + * Adds a test to the TestQueue for execution. + * @param {Function} testTasksFunc + * @param {boolean} prioritize + */ + }, { + key: "add", + value: function add(testTasksFunc, prioritize) { + if (prioritize) { + config.queue.splice(this.priorityCount++, 0, testTasksFunc); + } else if (config.seed) { + if (!this.unitSampler) { + this.unitSampler = unitSamplerGenerator(config.seed); + } + + // Insert into a random position after all prioritized items + var index = Math.floor(this.unitSampler() * (config.queue.length - this.priorityCount + 1)); + config.queue.splice(this.priorityCount + index, 0, testTasksFunc); + } else { + config.queue.push(testTasksFunc); + } } - return extend.apply(this, args); - }, - load: function load() { - config.pageLoaded = true; - // Initialize the configuration options - extend(config, { - started: 0, - updateRate: 1000, - autostart: true, - filter: '' - }, true); - if (!runStarted) { - config.blocking = false; - if (config.autostart) { - scheduleBegin(); + /** + * This function is called when the ProcessingQueue is done processing all + * items. It handles emitting the final run events. + */ + }, { + key: "done", + value: function done() { + // We have reached the end of the processing queue and are about to emit the + // "runEnd" event after which reporters typically stop listening and exit + // the process. First, check if we need to emit one final test. + if (config.stats.testCount === 0 && config.failOnZeroTests === true) { + var error; + if (config.filter && config.filter.length) { + error = new Error("No tests matched the filter \"".concat(config.filter, "\".")); + } else if (config.module && config.module.length) { + error = new Error("No tests matched the module \"".concat(config.module, "\".")); + } else if (config.moduleId && config.moduleId.length) { + error = new Error("No tests matched the moduleId \"".concat(config.moduleId, "\".")); + } else if (config.testId && config.testId.length) { + error = new Error("No tests matched the testId \"".concat(config.testId, "\".")); + } else { + error = new Error('No tests were run.'); + } + this.test('global failure', extend(function (assert) { + assert.pushResult({ + result: false, + message: error.message, + source: error.stack + }); + }, { + validTest: true + })); + + // We do need to call `advance()` in order to resume the processing queue. + // Once this new test is finished processing, we'll reach `done` again, and + // that time the above condition will evaluate to false. + this.advance(); + return; } + var storage = config.storage; + var runtime = Math.round(performance.now() - config.started); + var passed = config.stats.all - config.stats.bad; + this.finished = true; + emit('runEnd', runSuite.end(true)); + runLoggingCallbacks('done', { + // @deprecated since 2.19.0 Use done() without `details` parameter, + // or use `QUnit.on('runEnd')` instead. Parameter to be replaced in + // QUnit 3.0 with test counts. + passed: passed, + failed: config.stats.bad, + total: config.stats.all, + runtime: runtime + }).then(function () { + // Clear own storage items if all tests passed + if (storage && config.stats.bad === 0) { + for (var i = storage.length - 1; i >= 0; i--) { + var key = storage.key(i); + if (key.indexOf('qunit-test-') === 0) { + storage.removeItem(key); + } + } + } + }); } - }, - stack: function stack(offset) { - offset = (offset || 0) + 2; - return sourceFromStacktrace(offset); - } - }); - registerLoggingCallbacks(QUnit); - function scheduleBegin() { - runStarted = true; + }]); + }(); - // Add a slight delay to allow definition of more modules and tests. - if (setTimeout$1) { - setTimeout$1(function () { - begin(); + /** + * Handle a global error that should result in a failed test run. + * + * Summary: + * + * - If we're strictly inside a test (or one if its module hooks), the exception + * becomes a failed assertion. + * + * This has the important side-effect that uncaught exceptions (such as + * calling an undefined function) during a "todo" test do NOT result in + * a failed test run. + * + * - If we're anywhere outside a test (be it in early event callbacks, or + * internally between tests, or somewhere after "runEnd" if the process is + * still alive for some reason), then send an "error" event to the reporters. + * + * @since 2.17.0 + * @param {Error|any} error + */ + function onUncaughtException(error) { + if (config.current) { + // This omits 'actual' and 'expected' (undefined) + config.current.assert.pushResult({ + result: false, + message: "global failure: ".concat(errorString(error)), + // We could let callers specify an offset to subtract a number of frames via + // sourceFromStacktrace, in case they are a wrapper further away from the error + // handler, and thus reduce some noise in the stack trace. However, we're not + // doing this right now because it would almost never be used in practice given + // the vast majority of error values will be Error objects, and thus have their + // own stack trace already. + source: error && error.stack || sourceFromStacktrace(2) }); } else { - begin(); + // The "error" event was added in QUnit 2.17. + // Increase "bad assertion" stats despite no longer pushing an assertion in this case. + // This ensures "runEnd" and "QUnit.done()" handlers behave as expected, since the "bad" + // count is typically how reporters decide on the boolean outcome of the test run. + runSuite.globalFailureCount++; + config.stats.bad++; + config.stats.all++; + emit('error', error); } } - function unblockAndAdvanceQueue() { - config.blocking = false; - ProcessingQueue.advance(); - } - function begin() { - if (config.started) { - unblockAndAdvanceQueue(); - return; - } - - // The test run hasn't officially begun yet - // Record the time of the test run's beginning - config.started = performance.now(); - // Delete the loose unnamed module if unused. - if (config.modules[0].name === '' && config.modules[0].tests.length === 0) { - config.modules.shift(); - } - var modulesLog = []; - for (var i = 0; i < config.modules.length; i++) { - // Don't expose the unnamed global test module to plugins. - if (config.modules[i].name !== '') { - modulesLog.push({ - name: config.modules[i].name, - moduleId: config.modules[i].moduleId, - // Added in QUnit 1.16.0 for internal use by html-reporter, - // but no longer used since QUnit 2.7.0. - // @deprecated Kept unofficially to be removed in QUnit 3.0. - tests: config.modules[i].tests - }); - } + /** + * Handle a window.onerror error. + * + * If there is a current test that sets the internal `ignoreGlobalErrors` field + * (such as during `assert.throws()`), then the error is ignored and native + * error reporting is suppressed as well. This is because in browsers, an error + * can sometimes end up in `window.onerror` instead of in the local try/catch. + * This ignoring of errors does not apply to our general onUncaughtException + * method, nor to our `unhandledRejection` handlers, as those are not meant + * to receive an "expected" error during `assert.throws()`. + * + * @see + * @deprecated since 2.17.0 Use QUnit.onUncaughtException instead. + * @param {Object} details + * @param {string} details.message + * @param {string} details.fileName + * @param {number} details.lineNumber + * @param {string|undefined} [details.stacktrace] + * @return {bool} True if native error reporting should be suppressed. + */ + function onWindowError(details) { + Logger.warn('QUnit.onError is deprecated and will be removed in QUnit 3.0.' + ' Please use QUnit.onUncaughtException instead.'); + if (config.current && config.current.ignoreGlobalErrors) { + return true; } - - // The test run is officially beginning now - emit('runStart', runSuite.start(true)); - runLoggingCallbacks('begin', { - totalTests: Test.count, - modules: modulesLog - }).then(unblockAndAdvanceQueue); + var err = new Error(details.message); + err.stack = details.stacktrace || details.fileName + ':' + details.lineNumber; + onUncaughtException(err); + return false; } - exportQUnit(QUnit); - (function () { - if (!window$1 || !document) { - return; - } - var config = QUnit.config; - var hasOwn = Object.prototype.hasOwnProperty; + /* eslint-disable indent */ - // Stores fixture HTML for resetting later - function storeFixture() { - // Avoid overwriting user-defined values - if (hasOwn.call(config, 'fixture')) { - return; - } - var fixture = document.getElementById('qunit-fixture'); - if (fixture) { - config.fixture = fixture.cloneNode(true); - } + /* + * This file is a modified version of google-diff-match-patch's JavaScript implementation + * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js), + * modifications are licensed as more fully set forth in LICENSE.txt. + * + * The original source of google-diff-match-patch is attributable and licensed as follows: + * + * Copyright 2006 Google Inc. + * https://code.google.com/p/google-diff-match-patch/ + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * More Info: + * https://code.google.com/p/google-diff-match-patch/ + * + * Usage: QUnit.diff(expected, actual) + * + */ + function DiffMatchPatch() {} + + // DIFF FUNCTIONS + + /** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ + var DIFF_DELETE = -1; + var DIFF_INSERT = 1; + var DIFF_EQUAL = 0; + var hasOwn = Object.prototype.hasOwnProperty; + + /** + * Find the differences between two texts. Simplifies the problem by stripping + * any common prefix or suffix off the texts before diffing. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean=} optChecklines Optional speedup flag. If present and false, + * then don't run a line-level diff first to identify the changed areas. + * Defaults to true, which does a faster, slightly less optimal diff. + * @return {!Array.} Array of diff tuples. + */ + DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) { + // The diff must be complete in up to 1 second. + var deadline = Date.now() + 1000; + + // Check for null inputs. + if (text1 === null || text2 === null) { + throw new Error('Cannot diff null input.'); } - QUnit.begin(storeFixture); - // Resets the fixture DOM element if available. - function resetFixture() { - if (config.fixture == null) { - return; - } - var fixture = document.getElementById('qunit-fixture'); - var resetFixtureType = _typeof(config.fixture); - if (resetFixtureType === 'string') { - // support user defined values for `config.fixture` - var newFixture = document.createElement('div'); - newFixture.setAttribute('id', 'qunit-fixture'); - newFixture.innerHTML = config.fixture; - fixture.parentNode.replaceChild(newFixture, fixture); - } else { - var clonedFixture = config.fixture.cloneNode(true); - fixture.parentNode.replaceChild(clonedFixture, fixture); + // Check for equality (speedup). + if (text1 === text2) { + if (text1) { + return [[DIFF_EQUAL, text1]]; } + return []; } - QUnit.testStart(resetFixture); - })(); - - (function () { - // Only interact with URLs via window.location - var location = typeof window$1 !== 'undefined' && window$1.location; - if (!location) { - return; + if (typeof optChecklines === 'undefined') { + optChecklines = true; } - var urlParams = getUrlParams(); - QUnit.urlParams = urlParams; - QUnit.config.filter = urlParams.filter; - QUnit.config.module = urlParams.module; - QUnit.config.moduleId = [].concat(urlParams.moduleId || []); - QUnit.config.testId = [].concat(urlParams.testId || []); - // Test order randomization - if (urlParams.seed === true) { - // Generate a random seed if the option is specified without a value - QUnit.config.seed = Math.random().toString(36).slice(2); - } else if (urlParams.seed) { - QUnit.config.seed = urlParams.seed; + // Trim off common prefix (speedup). + var commonlength = this.diffCommonPrefix(text1, text2); + var commonprefix = text1.substring(0, commonlength); + text1 = text1.substring(commonlength); + text2 = text2.substring(commonlength); + + // Trim off common suffix (speedup). + commonlength = this.diffCommonSuffix(text1, text2); + var commonsuffix = text1.substring(text1.length - commonlength); + text1 = text1.substring(0, text1.length - commonlength); + text2 = text2.substring(0, text2.length - commonlength); + + // Compute the diff on the middle block. + var diffs = this.diffCompute(text1, text2, optChecklines, deadline); + + // Restore the prefix and suffix. + if (commonprefix) { + diffs.unshift([DIFF_EQUAL, commonprefix]); } + if (commonsuffix) { + diffs.push([DIFF_EQUAL, commonsuffix]); + } + this.diffCleanupMerge(diffs); + return diffs; + }; - // Add URL-parameter-mapped config values with UI form rendering data - QUnit.config.urlConfig.push({ - id: 'hidepassed', - label: 'Hide passed tests', - tooltip: 'Only show tests and assertions that fail. Stored as query-strings.' - }, { - id: 'noglobals', - label: 'Check for Globals', - tooltip: 'Enabling this will test if any test introduces new properties on the ' + 'global object (`window` in Browsers). Stored as query-strings.' - }, { - id: 'notrycatch', - label: 'No try-catch', - tooltip: 'Enabling this will run tests outside of a try-catch block. Makes debugging ' + 'exceptions in IE reasonable. Stored as query-strings.' - }); - QUnit.begin(function () { - var urlConfig = QUnit.config.urlConfig; - for (var i = 0; i < urlConfig.length; i++) { - // Options can be either strings or objects with nonempty "id" properties - var option = QUnit.config.urlConfig[i]; - if (typeof option !== 'string') { - option = option.id; - } - if (QUnit.config[option] === undefined) { - QUnit.config[option] = urlParams[option]; + /** + * Reduce the number of edits by eliminating operationally trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) { + var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel; + changes = false; + equalities = []; // Stack of indices where equalities are found. + equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + lastequality = null; + + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + pointer = 0; // Index of current position. + + // Is there an insertion operation before the last equality. + preIns = false; + + // Is there a deletion operation before the last equality. + preDel = false; + + // Is there an insertion operation after the last equality. + postIns = false; + + // Is there a deletion operation after the last equality. + postDel = false; + while (pointer < diffs.length) { + // Equality found. + if (diffs[pointer][0] === DIFF_EQUAL) { + if (diffs[pointer][1].length < 4 && (postIns || postDel)) { + // Candidate found. + equalities[equalitiesLength++] = pointer; + preIns = postIns; + preDel = postDel; + lastequality = diffs[pointer][1]; + } else { + // Not a candidate, and can never become one. + equalitiesLength = 0; + lastequality = null; } - } - }); - function getUrlParams() { - var urlParams = Object.create(null); - var params = location.search.slice(1).split('&'); - var length = params.length; - for (var i = 0; i < length; i++) { - if (params[i]) { - var param = params[i].split('='); - var name = decodeQueryParam(param[0]); + postIns = postDel = false; - // Allow just a key to turn on a flag, e.g., test.html?noglobals - var value = param.length === 1 || decodeQueryParam(param.slice(1).join('=')); - if (name in urlParams) { - urlParams[name] = [].concat(urlParams[name], value); + // An insertion or deletion. + } else { + if (diffs[pointer][0] === DIFF_DELETE) { + postDel = true; + } else { + postIns = true; + } + + /* + * Five types to be split: + * ABXYCD + * AXCD + * ABXC + * AXCD + * ABXC + */ + if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) { + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); + + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + equalitiesLength--; // Throw away the equality we just deleted; + lastequality = null; + if (preIns && preDel) { + // No changes made which could affect previous entry, keep going. + postIns = postDel = true; + equalitiesLength = 0; } else { - urlParams[name] = value; + equalitiesLength--; // Throw away the previous equality. + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + postIns = postDel = false; } + changes = true; } } - return urlParams; + pointer++; } - function decodeQueryParam(param) { - return decodeURIComponent(param.replace(/\+/g, '%20')); + if (changes) { + this.diffCleanupMerge(diffs); } - })(); + }; - var fuzzysort$1 = {exports: {}}; + /** + * Convert a diff array into a pretty HTML report. + * @param {!Array.} diffs Array of diff tuples. + * @param {integer} string to be beautified. + * @return {string} HTML representation. + */ + DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) { + var html = []; + for (var x = 0; x < diffs.length; x++) { + var op = diffs[x][0]; // Operation (insert, delete, equal) + var data = diffs[x][1]; // Text of change. + switch (op) { + case DIFF_INSERT: + html[x] = '' + escapeText(data) + ''; + break; + case DIFF_DELETE: + html[x] = '' + escapeText(data) + ''; + break; + case DIFF_EQUAL: + html[x] = '' + escapeText(data) + ''; + break; + } + } + return html.join(''); + }; - (function (module) { - (function (root, UMD) { - if (module.exports) module.exports = UMD();else root.fuzzysort = UMD(); - })(commonjsGlobal, function UMD() { - function fuzzysortNew(instanceOptions) { - var fuzzysort = { - single: function single(search, target, options) { - if (search == 'farzher') return { - target: "farzher was here (^-^*)/", - score: 0, - indexes: [0, 1, 2, 3, 4, 5, 6] - }; - if (!search) return null; - if (!isObj(search)) search = fuzzysort.getPreparedSearch(search); - if (!target) return null; - if (!isObj(target)) target = fuzzysort.getPrepared(target); - var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true; - var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; - return algorithm(search, target, search[0]); - }, - go: function go(search, targets, options) { - if (search == 'farzher') return [{ - target: "farzher was here (^-^*)/", - score: 0, - indexes: [0, 1, 2, 3, 4, 5, 6], - obj: targets ? targets[0] : null - }]; - if (!search) return noResults; - search = fuzzysort.prepareSearch(search); - var searchLowerCode = search[0]; - var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991; - var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991; - var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true; - var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; - var resultsLen = 0; - var limitedCount = 0; - var targetsLen = targets.length; + /** + * Determine the common prefix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the start of each + * string. + */ + DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) { + var pointermid, pointermax, pointermin, pointerstart; + + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { + return 0; + } + + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + pointermin = 0; + pointermax = Math.min(text1.length, text2.length); + pointermid = pointermax; + pointerstart = 0; + while (pointermin < pointermid) { + if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; - // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] + /** + * Determine the common suffix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of each string. + */ + DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) { + var pointermid, pointermax, pointermin, pointerend; + + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { + return 0; + } + + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + pointermin = 0; + pointermax = Math.min(text1.length, text2.length); + pointermid = pointermax; + pointerend = 0; + while (pointermin < pointermid) { + if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; + }; - // options.keys - if (options && options.keys) { - var scoreFn = options.scoreFn || defaultScoreFn; - var keys = options.keys; - var keysLen = keys.length; - for (var i = targetsLen - 1; i >= 0; --i) { - var obj = targets[i]; - var objResults = new Array(keysLen); - for (var keyI = keysLen - 1; keyI >= 0; --keyI) { - var key = keys[keyI]; - var target = getValue(obj, key); - if (!target) { - objResults[keyI] = null; - continue; - } - if (!isObj(target)) target = fuzzysort.getPrepared(target); - objResults[keyI] = algorithm(search, target, searchLowerCode); - } - objResults.obj = obj; // before scoreFn so scoreFn can use it - var score = scoreFn(objResults); - if (score === null) continue; - if (score < threshold) continue; - objResults.score = score; - if (resultsLen < limit) { - q.add(objResults); - ++resultsLen; - } else { - ++limitedCount; - if (score > q.peek().score) q.replaceTop(objResults); - } - } + /** + * Find the differences between two texts. Assumes that the texts do not + * have any common prefix or suffix. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {boolean} checklines Speedup flag. If false, then don't run a + * line-level diff first to identify the changed areas. + * If true, then run a faster, slightly less optimal diff. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) { + var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB; + if (!text1) { + // Just add some text (speedup). + return [[DIFF_INSERT, text2]]; + } + if (!text2) { + // Just delete some text (speedup). + return [[DIFF_DELETE, text1]]; + } + longtext = text1.length > text2.length ? text1 : text2; + shorttext = text1.length > text2.length ? text2 : text1; + i = longtext.indexOf(shorttext); + if (i !== -1) { + // Shorter text is inside the longer text (speedup). + diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; + + // Swap insertions for deletions if diff is reversed. + if (text1.length > text2.length) { + diffs[0][0] = diffs[2][0] = DIFF_DELETE; + } + return diffs; + } + if (shorttext.length === 1) { + // Single character string. + // After the previous speedup, the character can't be an equality. + return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; + } - // options.key - } else if (options && options.key) { - var key = options.key; - for (var i = targetsLen - 1; i >= 0; --i) { - var obj = targets[i]; - var target = getValue(obj, key); - if (!target) continue; - if (!isObj(target)) target = fuzzysort.getPrepared(target); - var result = algorithm(search, target, searchLowerCode); - if (result === null) continue; - if (result.score < threshold) continue; + // Check to see if the problem can be split in two. + hm = this.diffHalfMatch(text1, text2); + if (hm) { + // A half-match was found, sort out the return data. + text1A = hm[0]; + text1B = hm[1]; + text2A = hm[2]; + text2B = hm[3]; + midCommon = hm[4]; - // have to clone result so duplicate targets from different obj can each reference the correct obj - result = { - target: result.target, - _targetLowerCodes: null, - _nextBeginningIndexes: null, - score: result.score, - indexes: result.indexes, - obj: obj - }; // hidden + // Send both pairs off for separate processing. + diffsA = this.DiffMain(text1A, text2A, checklines, deadline); + diffsB = this.DiffMain(text1B, text2B, checklines, deadline); - if (resultsLen < limit) { - q.add(result); - ++resultsLen; - } else { - ++limitedCount; - if (result.score > q.peek().score) q.replaceTop(result); - } - } + // Merge the results. + return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB); + } + if (checklines && text1.length > 100 && text2.length > 100) { + return this.diffLineMode(text1, text2, deadline); + } + return this.diffBisect(text1, text2, deadline); + }; - // no keys - } else { - for (var i = targetsLen - 1; i >= 0; --i) { - var target = targets[i]; - if (!target) continue; - if (!isObj(target)) target = fuzzysort.getPrepared(target); - var result = algorithm(search, target, searchLowerCode); - if (result === null) continue; - if (result.score < threshold) continue; - if (resultsLen < limit) { - q.add(result); - ++resultsLen; - } else { - ++limitedCount; - if (result.score > q.peek().score) q.replaceTop(result); - } - } + /** + * Do the two texts share a substring which is at least half the length of the + * longer text? + * This speedup can produce non-minimal diffs. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {Array.} Five element Array, containing the prefix of + * text1, the suffix of text1, the prefix of text2, the suffix of + * text2 and the common middle. Or null if there was no match. + * @private + */ + DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) { + var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm; + longtext = text1.length > text2.length ? text1 : text2; + shorttext = text1.length > text2.length ? text2 : text1; + if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { + return null; // Pointless. + } + dmp = this; // 'this' becomes 'window' in a closure. + + /** + * Does a substring of shorttext exist within longtext such that the substring + * is at least half the length of longtext? + * Closure, but does not reference any external variables. + * @param {string} longtext Longer string. + * @param {string} shorttext Shorter string. + * @param {number} i Start index of quarter length substring within longtext. + * @return {Array.} Five element Array, containing the prefix of + * longtext, the suffix of longtext, the prefix of shorttext, the suffix + * of shorttext and the common middle. Or null if there was no match. + * @private + */ + function diffHalfMatchI(longtext, shorttext, i) { + var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; + + // Start with a 1/4 length substring at position i as a seed. + seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); + j = -1; + bestCommon = ''; + while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { + prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j)); + suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); + if (bestCommon.length < suffixLength + prefixLength) { + bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); + bestLongtextA = longtext.substring(0, i - suffixLength); + bestLongtextB = longtext.substring(i + prefixLength); + bestShorttextA = shorttext.substring(0, j - suffixLength); + bestShorttextB = shorttext.substring(j + prefixLength); + } + } + if (bestCommon.length * 2 >= longtext.length) { + return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon]; + } else { + return null; + } + } + + // First check if the second quarter is the seed for a half-match. + hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4)); + + // Check again based on the third quarter. + hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2)); + if (!hm1 && !hm2) { + return null; + } else if (!hm2) { + hm = hm1; + } else if (!hm1) { + hm = hm2; + } else { + // Both matched. Select the longest. + hm = hm1[4].length > hm2[4].length ? hm1 : hm2; + } + + // A half-match was found, sort out the return data. + if (text1.length > text2.length) { + text1A = hm[0]; + text1B = hm[1]; + text2A = hm[2]; + text2B = hm[3]; + } else { + text2A = hm[0]; + text2B = hm[1]; + text1A = hm[2]; + text1B = hm[3]; + } + midCommon = hm[4]; + return [text1A, text1B, text2A, text2B, midCommon]; + }; + + /** + * Do a quick line-level diff on both strings, then rediff the parts for + * greater accuracy. + * This speedup can produce non-minimal diffs. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time when the diff should be complete by. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) { + var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j; + + // Scan the text on a line-by-line basis first. + a = this.diffLinesToChars(text1, text2); + text1 = a.chars1; + text2 = a.chars2; + linearray = a.lineArray; + diffs = this.DiffMain(text1, text2, false, deadline); + + // Convert the diff back to original text. + this.diffCharsToLines(diffs, linearray); + + // Eliminate freak matches (e.g. blank lines) + this.diffCleanupSemantic(diffs); + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs.push([DIFF_EQUAL, '']); + pointer = 0; + countDelete = 0; + countInsert = 0; + textDelete = ''; + textInsert = ''; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + countInsert++; + textInsert += diffs[pointer][1]; + break; + case DIFF_DELETE: + countDelete++; + textDelete += diffs[pointer][1]; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (countDelete >= 1 && countInsert >= 1) { + // Delete the offending records and add the merged ones. + diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert); + pointer = pointer - countDelete - countInsert; + a = this.DiffMain(textDelete, textInsert, false, deadline); + for (j = a.length - 1; j >= 0; j--) { + diffs.splice(pointer, 0, a[j]); } - if (resultsLen === 0) return noResults; - var results = new Array(resultsLen); - for (var i = resultsLen - 1; i >= 0; --i) { - results[i] = q.poll(); + pointer = pointer + a.length; + } + countInsert = 0; + countDelete = 0; + textDelete = ''; + textInsert = ''; + break; + } + pointer++; + } + diffs.pop(); // Remove the dummy entry at the end. + + return diffs; + }; + + /** + * Find the 'middle snake' of a diff, split the problem in two + * and return the recursively constructed diff. + * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) { + var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2; + + // Cache the text lengths to prevent multiple calls. + text1Length = text1.length; + text2Length = text2.length; + maxD = Math.ceil((text1Length + text2Length) / 2); + vOffset = maxD; + vLength = 2 * maxD; + v1 = new Array(vLength); + v2 = new Array(vLength); + + // Setting all elements to -1 is faster in Chrome & Firefox than mixing + // integers and undefined. + for (x = 0; x < vLength; x++) { + v1[x] = -1; + v2[x] = -1; + } + v1[vOffset + 1] = 0; + v2[vOffset + 1] = 0; + delta = text1Length - text2Length; + + // If the total number of characters is odd, then the front path will collide + // with the reverse path. + front = delta % 2 !== 0; + + // Offsets for start and end of k loop. + // Prevents mapping of space beyond the grid. + k1start = 0; + k1end = 0; + k2start = 0; + k2end = 0; + for (d = 0; d < maxD; d++) { + // Bail out if deadline is reached. + if (Date.now() > deadline) { + break; + } + + // Walk the front path one step. + for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { + k1Offset = vOffset + k1; + if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) { + x1 = v1[k1Offset + 1]; + } else { + x1 = v1[k1Offset - 1] + 1; + } + y1 = x1 - k1; + while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) { + x1++; + y1++; + } + v1[k1Offset] = x1; + if (x1 > text1Length) { + // Ran off the right of the graph. + k1end += 2; + } else if (y1 > text2Length) { + // Ran off the bottom of the graph. + k1start += 2; + } else if (front) { + k2Offset = vOffset + delta - k1; + if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) { + // Mirror x2 onto top-left coordinate system. + x2 = text1Length - v2[k2Offset]; + if (x1 >= x2) { + // Overlap detected. + return this.diffBisectSplit(text1, text2, x1, y1, deadline); } - results.total = resultsLen + limitedCount; - return results; - }, - goAsync: function goAsync(search, targets, options) { - var canceled = false; - var p = new Promise(function (resolve, reject) { - if (search == 'farzher') return resolve([{ - target: "farzher was here (^-^*)/", - score: 0, - indexes: [0, 1, 2, 3, 4, 5, 6], - obj: targets ? targets[0] : null - }]); - if (!search) return resolve(noResults); - search = fuzzysort.prepareSearch(search); - var searchLowerCode = search[0]; - var q = fastpriorityqueue(); - var iCurrent = targets.length - 1; - var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991; - var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991; - var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true; - var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; - var resultsLen = 0; - var limitedCount = 0; - function step() { - if (canceled) return reject('canceled'); - var startMs = Date.now(); + } + } + } - // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] + // Walk the reverse path one step. + for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { + k2Offset = vOffset + k2; + if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) { + x2 = v2[k2Offset + 1]; + } else { + x2 = v2[k2Offset - 1] + 1; + } + y2 = x2 - k2; + while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) { + x2++; + y2++; + } + v2[k2Offset] = x2; + if (x2 > text1Length) { + // Ran off the left of the graph. + k2end += 2; + } else if (y2 > text2Length) { + // Ran off the top of the graph. + k2start += 2; + } else if (!front) { + k1Offset = vOffset + delta - k2; + if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) { + x1 = v1[k1Offset]; + y1 = vOffset + x1 - k1Offset; + + // Mirror x2 onto top-left coordinate system. + x2 = text1Length - x2; + if (x1 >= x2) { + // Overlap detected. + return this.diffBisectSplit(text1, text2, x1, y1, deadline); + } + } + } + } + } - // options.keys - if (options && options.keys) { - var scoreFn = options.scoreFn || defaultScoreFn; - var keys = options.keys; - var keysLen = keys.length; - for (; iCurrent >= 0; --iCurrent) { - if (iCurrent % 1000 /*itemsPerCheck*/ === 0) { - if (Date.now() - startMs >= 10 /*asyncInterval*/) { - isNode ? setImmediate(step) : setTimeout(step); - return; - } - } - var obj = targets[iCurrent]; - var objResults = new Array(keysLen); - for (var keyI = keysLen - 1; keyI >= 0; --keyI) { - var key = keys[keyI]; - var target = getValue(obj, key); - if (!target) { - objResults[keyI] = null; - continue; - } - if (!isObj(target)) target = fuzzysort.getPrepared(target); - objResults[keyI] = algorithm(search, target, searchLowerCode); - } - objResults.obj = obj; // before scoreFn so scoreFn can use it - var score = scoreFn(objResults); - if (score === null) continue; - if (score < threshold) continue; - objResults.score = score; - if (resultsLen < limit) { - q.add(objResults); - ++resultsLen; - } else { - ++limitedCount; - if (score > q.peek().score) q.replaceTop(objResults); - } - } + // Diff took too long and hit the deadline or + // number of diffs equals number of characters, no commonality at all. + return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; + }; - // options.key - } else if (options && options.key) { - var key = options.key; - for (; iCurrent >= 0; --iCurrent) { - if (iCurrent % 1000 /*itemsPerCheck*/ === 0) { - if (Date.now() - startMs >= 10 /*asyncInterval*/) { - isNode ? setImmediate(step) : setTimeout(step); - return; - } - } - var obj = targets[iCurrent]; - var target = getValue(obj, key); - if (!target) continue; - if (!isObj(target)) target = fuzzysort.getPrepared(target); - var result = algorithm(search, target, searchLowerCode); - if (result === null) continue; - if (result.score < threshold) continue; + /** + * Given the location of the 'middle snake', split the diff in two parts + * and recurse. + * @param {string} text1 Old string to be diffed. + * @param {string} text2 New string to be diffed. + * @param {number} x Index of split point in text1. + * @param {number} y Index of split point in text2. + * @param {number} deadline Time at which to bail if not yet complete. + * @return {!Array.} Array of diff tuples. + * @private + */ + DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) { + var text1a, text1b, text2a, text2b, diffs, diffsb; + text1a = text1.substring(0, x); + text2a = text2.substring(0, y); + text1b = text1.substring(x); + text2b = text2.substring(y); + + // Compute both diffs serially. + diffs = this.DiffMain(text1a, text2a, false, deadline); + diffsb = this.DiffMain(text1b, text2b, false, deadline); + return diffs.concat(diffsb); + }; - // have to clone result so duplicate targets from different obj can each reference the correct obj - result = { - target: result.target, - _targetLowerCodes: null, - _nextBeginningIndexes: null, - score: result.score, - indexes: result.indexes, - obj: obj - }; // hidden + /** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) { + var changes = false; + var equalities = []; // Stack of indices where equalities are found. + var equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + var lastequality = null; + + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer = 0; // Index of current position. + + // Number of characters that changed prior to the equality. + var lengthInsertions1 = 0; + var lengthDeletions1 = 0; + + // Number of characters that changed after the equality. + var lengthInsertions2 = 0; + var lengthDeletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] === DIFF_EQUAL) { + // Equality found. + equalities[equalitiesLength++] = pointer; + lengthInsertions1 = lengthInsertions2; + lengthDeletions1 = lengthDeletions2; + lengthInsertions2 = 0; + lengthDeletions2 = 0; + lastequality = diffs[pointer][1]; + } else { + // An insertion or deletion. + if (diffs[pointer][0] === DIFF_INSERT) { + lengthInsertions2 += diffs[pointer][1].length; + } else { + lengthDeletions2 += diffs[pointer][1].length; + } - if (resultsLen < limit) { - q.add(result); - ++resultsLen; - } else { - ++limitedCount; - if (result.score > q.peek().score) q.replaceTop(result); - } - } + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) { + // Duplicate record. + diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); - // no keys - } else { - for (; iCurrent >= 0; --iCurrent) { - if (iCurrent % 1000 /*itemsPerCheck*/ === 0) { - if (Date.now() - startMs >= 10 /*asyncInterval*/) { - isNode ? setImmediate(step) : setTimeout(step); - return; - } - } - var target = targets[iCurrent]; - if (!target) continue; - if (!isObj(target)) target = fuzzysort.getPrepared(target); - var result = algorithm(search, target, searchLowerCode); - if (result === null) continue; - if (result.score < threshold) continue; - if (resultsLen < limit) { - q.add(result); - ++resultsLen; - } else { - ++limitedCount; - if (result.score > q.peek().score) q.replaceTop(result); - } - } - } - if (resultsLen === 0) return resolve(noResults); - var results = new Array(resultsLen); - for (var i = resultsLen - 1; i >= 0; --i) { - results[i] = q.poll(); - } - results.total = resultsLen + limitedCount; - resolve(results); - } - isNode ? setImmediate(step) : step(); //setTimeout here is too slow - }); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - p.cancel = function () { - canceled = true; - }; - return p; - }, - highlight: function highlight(result, hOpen, hClose) { - if (typeof hOpen == 'function') return fuzzysort.highlightCallback(result, hOpen); - if (result === null) return null; - if (hOpen === undefined) hOpen = ''; - if (hClose === undefined) hClose = ''; - var highlighted = ''; - var matchesIndex = 0; - var opened = false; - var target = result.target; - var targetLen = target.length; - var matchesBest = result.indexes; - for (var i = 0; i < targetLen; ++i) { - var char = target[i]; - if (matchesBest[matchesIndex] === i) { - ++matchesIndex; - if (!opened) { - opened = true; - highlighted += hOpen; - } - if (matchesIndex === matchesBest.length) { - highlighted += char + hClose + target.substr(i + 1); - break; - } - } else { - if (opened) { - opened = false; - highlighted += hClose; - } - } - highlighted += char; - } - return highlighted; - }, - highlightCallback: function highlightCallback(result, cb) { - if (result === null) return null; - var target = result.target; - var targetLen = target.length; - var indexes = result.indexes; - var highlighted = ''; - var matchI = 0; - var indexesI = 0; - var opened = false; - var result = []; - for (var i = 0; i < targetLen; ++i) { - var char = target[i]; - if (indexes[indexesI] === i) { - ++indexesI; - if (!opened) { - opened = true; - result.push(highlighted); - highlighted = ''; - } - if (indexesI === indexes.length) { - highlighted += char; - result.push(cb(highlighted, matchI++)); - highlighted = ''; - result.push(target.substr(i + 1)); - break; - } - } else { - if (opened) { - opened = false; - result.push(cb(highlighted, matchI++)); - highlighted = ''; - } - } - highlighted += char; - } - return result; - }, - prepare: function prepare(target) { - if (!target) return { - target: '', - _targetLowerCodes: [0 /*this 0 doesn't make sense. here because an empty array causes the algorithm to deoptimize and run 50% slower!*/], - _nextBeginningIndexes: null, - score: null, - indexes: null, - obj: null - }; // hidden - return { - target: target, - _targetLowerCodes: fuzzysort.prepareLowerCodes(target), - _nextBeginningIndexes: null, - score: null, - indexes: null, - obj: null - }; // hidden - }, + // Throw away the equality we just deleted. + equalitiesLength--; - prepareSlow: function prepareSlow(target) { - if (!target) return { - target: '', - _targetLowerCodes: [0 /*this 0 doesn't make sense. here because an empty array causes the algorithm to deoptimize and run 50% slower!*/], - _nextBeginningIndexes: null, - score: null, - indexes: null, - obj: null - }; // hidden - return { - target: target, - _targetLowerCodes: fuzzysort.prepareLowerCodes(target), - _nextBeginningIndexes: fuzzysort.prepareNextBeginningIndexes(target), - score: null, - indexes: null, - obj: null - }; // hidden - }, + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - prepareSearch: function prepareSearch(search) { - if (!search) search = ''; - return fuzzysort.prepareLowerCodes(search); - }, - // Below this point is only internal code - // Below this point is only internal code - // Below this point is only internal code - // Below this point is only internal code + // Reset the counters. + lengthInsertions1 = 0; + lengthDeletions1 = 0; + lengthInsertions2 = 0; + lengthDeletions2 = 0; + lastequality = null; + changes = true; + } + } + pointer++; + } - getPrepared: function getPrepared(target) { - if (target.length > 999) return fuzzysort.prepare(target); // don't cache huge targets - var targetPrepared = preparedCache.get(target); - if (targetPrepared !== undefined) return targetPrepared; - targetPrepared = fuzzysort.prepare(target); - preparedCache.set(target, targetPrepared); - return targetPrepared; - }, - getPreparedSearch: function getPreparedSearch(search) { - if (search.length > 999) return fuzzysort.prepareSearch(search); // don't cache huge searches - var searchPrepared = preparedSearchCache.get(search); - if (searchPrepared !== undefined) return searchPrepared; - searchPrepared = fuzzysort.prepareSearch(search); - preparedSearchCache.set(search, searchPrepared); - return searchPrepared; - }, - algorithm: function algorithm(searchLowerCodes, prepared, searchLowerCode) { - var targetLowerCodes = prepared._targetLowerCodes; - var searchLen = searchLowerCodes.length; - var targetLen = targetLowerCodes.length; - var searchI = 0; // where we at - var targetI = 0; // where you at - var typoSimpleI = 0; - var matchesSimpleLen = 0; + // Normalize the diff. + if (changes) { + this.diffCleanupMerge(diffs); + } + var deletion, insertion, overlapLength1, overlapLength2; + + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { + deletion = diffs[pointer - 1][1]; + insertion = diffs[pointer][1]; + overlapLength1 = this.diffCommonOverlap(deletion, insertion); + overlapLength2 = this.diffCommonOverlap(insertion, deletion); + if (overlapLength1 >= overlapLength2) { + if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]); + diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1); + diffs[pointer + 1][1] = insertion.substring(overlapLength1); + pointer++; + } + } else { + if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlapLength2); + pointer++; + } + } + pointer++; + } + pointer++; + } + }; - // very basic fuzzy match; to remove non-matching targets ASAP! - // walk through target. find sequential matches. - // if all chars aren't found then exit - for (;;) { - var isMatch = searchLowerCode === targetLowerCodes[targetI]; - if (isMatch) { - matchesSimple[matchesSimpleLen++] = targetI; - ++searchI; - if (searchI === searchLen) break; - searchLowerCode = searchLowerCodes[typoSimpleI === 0 ? searchI : typoSimpleI === searchI ? searchI + 1 : typoSimpleI === searchI - 1 ? searchI - 1 : searchI]; - } - ++targetI; - if (targetI >= targetLen) { - // Failed to find searchI - // Check for typo or exit - // we go as far as possible before trying to transpose - // then we transpose backwards until we reach the beginning - for (;;) { - if (searchI <= 1) return null; // not allowed to transpose first char - if (typoSimpleI === 0) { - // we haven't tried to transpose yet - --searchI; - var searchLowerCodeNew = searchLowerCodes[searchI]; - if (searchLowerCode === searchLowerCodeNew) continue; // doesn't make sense to transpose a repeat char - typoSimpleI = searchI; - } else { - if (typoSimpleI === 1) return null; // reached the end of the line for transposing - --typoSimpleI; - searchI = typoSimpleI; - searchLowerCode = searchLowerCodes[searchI + 1]; - var searchLowerCodeNew = searchLowerCodes[searchI]; - if (searchLowerCode === searchLowerCodeNew) continue; // doesn't make sense to transpose a repeat char - } + /** + * Determine if the suffix of one string is the prefix of another. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of the first + * string and the start of the second string. + * @private + */ + DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) { + // Cache the text lengths to prevent multiple calls. + var text1Length = text1.length; + var text2Length = text2.length; - matchesSimpleLen = searchI; - targetI = matchesSimple[matchesSimpleLen - 1] + 1; - break; - } - } - } - var searchI = 0; - var typoStrictI = 0; - var successStrict = false; - var matchesStrictLen = 0; - var nextBeginningIndexes = prepared._nextBeginningIndexes; - if (nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target); - var firstPossibleI = targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; + // Eliminate the null case. + if (text1Length === 0 || text2Length === 0) { + return 0; + } - // Our target string successfully matched all characters in sequence! - // Let's try a more advanced and strict test to improve the score - // only count it as a match if it's consecutive or a beginning character! - if (targetI !== targetLen) for (;;) { - if (targetI >= targetLen) { - // We failed to find a good spot for this search char, go back to the previous search char and force it forward - if (searchI <= 0) { - // We failed to push chars forward for a better match - // transpose, starting from the beginning - ++typoStrictI; - if (typoStrictI > searchLen - 2) break; - if (searchLowerCodes[typoStrictI] === searchLowerCodes[typoStrictI + 1]) continue; // doesn't make sense to transpose a repeat char - targetI = firstPossibleI; - continue; - } - --searchI; - var lastMatch = matchesStrict[--matchesStrictLen]; - targetI = nextBeginningIndexes[lastMatch]; - } else { - var isMatch = searchLowerCodes[typoStrictI === 0 ? searchI : typoStrictI === searchI ? searchI + 1 : typoStrictI === searchI - 1 ? searchI - 1 : searchI] === targetLowerCodes[targetI]; - if (isMatch) { - matchesStrict[matchesStrictLen++] = targetI; - ++searchI; - if (searchI === searchLen) { - successStrict = true; - break; - } - ++targetI; + // Truncate the longer string. + if (text1Length > text2Length) { + text1 = text1.substring(text1Length - text2Length); + } else if (text1Length < text2Length) { + text2 = text2.substring(0, text1Length); + } + var textLength = Math.min(text1Length, text2Length); + + // Quick check for the worst case. + if (text1 === text2) { + return textLength; + } + + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + var best = 0; + var length = 1; + while (true) { + var pattern = text1.substring(textLength - length); + var found = text2.indexOf(pattern); + if (found === -1) { + return best; + } + length += found; + if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) { + best = length; + length++; + } + } + }; + + /** + * Split two texts into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {{chars1: string, chars2: string, lineArray: !Array.}} + * An object containing the encoded text1, the encoded text2 and + * the array of unique strings. + * The zeroth element of the array of unique strings is intentionally blank. + * @private + */ + DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) { + var lineArray = []; // E.g. lineArray[4] === 'Hello\n' + var lineHash = {}; // E.g. lineHash['Hello\n'] === 4 + + // '\x00' is a valid character, but various debuggers don't like it. + // So we'll insert a junk entry to avoid generating a null character. + lineArray[0] = ''; + + /** + * Split a text into an array of strings. Reduce the texts to a string of + * hashes where each Unicode character represents one line. + * Modifies linearray and linehash through being a closure. + * @param {string} text String to encode. + * @return {string} Encoded string. + * @private + */ + function diffLinesToCharsMunge(text) { + var chars = ''; + + // Walk the text, pulling out a substring for each line. + // text.split('\n') would would temporarily double our memory footprint. + // Modifying text would create many large strings to garbage collect. + var lineStart = 0; + var lineEnd = -1; + + // Keeping our own length variable is faster than looking it up. + var lineArrayLength = lineArray.length; + while (lineEnd < text.length - 1) { + lineEnd = text.indexOf('\n', lineStart); + if (lineEnd === -1) { + lineEnd = text.length - 1; + } + var line = text.substring(lineStart, lineEnd + 1); + lineStart = lineEnd + 1; + if (hasOwn.call(lineHash, line)) { + chars += String.fromCharCode(lineHash[line]); + } else { + chars += String.fromCharCode(lineArrayLength); + lineHash[line] = lineArrayLength; + lineArray[lineArrayLength++] = line; + } + } + return chars; + } + var chars1 = diffLinesToCharsMunge(text1); + var chars2 = diffLinesToCharsMunge(text2); + return { + chars1: chars1, + chars2: chars2, + lineArray: lineArray + }; + }; + + /** + * Rehydrate the text in a diff from a string of line hashes to real lines of + * text. + * @param {!Array.} diffs Array of diff tuples. + * @param {!Array.} lineArray Array of unique strings. + * @private + */ + DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) { + for (var x = 0; x < diffs.length; x++) { + var chars = diffs[x][1]; + var text = []; + for (var y = 0; y < chars.length; y++) { + text[y] = lineArray[chars.charCodeAt(y)]; + } + diffs[x][1] = text.join(''); + } + }; + + /** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param {!Array.} diffs Array of diff tuples. + */ + DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) { + diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. + var pointer = 0; + var countDelete = 0; + var countInsert = 0; + var textDelete = ''; + var textInsert = ''; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + countInsert++; + textInsert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + countDelete++; + textDelete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (countDelete + countInsert > 1) { + if (countDelete !== 0 && countInsert !== 0) { + // Factor out any common prefixes. + var commonlength = this.diffCommonPrefix(textInsert, textDelete); + if (commonlength !== 0) { + if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) { + diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength); } else { - targetI = nextBeginningIndexes[targetI]; + diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]); + pointer++; } + textInsert = textInsert.substring(commonlength); + textDelete = textDelete.substring(commonlength); } - } - { - // tally up the score & keep track of matches for highlighting later - if (successStrict) { - var matchesBest = matchesStrict; - var matchesBestLen = matchesStrictLen; - } else { - var matchesBest = matchesSimple; - var matchesBestLen = matchesSimpleLen; + + // Factor out any common suffixies. + commonlength = this.diffCommonSuffix(textInsert, textDelete); + if (commonlength !== 0) { + diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1]; + textInsert = textInsert.substring(0, textInsert.length - commonlength); + textDelete = textDelete.substring(0, textDelete.length - commonlength); } - var score = 0; - var lastTargetI = -1; - for (var i = 0; i < searchLen; ++i) { - var targetI = matchesBest[i]; - // score only goes down if they're not consecutive - if (lastTargetI !== targetI - 1) score -= targetI; - lastTargetI = targetI; - } - if (!successStrict) { - score *= 1000; - if (typoSimpleI !== 0) score += -20; /*typoPenalty*/ - } else { - if (typoStrictI !== 0) score += -20; /*typoPenalty*/ - } - - score -= targetLen - searchLen; - prepared.score = score; - prepared.indexes = new Array(matchesBestLen); - for (var i = matchesBestLen - 1; i >= 0; --i) { - prepared.indexes[i] = matchesBest[i]; - } - return prepared; } - }, - algorithmNoTypo: function algorithmNoTypo(searchLowerCodes, prepared, searchLowerCode) { - var targetLowerCodes = prepared._targetLowerCodes; - var searchLen = searchLowerCodes.length; - var targetLen = targetLowerCodes.length; - var searchI = 0; // where we at - var targetI = 0; // where you at - var matchesSimpleLen = 0; - // very basic fuzzy match; to remove non-matching targets ASAP! - // walk through target. find sequential matches. - // if all chars aren't found then exit - for (;;) { - var isMatch = searchLowerCode === targetLowerCodes[targetI]; - if (isMatch) { - matchesSimple[matchesSimpleLen++] = targetI; - ++searchI; - if (searchI === searchLen) break; - searchLowerCode = searchLowerCodes[searchI]; - } - ++targetI; - if (targetI >= targetLen) return null; // Failed to find searchI + // Delete the offending records and add the merged ones. + if (countDelete === 0) { + diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]); + } else if (countInsert === 0) { + diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]); + } else { + diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]); } + pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1; + } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + countInsert = 0; + countDelete = 0; + textDelete = ''; + textInsert = ''; + break; + } + } + if (diffs[diffs.length - 1][1] === '') { + diffs.pop(); // Remove the dummy entry at the end. + } - var searchI = 0; - var successStrict = false; - var matchesStrictLen = 0; - var nextBeginningIndexes = prepared._nextBeginningIndexes; - if (nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target); - targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; - - // Our target string successfully matched all characters in sequence! - // Let's try a more advanced and strict test to improve the score - // only count it as a match if it's consecutive or a beginning character! - if (targetI !== targetLen) for (;;) { - if (targetI >= targetLen) { - // We failed to find a good spot for this search char, go back to the previous search char and force it forward - if (searchI <= 0) break; // We failed to push chars forward for a better match + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + var changes = false; + pointer = 1; - --searchI; - var lastMatch = matchesStrict[--matchesStrictLen]; - targetI = nextBeginningIndexes[lastMatch]; - } else { - var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI]; - if (isMatch) { - matchesStrict[matchesStrictLen++] = targetI; - ++searchI; - if (searchI === searchLen) { - successStrict = true; - break; - } - ++targetI; - } else { - targetI = nextBeginningIndexes[targetI]; - } - } - } - { - // tally up the score & keep track of matches for highlighting later - if (successStrict) { - var matchesBest = matchesStrict; - var matchesBestLen = matchesStrictLen; - } else { - var matchesBest = matchesSimple; - var matchesBestLen = matchesSimpleLen; - } - var score = 0; - var lastTargetI = -1; - for (var i = 0; i < searchLen; ++i) { - var targetI = matchesBest[i]; - // score only goes down if they're not consecutive - if (lastTargetI !== targetI - 1) score -= targetI; - lastTargetI = targetI; - } - if (!successStrict) score *= 1000; - score -= targetLen - searchLen; - prepared.score = score; - prepared.indexes = new Array(matchesBestLen); - for (var i = matchesBestLen - 1; i >= 0; --i) { - prepared.indexes[i] = matchesBest[i]; - } - return prepared; - } - }, - prepareLowerCodes: function prepareLowerCodes(str) { - var strLen = str.length; - var lowerCodes = []; // new Array(strLen) sparse array is too slow - var lower = str.toLowerCase(); - for (var i = 0; i < strLen; ++i) { - lowerCodes[i] = lower.charCodeAt(i); - } - return lowerCodes; - }, - prepareBeginningIndexes: function prepareBeginningIndexes(target) { - var targetLen = target.length; - var beginningIndexes = []; - var beginningIndexesLen = 0; - var wasUpper = false; - var wasAlphanum = false; - for (var i = 0; i < targetLen; ++i) { - var targetCode = target.charCodeAt(i); - var isUpper = targetCode >= 65 && targetCode <= 90; - var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57; - var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum; - wasUpper = isUpper; - wasAlphanum = isAlphanum; - if (isBeginning) beginningIndexes[beginningIndexesLen++] = i; - } - return beginningIndexes; - }, - prepareNextBeginningIndexes: function prepareNextBeginningIndexes(target) { - var targetLen = target.length; - var beginningIndexes = fuzzysort.prepareBeginningIndexes(target); - var nextBeginningIndexes = []; // new Array(targetLen) sparse array is too slow - var lastIsBeginning = beginningIndexes[0]; - var lastIsBeginningI = 0; - for (var i = 0; i < targetLen; ++i) { - if (lastIsBeginning > i) { - nextBeginningIndexes[i] = lastIsBeginning; - } else { - lastIsBeginning = beginningIndexes[++lastIsBeginningI]; - nextBeginningIndexes[i] = lastIsBeginning === undefined ? targetLen : lastIsBeginning; - } - } - return nextBeginningIndexes; - }, - cleanup: cleanup, - new: fuzzysortNew - }; - return fuzzysort; - } // fuzzysortNew + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { + var diffPointer = diffs[pointer][1]; + var position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length); - // This stuff is outside fuzzysortNew, because it's shared with instances of fuzzysort.new() - var isNode = typeof commonjsRequire !== 'undefined' && typeof window === 'undefined'; - var MyMap = typeof Map === 'function' ? Map : function () { - var s = Object.create(null); - this.get = function (k) { - return s[k]; - }; - this.set = function (k, val) { - s[k] = val; - return this; - }; - this.clear = function () { - s = Object.create(null); - }; - }; - var preparedCache = new MyMap(); - var preparedSearchCache = new MyMap(); - var noResults = []; - noResults.total = 0; - var matchesSimple = []; - var matchesStrict = []; - function cleanup() { - preparedCache.clear(); - preparedSearchCache.clear(); - matchesSimple = []; - matchesStrict = []; - } - function defaultScoreFn(a) { - var max = -9007199254740991; - for (var i = a.length - 1; i >= 0; --i) { - var result = a[i]; - if (result === null) continue; - var score = result.score; - if (score > max) max = score; + // This is a single edit surrounded by equalities. + if (position === diffs[pointer - 1][1]) { + // Shift the edit over the previous equality. + diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; } - if (max === -9007199254740991) return null; - return max; } + pointer++; + } - // prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop] - // prop = 'key1.key2' 10ms - // prop = ['key1', 'key2'] 27ms - function getValue(obj, prop) { - var tmp = obj[prop]; - if (tmp !== undefined) return tmp; - var segs = prop; - if (!Array.isArray(prop)) segs = prop.split('.'); - var len = segs.length; - var i = -1; - while (obj && ++i < len) { - obj = obj[segs[i]]; - } - return obj; - } - function isObj(x) { - return _typeof(x) === 'object'; - } // faster as a function + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + this.diffCleanupMerge(diffs); + } + }; + function diff(o, n) { + var diff, output, text; + diff = new DiffMatchPatch(); + output = diff.DiffMain(o, n); + diff.diffCleanupEfficiency(output); + text = diff.diffPrettyHtml(output); + return text; + } - // Hacked version of https://github.com/lemire/FastPriorityQueue.js - var fastpriorityqueue = function fastpriorityqueue() { - var r = [], - o = 0, - e = {}; - function n() { - for (var e = 0, n = r[e], c = 1; c < o;) { - var f = c + 1; - e = c, f < o && r[f].score < r[c].score && (e = f), r[e - 1 >> 1] = r[e], c = 1 + (e << 1); - } - for (var a = e - 1 >> 1; e > 0 && n.score < r[a].score; a = (e = a) - 1 >> 1) { - r[e] = r[a]; - } - r[e] = n; - } - return e.add = function (e) { - var n = o; - r[o++] = e; - for (var c = n - 1 >> 1; n > 0 && e.score < r[c].score; c = (n = c) - 1 >> 1) { - r[n] = r[c]; - } - r[n] = e; - }, e.poll = function () { - if (0 !== o) { - var e = r[0]; - return r[0] = r[--o], n(), e; - } - }, e.peek = function (e) { - if (0 !== o) return r[0]; - }, e.replaceTop = function (o) { - r[0] = o, n(); - }, e; - }; - var q = fastpriorityqueue(); // reuse this, except for async, it needs to make its own + var QUnit = {}; - return fuzzysortNew(); - }); // UMD + // The "currentModule" object would ideally be defined using the createModule() + // function. Since it isn't, add the missing suiteReport property to it now that + // we have loaded all source code required to do so. + // + // TODO: Consider defining currentModule in core.js or module.js in its entirely + // rather than partly in config.js and partly here. + config.currentModule.suiteReport = runSuite; + config.pq = new ProcessingQueue(test); + var globalStartCalled = false; + var runStarted = false; - // TODO: (performance) wasm version!? - // TODO: (performance) threads? - // TODO: (performance) avoid cache misses - // TODO: (performance) preparedCache is a memory leak - // TODO: (like sublime) backslash === forwardslash - // TODO: (like sublime) spaces: "a b" should do 2 searches 1 for a and 1 for b - // TODO: (scoring) garbage in targets that allows most searches to strict match need a penality - // TODO: (performance) idk if allowTypo is optimized - })(fuzzysort$1); - var fuzzysort = fuzzysort$1.exports; + // Figure out if we're running the tests from a server or not + QUnit.isLocal = window$1 && window$1.location && window$1.location.protocol === 'file:'; - var stats = { - failedTests: [], - defined: 0, - completed: 0 - }; + // Expose the current QUnit version + QUnit.version = '2.25.0'; + extend(QUnit, { + config: config, + diff: diff, + dump: dump, + equiv: equiv, + reporters: reporters, + hooks: hooks, + is: is, + objectType: objectType, + on: on, + onError: onWindowError, + onUncaughtException: onUncaughtException, + pushFailure: pushFailure, + assert: Assert.prototype, + module: module$1, + test: test, + // alias other test flavors for easy access + todo: test.todo, + skip: test.skip, + only: test.only, + start: function start(count) { + if (config.current) { + throw new Error('QUnit.start cannot be called inside a test context.'); + } + var globalStartAlreadyCalled = globalStartCalled; + globalStartCalled = true; + if (runStarted) { + throw new Error('Called start() while test already started running'); + } + if (globalStartAlreadyCalled || count > 1) { + throw new Error('Called start() outside of a test context too many times'); + } + if (config.autostart) { + throw new Error('Called start() outside of a test context when ' + 'QUnit.config.autostart was true'); + } - // Escape text for attribute or text content. - function escapeText(str) { - if (!str) { - return ''; + // Until we remove QUnit.load() in QUnit 3, we keep `pageLoaded`. + // It no longer serves any purpose other than to support old test runners + // that still call only QUnit.load(), or that call both it and QUnit.start(). + if (!config.pageLoaded) { + // If the test runner used `autostart = false` and is calling QUnit.start() + // to tell is their resources are ready, but the browser isn't ready yet, + // then enable autostart now, and we'll let the tests really start after + // the browser's "load" event handler calls autostart(). + config.autostart = true; + + // If we're in Node or another non-browser environment, we start now as there + // won't be any "load" event. We return early either way since autostart + // is responsible for calling scheduleBegin (avoid "beginning" twice). + if (!document) { + QUnit.autostart(); + } + return; + } + scheduleBegin(); + }, + onUnhandledRejection: function onUnhandledRejection(reason) { + Logger.warn('QUnit.onUnhandledRejection is deprecated and will be removed in QUnit 3.0.' + ' Please use QUnit.onUncaughtException instead.'); + onUncaughtException(reason); + }, + extend: function extend$1() { + Logger.warn('QUnit.extend is deprecated and will be removed in QUnit 3.0.' + ' Please use Object.assign instead.'); + + // delegate to utility implementation, which does not warn and can be used elsewhere internally + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + return extend.apply(this, args); + }, + load: function load() { + Logger.warn('QUnit.load is deprecated and will be removed in QUnit 3.0.' + ' https://qunitjs.com/api/QUnit/load/'); + QUnit.autostart(); + }, + /** + * @internal + */ + autostart: function autostart() { + config.pageLoaded = true; + + // Initialize the configuration options + // TODO: Move this to config.js in QUnit 3. + extend(config, { + started: 0, + updateRate: 1000, + autostart: true, + filter: '' + }, true); + if (!runStarted) { + config.blocking = false; + if (config.autostart) { + scheduleBegin(); + } + } + }, + stack: function stack(offset) { + offset = (offset || 0) + 2; + // Support Safari: Use temp variable to avoid TCO for consistent cross-browser result + // https://bugs.webkit.org/show_bug.cgi?id=276187 + var source = sourceFromStacktrace(offset); + return source; } + }); + registerLoggingCallbacks(QUnit); + function scheduleBegin() { + runStarted = true; - // Both single quotes and double quotes (for attributes) - return ('' + str).replace(/['"<>&]/g, function (s) { - switch (s) { - case "'": - return '''; - case '"': - return '"'; - case '<': - return '<'; - case '>': - return '>'; - case '&': - return '&'; + // Add a slight delay to allow definition of more modules and tests. + if (setTimeout$1) { + setTimeout$1(function () { + begin(); + }); + } else { + begin(); + } + } + function unblockAndAdvanceQueue() { + config.blocking = false; + config.pq.advance(); + } + function begin() { + if (config.started) { + unblockAndAdvanceQueue(); + return; + } + + // QUnit.config.reporters is considered writable between qunit.js and QUnit.start(). + // Now that QUnit.start() has been called, it is time to decide which built-in reporters + // to load. + if (config.reporters.console) { + reporters.console.init(QUnit); + } + if (config.reporters.tap) { + reporters.tap.init(QUnit); + } + + // The test run hasn't officially begun yet + // Record the time of the test run's beginning + config.started = performance.now(); + + // Delete the loose unnamed module if unused. + if (config.modules[0].name === '' && config.modules[0].tests.length === 0) { + config.modules.shift(); + } + var modulesLog = []; + for (var i = 0; i < config.modules.length; i++) { + // Don't expose the unnamed global test module to plugins. + if (config.modules[i].name !== '') { + modulesLog.push({ + name: config.modules[i].name, + moduleId: config.modules[i].moduleId, + // Added in QUnit 1.16.0 for internal use by html-reporter, + // but no longer used since QUnit 2.7.0. + // @deprecated Kept unofficially to be removed in QUnit 3.0. + tests: config.modules[i].tests + }); } - }); + } + + // The test run is officially beginning now + emit('runStart', runSuite.start(true)); + runLoggingCallbacks('begin', { + totalTests: Test.count, + modules: modulesLog + }).then(unblockAndAdvanceQueue); } + exportQUnit(QUnit); + (function () { - // Don't load the HTML Reporter on non-browser environments if (!window$1 || !document) { return; } var config = QUnit.config; - var hiddenTests = []; - var collapseNext = false; var hasOwn = Object.prototype.hasOwnProperty; - var unfilteredUrl = setUrl({ - filter: undefined, - module: undefined, - moduleId: undefined, - testId: undefined - }); - var dropdownData = null; - function trim(string) { - if (typeof string.trim === 'function') { - return string.trim(); - } else { - return string.replace(/^\s+|\s+$/g, ''); + + // Stores fixture HTML for resetting later + function storeFixture() { + // Avoid overwriting user-defined values + // TODO: Change to negative null/undefined check once declared in /src/config.js + if (hasOwn.call(config, 'fixture')) { + return; } - } - function addEvent(elem, type, fn) { - elem.addEventListener(type, fn, false); - } - function removeEvent(elem, type, fn) { - elem.removeEventListener(type, fn, false); - } - function addEvents(elems, type, fn) { - var i = elems.length; - while (i--) { - addEvent(elems[i], type, fn); + var fixture = document.getElementById('qunit-fixture'); + if (fixture) { + config.fixture = fixture.cloneNode(true); } } - function hasClass(elem, name) { - return (' ' + elem.className + ' ').indexOf(' ' + name + ' ') >= 0; - } - function addClass(elem, name) { - if (!hasClass(elem, name)) { - elem.className += (elem.className ? ' ' : '') + name; + QUnit.begin(storeFixture); + + // Resets the fixture DOM element if available. + function resetFixture() { + if (config.fixture == null) { + return; } - } - function toggleClass(elem, name, force) { - if (force || typeof force === 'undefined' && !hasClass(elem, name)) { - addClass(elem, name); + var fixture = document.getElementById('qunit-fixture'); + var resetFixtureType = _typeof(config.fixture); + if (resetFixtureType === 'string') { + // support user defined values for `config.fixture` + var newFixture = document.createElement('div'); + newFixture.setAttribute('id', 'qunit-fixture'); + newFixture.innerHTML = config.fixture; + fixture.parentNode.replaceChild(newFixture, fixture); } else { - removeClass(elem, name); + var clonedFixture = config.fixture.cloneNode(true); + fixture.parentNode.replaceChild(clonedFixture, fixture); } } - function removeClass(elem, name) { - var set = ' ' + elem.className + ' '; + QUnit.testStart(resetFixture); + })(); - // Class name may appear multiple times - while (set.indexOf(' ' + name + ' ') >= 0) { - set = set.replace(' ' + name + ' ', ' '); - } + (function () { + // Only interact with URLs via window.location + var location = typeof window$1 !== 'undefined' && window$1.location; + if (!location) { + return; + } + var urlParams = getUrlParams(); - // Trim for prettiness - elem.className = trim(set); + // TODO: Move to /src/core/ in QUnit 3 + // TODO: Document this as public API (read-only) + QUnit.urlParams = urlParams; + + // TODO: Move to /src/core/config.js in QUnit 3, + // in accordance with /docs/api/config.index.md#order + QUnit.config.filter = urlParams.filter; + // NOTE: Based on readFlatPreconfigNumber from QUnit 3. + if (/^[0-9]+$/.test(urlParams.maxDepth)) { + QUnit.config.maxDepth = QUnit.dump.maxDepth = +urlParams.maxDepth; } - function id(name) { - return document.getElementById && document.getElementById(name); + QUnit.config.module = urlParams.module; + QUnit.config.moduleId = [].concat(urlParams.moduleId || []); + QUnit.config.testId = [].concat(urlParams.testId || []); + + // Test order randomization + // Generate a random seed if `?seed` is specified without a value (boolean true), + // or when set to the string "true". + if (urlParams.seed === 'true' || urlParams.seed === true) { + // NOTE: This duplicates logic from /src/core/config.js. Consolidated in QUnit 3. + QUnit.config.seed = (Math.random().toString(36) + '0000000000').slice(2, 12); + } else if (urlParams.seed) { + QUnit.config.seed = urlParams.seed; } - function abortTests() { - var abortButton = id('qunit-abort-tests-button'); - if (abortButton) { - abortButton.disabled = true; - abortButton.innerHTML = 'Aborting...'; - } - QUnit.config.queue.length = 0; - return false; - } - function interceptNavigation(ev) { - // Trim potential accidental whitespace so that QUnit doesn't throw an error about no tests matching the filter. - var filterInputElem = id('qunit-filter-input'); - filterInputElem.value = trim(filterInputElem.value); - applyUrlParams(); - if (ev && ev.preventDefault) { - ev.preventDefault(); - } - return false; - } - function getUrlConfigHtml() { - var selection = false; - var urlConfig = config.urlConfig; - var urlConfigHtml = ''; + + // Add URL-parameter-mapped config values with UI form rendering data + QUnit.config.urlConfig.push({ + id: 'hidepassed', + label: 'Hide passed tests', + tooltip: 'Only show tests and assertions that fail. Stored as query-strings.' + }, { + id: 'noglobals', + label: 'Check for Globals', + tooltip: 'Enabling this will test if any test introduces new properties on the ' + 'global object (`window` in Browsers). Stored as query-strings.' + }, { + id: 'notrycatch', + label: 'No try-catch', + tooltip: 'Enabling this will run tests outside of a try-catch block. Makes debugging ' + 'exceptions in IE reasonable. Stored as query-strings.' + }); + QUnit.begin(function () { + var urlConfig = QUnit.config.urlConfig; for (var i = 0; i < urlConfig.length; i++) { // Options can be either strings or objects with nonempty "id" properties - var val = config.urlConfig[i]; - if (typeof val === 'string') { - val = { - id: val, - label: val - }; + var option = QUnit.config.urlConfig[i]; + if (typeof option !== 'string') { + option = option.id; } - var escaped = escapeText(val.id); - var escapedTooltip = escapeText(val.tooltip); - if (!val.value || typeof val.value === 'string') { - urlConfigHtml += "'; - } else { - urlConfigHtml += "'; + if (QUnit.config[option] === undefined) { + QUnit.config[option] = urlParams[option]; } } - return urlConfigHtml; - } - - // Handle "click" events on toolbar checkboxes and "change" for select menus. - // Updates the URL with the new state of `config.urlConfig` values. - function toolbarChanged() { - var field = this; - var params = {}; - - // Detect if field is a select menu or a checkbox - var value; - if ('selectedIndex' in field) { - value = field.options[field.selectedIndex].value || undefined; - } else { - value = field.checked ? field.defaultValue || true : undefined; - } - params[field.name] = value; - var updatedUrl = setUrl(params); + }); + function getUrlParams() { + var urlParams = Object.create(null); + var params = location.search.slice(1).split('&'); + var length = params.length; + for (var i = 0; i < length; i++) { + if (params[i]) { + var param = params[i].split('='); + var name = decodeQueryParam(param[0]); - // Check if we can apply the change without a page refresh - if (field.name === 'hidepassed' && 'replaceState' in window$1.history) { - QUnit.urlParams[field.name] = value; - config[field.name] = value || false; - var tests = id('qunit-tests'); - if (tests) { - var length = tests.children.length; - var children = tests.children; - if (field.checked) { - for (var i = 0; i < length; i++) { - var test = children[i]; - var className = test ? test.className : ''; - var classNameHasPass = className.indexOf('pass') > -1; - var classNameHasSkipped = className.indexOf('skipped') > -1; - if (classNameHasPass || classNameHasSkipped) { - hiddenTests.push(test); - } - } - var _iterator = _createForOfIteratorHelper(hiddenTests), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var hiddenTest = _step.value; - tests.removeChild(hiddenTest); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } + // Allow just a key to turn on a flag, e.g., test.html?noglobals + var value = param.length === 1 || decodeQueryParam(param.slice(1).join('=')); + if (name in urlParams) { + urlParams[name] = [].concat(urlParams[name], value); } else { - var _test; - while ((_test = hiddenTests.pop()) != null) { - tests.appendChild(_test); - } - } - } - window$1.history.replaceState(null, '', updatedUrl); - } else { - window$1.location = updatedUrl; - } - } - function setUrl(params) { - var querystring = '?'; - var location = window$1.location; - params = extend(extend({}, QUnit.urlParams), params); - for (var key in params) { - // Skip inherited or undefined properties - if (hasOwn.call(params, key) && params[key] !== undefined) { - // Output a parameter for each value of this key - // (but usually just one) - var arrValue = [].concat(params[key]); - for (var i = 0; i < arrValue.length; i++) { - querystring += encodeURIComponent(key); - if (arrValue[i] !== true) { - querystring += '=' + encodeURIComponent(arrValue[i]); - } - querystring += '&'; + urlParams[name] = value; } } } - return location.protocol + '//' + location.host + location.pathname + querystring.slice(0, -1); - } - function applyUrlParams() { - var filter = id('qunit-filter-input').value; - window$1.location = setUrl({ - filter: filter === '' ? undefined : filter, - moduleId: _toConsumableArray(dropdownData.selectedMap.keys()), - // Remove module and testId filter - module: undefined, - testId: undefined - }); - } - function toolbarUrlConfigContainer() { - var urlConfigContainer = document.createElement('span'); - urlConfigContainer.innerHTML = getUrlConfigHtml(); - addClass(urlConfigContainer, 'qunit-url-config'); - addEvents(urlConfigContainer.getElementsByTagName('input'), 'change', toolbarChanged); - addEvents(urlConfigContainer.getElementsByTagName('select'), 'change', toolbarChanged); - return urlConfigContainer; - } - function abortTestsButton() { - var button = document.createElement('button'); - button.id = 'qunit-abort-tests-button'; - button.innerHTML = 'Abort'; - addEvent(button, 'click', abortTests); - return button; - } - function toolbarLooseFilter() { - var filter = document.createElement('form'); - var label = document.createElement('label'); - var input = document.createElement('input'); - var button = document.createElement('button'); - addClass(filter, 'qunit-filter'); - label.innerHTML = 'Filter: '; - input.type = 'text'; - input.value = config.filter || ''; - input.name = 'filter'; - input.id = 'qunit-filter-input'; - button.innerHTML = 'Go'; - label.appendChild(input); - filter.appendChild(label); - filter.appendChild(document.createTextNode(' ')); - filter.appendChild(button); - addEvent(filter, 'submit', interceptNavigation); - return filter; + return urlParams; } - function createModuleListItem(moduleId, name, checked) { - return '
  • '; + function decodeQueryParam(param) { + return decodeURIComponent(param.replace(/\+/g, '%20')); } + })(); - /** - * @param {Array} Results from fuzzysort - * @return {string} HTML - */ - function moduleListHtml(results) { - var html = ''; + var fuzzysort$1 = {exports: {}}; - // Hoist the already selected items, and show them always - // even if not matched by the current search. - dropdownData.selectedMap.forEach(function (name, moduleId) { - html += createModuleListItem(moduleId, name, true); - }); - for (var i = 0; i < results.length; i++) { - var mod = results[i].obj; - if (!dropdownData.selectedMap.has(mod.moduleId)) { - html += createModuleListItem(mod.moduleId, mod.name, false); - } - } - return html; - } - function toolbarModuleFilter(beginDetails) { - var initialSelected = null; - dropdownData = { - options: beginDetails.modules.slice(), - selectedMap: new StringMap(), - isDirty: function isDirty() { - return _toConsumableArray(dropdownData.selectedMap.keys()).sort().join(',') !== _toConsumableArray(initialSelected.keys()).sort().join(','); - } - }; - if (config.moduleId.length) { - // The module dropdown is seeded with the runtime configuration of the last run. - // - // We don't reference `config.moduleId` directly after this and keep our own - // copy because: - // 1. This naturally filters out unknown moduleIds. - // 2. Gives us a place to manage and remember unsubmitted checkbox changes. - // 3. Gives us an efficient way to map a selected moduleId to module name - // during rendering. - for (var i = 0; i < beginDetails.modules.length; i++) { - var mod = beginDetails.modules[i]; - if (config.moduleId.indexOf(mod.moduleId) !== -1) { - dropdownData.selectedMap.set(mod.moduleId, mod.name); - } - } - } - initialSelected = new StringMap(dropdownData.selectedMap); - var moduleSearch = document.createElement('input'); - moduleSearch.id = 'qunit-modulefilter-search'; - moduleSearch.autocomplete = 'off'; - addEvent(moduleSearch, 'input', searchInput); - addEvent(moduleSearch, 'input', searchFocus); - addEvent(moduleSearch, 'focus', searchFocus); - addEvent(moduleSearch, 'click', searchFocus); - var label = document.createElement('label'); - label.htmlFor = 'qunit-modulefilter-search'; - label.textContent = 'Module:'; - var searchContainer = document.createElement('span'); - searchContainer.id = 'qunit-modulefilter-search-container'; - searchContainer.appendChild(moduleSearch); - var applyButton = document.createElement('button'); - applyButton.textContent = 'Apply'; - applyButton.title = 'Re-run the selected test modules'; - addEvent(applyButton, 'click', applyUrlParams); - var resetButton = document.createElement('button'); - resetButton.textContent = 'Reset'; - resetButton.type = 'reset'; - resetButton.title = 'Restore the previous module selection'; - var clearButton = document.createElement('button'); - clearButton.textContent = 'Select none'; - clearButton.type = 'button'; - clearButton.title = 'Clear the current module selection'; - addEvent(clearButton, 'click', function () { - dropdownData.selectedMap.clear(); - selectionChange(); - searchInput(); - }); - var actions = document.createElement('span'); - actions.id = 'qunit-modulefilter-actions'; - actions.appendChild(applyButton); - actions.appendChild(resetButton); - if (initialSelected.size) { - // Only show clear button if functionally different from reset - actions.appendChild(clearButton); - } - var dropDownList = document.createElement('ul'); - dropDownList.id = 'qunit-modulefilter-dropdown-list'; - var dropDown = document.createElement('div'); - dropDown.id = 'qunit-modulefilter-dropdown'; - dropDown.style.display = 'none'; - dropDown.appendChild(actions); - dropDown.appendChild(dropDownList); - addEvent(dropDown, 'change', selectionChange); - searchContainer.appendChild(dropDown); - // Set initial moduleSearch.placeholder and clearButton/resetButton. - selectionChange(); - var moduleFilter = document.createElement('form'); - moduleFilter.id = 'qunit-modulefilter'; - moduleFilter.appendChild(label); - moduleFilter.appendChild(document.createTextNode(' ')); - moduleFilter.appendChild(searchContainer); - addEvent(moduleFilter, 'submit', interceptNavigation); - addEvent(moduleFilter, 'reset', function () { - dropdownData.selectedMap = new StringMap(initialSelected); - // Set moduleSearch.placeholder and reflect non-dirty state - selectionChange(); - searchInput(); - }); + (function (module) { + (function (root, UMD) { + if (module.exports) module.exports = UMD();else root.fuzzysort = UMD(); + })(commonjsGlobal, function UMD() { + function fuzzysortNew(instanceOptions) { + var fuzzysort = { + single: function single(search, target, options) { + if (search == 'farzher') return { + target: "farzher was here (^-^*)/", + score: 0, + indexes: [0, 1, 2, 3, 4, 5, 6] + }; + if (!search) return null; + if (!isObj(search)) search = fuzzysort.getPreparedSearch(search); + if (!target) return null; + if (!isObj(target)) target = fuzzysort.getPrepared(target); + var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true; + var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; + return algorithm(search, target, search[0]); + }, + go: function go(search, targets, options) { + if (search == 'farzher') return [{ + target: "farzher was here (^-^*)/", + score: 0, + indexes: [0, 1, 2, 3, 4, 5, 6], + obj: targets ? targets[0] : null + }]; + if (!search) return noResults; + search = fuzzysort.prepareSearch(search); + var searchLowerCode = search[0]; + var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991; + var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991; + var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true; + var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; + var resultsLen = 0; + var limitedCount = 0; + var targetsLen = targets.length; + + // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] + + // options.keys + if (options && options.keys) { + var scoreFn = options.scoreFn || defaultScoreFn; + var keys = options.keys; + var keysLen = keys.length; + for (var i = targetsLen - 1; i >= 0; --i) { + var obj = targets[i]; + var objResults = new Array(keysLen); + for (var keyI = keysLen - 1; keyI >= 0; --keyI) { + var key = keys[keyI]; + var target = getValue(obj, key); + if (!target) { + objResults[keyI] = null; + continue; + } + if (!isObj(target)) target = fuzzysort.getPrepared(target); + objResults[keyI] = algorithm(search, target, searchLowerCode); + } + objResults.obj = obj; // before scoreFn so scoreFn can use it + var score = scoreFn(objResults); + if (score === null) continue; + if (score < threshold) continue; + objResults.score = score; + if (resultsLen < limit) { + q.add(objResults); + ++resultsLen; + } else { + ++limitedCount; + if (score > q.peek().score) q.replaceTop(objResults); + } + } + + // options.key + } else if (options && options.key) { + var key = options.key; + for (var i = targetsLen - 1; i >= 0; --i) { + var obj = targets[i]; + var target = getValue(obj, key); + if (!target) continue; + if (!isObj(target)) target = fuzzysort.getPrepared(target); + var result = algorithm(search, target, searchLowerCode); + if (result === null) continue; + if (result.score < threshold) continue; + + // have to clone result so duplicate targets from different obj can each reference the correct obj + result = { + target: result.target, + _targetLowerCodes: null, + _nextBeginningIndexes: null, + score: result.score, + indexes: result.indexes, + obj: obj + }; // hidden + + if (resultsLen < limit) { + q.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result.score > q.peek().score) q.replaceTop(result); + } + } + + // no keys + } else { + for (var i = targetsLen - 1; i >= 0; --i) { + var target = targets[i]; + if (!target) continue; + if (!isObj(target)) target = fuzzysort.getPrepared(target); + var result = algorithm(search, target, searchLowerCode); + if (result === null) continue; + if (result.score < threshold) continue; + if (resultsLen < limit) { + q.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result.score > q.peek().score) q.replaceTop(result); + } + } + } + if (resultsLen === 0) return noResults; + var results = new Array(resultsLen); + for (var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll(); + results.total = resultsLen + limitedCount; + return results; + }, + goAsync: function goAsync(search, targets, options) { + var canceled = false; + var p = new Promise(function (resolve, reject) { + if (search == 'farzher') return resolve([{ + target: "farzher was here (^-^*)/", + score: 0, + indexes: [0, 1, 2, 3, 4, 5, 6], + obj: targets ? targets[0] : null + }]); + if (!search) return resolve(noResults); + search = fuzzysort.prepareSearch(search); + var searchLowerCode = search[0]; + var q = fastpriorityqueue(); + var iCurrent = targets.length - 1; + var threshold = options && options.threshold || instanceOptions && instanceOptions.threshold || -9007199254740991; + var limit = options && options.limit || instanceOptions && instanceOptions.limit || 9007199254740991; + var allowTypo = options && options.allowTypo !== undefined ? options.allowTypo : instanceOptions && instanceOptions.allowTypo !== undefined ? instanceOptions.allowTypo : true; + var algorithm = allowTypo ? fuzzysort.algorithm : fuzzysort.algorithmNoTypo; + var resultsLen = 0; + var limitedCount = 0; + function step() { + if (canceled) return reject('canceled'); + var startMs = Date.now(); + + // This code is copy/pasted 3 times for performance reasons [options.keys, options.key, no keys] + + // options.keys + if (options && options.keys) { + var scoreFn = options.scoreFn || defaultScoreFn; + var keys = options.keys; + var keysLen = keys.length; + for (; iCurrent >= 0; --iCurrent) { + if (iCurrent % 1000 /*itemsPerCheck*/ === 0) { + if (Date.now() - startMs >= 10 /*asyncInterval*/) { + isNode ? setImmediate(step) : setTimeout(step); + return; + } + } + var obj = targets[iCurrent]; + var objResults = new Array(keysLen); + for (var keyI = keysLen - 1; keyI >= 0; --keyI) { + var key = keys[keyI]; + var target = getValue(obj, key); + if (!target) { + objResults[keyI] = null; + continue; + } + if (!isObj(target)) target = fuzzysort.getPrepared(target); + objResults[keyI] = algorithm(search, target, searchLowerCode); + } + objResults.obj = obj; // before scoreFn so scoreFn can use it + var score = scoreFn(objResults); + if (score === null) continue; + if (score < threshold) continue; + objResults.score = score; + if (resultsLen < limit) { + q.add(objResults); + ++resultsLen; + } else { + ++limitedCount; + if (score > q.peek().score) q.replaceTop(objResults); + } + } + + // options.key + } else if (options && options.key) { + var key = options.key; + for (; iCurrent >= 0; --iCurrent) { + if (iCurrent % 1000 /*itemsPerCheck*/ === 0) { + if (Date.now() - startMs >= 10 /*asyncInterval*/) { + isNode ? setImmediate(step) : setTimeout(step); + return; + } + } + var obj = targets[iCurrent]; + var target = getValue(obj, key); + if (!target) continue; + if (!isObj(target)) target = fuzzysort.getPrepared(target); + var result = algorithm(search, target, searchLowerCode); + if (result === null) continue; + if (result.score < threshold) continue; + + // have to clone result so duplicate targets from different obj can each reference the correct obj + result = { + target: result.target, + _targetLowerCodes: null, + _nextBeginningIndexes: null, + score: result.score, + indexes: result.indexes, + obj: obj + }; // hidden + + if (resultsLen < limit) { + q.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result.score > q.peek().score) q.replaceTop(result); + } + } + + // no keys + } else { + for (; iCurrent >= 0; --iCurrent) { + if (iCurrent % 1000 /*itemsPerCheck*/ === 0) { + if (Date.now() - startMs >= 10 /*asyncInterval*/) { + isNode ? setImmediate(step) : setTimeout(step); + return; + } + } + var target = targets[iCurrent]; + if (!target) continue; + if (!isObj(target)) target = fuzzysort.getPrepared(target); + var result = algorithm(search, target, searchLowerCode); + if (result === null) continue; + if (result.score < threshold) continue; + if (resultsLen < limit) { + q.add(result); + ++resultsLen; + } else { + ++limitedCount; + if (result.score > q.peek().score) q.replaceTop(result); + } + } + } + if (resultsLen === 0) return resolve(noResults); + var results = new Array(resultsLen); + for (var i = resultsLen - 1; i >= 0; --i) results[i] = q.poll(); + results.total = resultsLen + limitedCount; + resolve(results); + } + isNode ? setImmediate(step) : step(); //setTimeout here is too slow + }); + p.cancel = function () { + canceled = true; + }; + return p; + }, + highlight: function highlight(result, hOpen, hClose) { + if (typeof hOpen == 'function') return fuzzysort.highlightCallback(result, hOpen); + if (result === null) return null; + if (hOpen === undefined) hOpen = ''; + if (hClose === undefined) hClose = ''; + var highlighted = ''; + var matchesIndex = 0; + var opened = false; + var target = result.target; + var targetLen = target.length; + var matchesBest = result.indexes; + for (var i = 0; i < targetLen; ++i) { + var char = target[i]; + if (matchesBest[matchesIndex] === i) { + ++matchesIndex; + if (!opened) { + opened = true; + highlighted += hOpen; + } + if (matchesIndex === matchesBest.length) { + highlighted += char + hClose + target.substr(i + 1); + break; + } + } else { + if (opened) { + opened = false; + highlighted += hClose; + } + } + highlighted += char; + } + return highlighted; + }, + highlightCallback: function highlightCallback(result, cb) { + if (result === null) return null; + var target = result.target; + var targetLen = target.length; + var indexes = result.indexes; + var highlighted = ''; + var matchI = 0; + var indexesI = 0; + var opened = false; + var result = []; + for (var i = 0; i < targetLen; ++i) { + var char = target[i]; + if (indexes[indexesI] === i) { + ++indexesI; + if (!opened) { + opened = true; + result.push(highlighted); + highlighted = ''; + } + if (indexesI === indexes.length) { + highlighted += char; + result.push(cb(highlighted, matchI++)); + highlighted = ''; + result.push(target.substr(i + 1)); + break; + } + } else { + if (opened) { + opened = false; + result.push(cb(highlighted, matchI++)); + highlighted = ''; + } + } + highlighted += char; + } + return result; + }, + prepare: function prepare(target) { + if (!target) return { + target: '', + _targetLowerCodes: [0 /*this 0 doesn't make sense. here because an empty array causes the algorithm to deoptimize and run 50% slower!*/], + _nextBeginningIndexes: null, + score: null, + indexes: null, + obj: null + }; // hidden + return { + target: target, + _targetLowerCodes: fuzzysort.prepareLowerCodes(target), + _nextBeginningIndexes: null, + score: null, + indexes: null, + obj: null + }; // hidden + }, + prepareSlow: function prepareSlow(target) { + if (!target) return { + target: '', + _targetLowerCodes: [0 /*this 0 doesn't make sense. here because an empty array causes the algorithm to deoptimize and run 50% slower!*/], + _nextBeginningIndexes: null, + score: null, + indexes: null, + obj: null + }; // hidden + return { + target: target, + _targetLowerCodes: fuzzysort.prepareLowerCodes(target), + _nextBeginningIndexes: fuzzysort.prepareNextBeginningIndexes(target), + score: null, + indexes: null, + obj: null + }; // hidden + }, + prepareSearch: function prepareSearch(search) { + if (!search) search = ''; + return fuzzysort.prepareLowerCodes(search); + }, + // Below this point is only internal code + // Below this point is only internal code + // Below this point is only internal code + // Below this point is only internal code + + getPrepared: function getPrepared(target) { + if (target.length > 999) return fuzzysort.prepare(target); // don't cache huge targets + var targetPrepared = preparedCache.get(target); + if (targetPrepared !== undefined) return targetPrepared; + targetPrepared = fuzzysort.prepare(target); + preparedCache.set(target, targetPrepared); + return targetPrepared; + }, + getPreparedSearch: function getPreparedSearch(search) { + if (search.length > 999) return fuzzysort.prepareSearch(search); // don't cache huge searches + var searchPrepared = preparedSearchCache.get(search); + if (searchPrepared !== undefined) return searchPrepared; + searchPrepared = fuzzysort.prepareSearch(search); + preparedSearchCache.set(search, searchPrepared); + return searchPrepared; + }, + algorithm: function algorithm(searchLowerCodes, prepared, searchLowerCode) { + var targetLowerCodes = prepared._targetLowerCodes; + var searchLen = searchLowerCodes.length; + var targetLen = targetLowerCodes.length; + var searchI = 0; // where we at + var targetI = 0; // where you at + var typoSimpleI = 0; + var matchesSimpleLen = 0; - // Enables show/hide for the dropdown - function searchFocus() { - if (dropDown.style.display !== 'none') { - return; - } + // very basic fuzzy match; to remove non-matching targets ASAP! + // walk through target. find sequential matches. + // if all chars aren't found then exit + for (;;) { + var isMatch = searchLowerCode === targetLowerCodes[targetI]; + if (isMatch) { + matchesSimple[matchesSimpleLen++] = targetI; + ++searchI; + if (searchI === searchLen) break; + searchLowerCode = searchLowerCodes[typoSimpleI === 0 ? searchI : typoSimpleI === searchI ? searchI + 1 : typoSimpleI === searchI - 1 ? searchI - 1 : searchI]; + } + ++targetI; + if (targetI >= targetLen) { + // Failed to find searchI + // Check for typo or exit + // we go as far as possible before trying to transpose + // then we transpose backwards until we reach the beginning + for (;;) { + if (searchI <= 1) return null; // not allowed to transpose first char + if (typoSimpleI === 0) { + // we haven't tried to transpose yet + --searchI; + var searchLowerCodeNew = searchLowerCodes[searchI]; + if (searchLowerCode === searchLowerCodeNew) continue; // doesn't make sense to transpose a repeat char + typoSimpleI = searchI; + } else { + if (typoSimpleI === 1) return null; // reached the end of the line for transposing + --typoSimpleI; + searchI = typoSimpleI; + searchLowerCode = searchLowerCodes[searchI + 1]; + var searchLowerCodeNew = searchLowerCodes[searchI]; + if (searchLowerCode === searchLowerCodeNew) continue; // doesn't make sense to transpose a repeat char + } + matchesSimpleLen = searchI; + targetI = matchesSimple[matchesSimpleLen - 1] + 1; + break; + } + } + } + var searchI = 0; + var typoStrictI = 0; + var successStrict = false; + var matchesStrictLen = 0; + var nextBeginningIndexes = prepared._nextBeginningIndexes; + if (nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target); + var firstPossibleI = targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; - // Optimization: Defer rendering options until focussed. - // https://github.com/qunitjs/qunit/issues/1664 - searchInput(); - dropDown.style.display = 'block'; + // Our target string successfully matched all characters in sequence! + // Let's try a more advanced and strict test to improve the score + // only count it as a match if it's consecutive or a beginning character! + if (targetI !== targetLen) for (;;) { + if (targetI >= targetLen) { + // We failed to find a good spot for this search char, go back to the previous search char and force it forward + if (searchI <= 0) { + // We failed to push chars forward for a better match + // transpose, starting from the beginning + ++typoStrictI; + if (typoStrictI > searchLen - 2) break; + if (searchLowerCodes[typoStrictI] === searchLowerCodes[typoStrictI + 1]) continue; // doesn't make sense to transpose a repeat char + targetI = firstPossibleI; + continue; + } + --searchI; + var lastMatch = matchesStrict[--matchesStrictLen]; + targetI = nextBeginningIndexes[lastMatch]; + } else { + var isMatch = searchLowerCodes[typoStrictI === 0 ? searchI : typoStrictI === searchI ? searchI + 1 : typoStrictI === searchI - 1 ? searchI - 1 : searchI] === targetLowerCodes[targetI]; + if (isMatch) { + matchesStrict[matchesStrictLen++] = targetI; + ++searchI; + if (searchI === searchLen) { + successStrict = true; + break; + } + ++targetI; + } else { + targetI = nextBeginningIndexes[targetI]; + } + } + } + { + // tally up the score & keep track of matches for highlighting later + if (successStrict) { + var matchesBest = matchesStrict; + var matchesBestLen = matchesStrictLen; + } else { + var matchesBest = matchesSimple; + var matchesBestLen = matchesSimpleLen; + } + var score = 0; + var lastTargetI = -1; + for (var i = 0; i < searchLen; ++i) { + var targetI = matchesBest[i]; + // score only goes down if they're not consecutive + if (lastTargetI !== targetI - 1) score -= targetI; + lastTargetI = targetI; + } + if (!successStrict) { + score *= 1000; + if (typoSimpleI !== 0) score += -20; /*typoPenalty*/ + } else { + if (typoStrictI !== 0) score += -20; /*typoPenalty*/ + } + score -= targetLen - searchLen; + prepared.score = score; + prepared.indexes = new Array(matchesBestLen); + for (var i = matchesBestLen - 1; i >= 0; --i) prepared.indexes[i] = matchesBest[i]; + return prepared; + } + }, + algorithmNoTypo: function algorithmNoTypo(searchLowerCodes, prepared, searchLowerCode) { + var targetLowerCodes = prepared._targetLowerCodes; + var searchLen = searchLowerCodes.length; + var targetLen = targetLowerCodes.length; + var searchI = 0; // where we at + var targetI = 0; // where you at + var matchesSimpleLen = 0; - // Hide on Escape keydown or on click outside the container - addEvent(document, 'click', hideHandler); - addEvent(document, 'keydown', hideHandler); - function hideHandler(e) { - var inContainer = moduleFilter.contains(e.target); - if (e.keyCode === 27 || !inContainer) { - if (e.keyCode === 27 && inContainer) { - moduleSearch.focus(); + // very basic fuzzy match; to remove non-matching targets ASAP! + // walk through target. find sequential matches. + // if all chars aren't found then exit + for (;;) { + var isMatch = searchLowerCode === targetLowerCodes[targetI]; + if (isMatch) { + matchesSimple[matchesSimpleLen++] = targetI; + ++searchI; + if (searchI === searchLen) break; + searchLowerCode = searchLowerCodes[searchI]; + } + ++targetI; + if (targetI >= targetLen) return null; // Failed to find searchI + } + var searchI = 0; + var successStrict = false; + var matchesStrictLen = 0; + var nextBeginningIndexes = prepared._nextBeginningIndexes; + if (nextBeginningIndexes === null) nextBeginningIndexes = prepared._nextBeginningIndexes = fuzzysort.prepareNextBeginningIndexes(prepared.target); + targetI = matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[matchesSimple[0] - 1]; + + // Our target string successfully matched all characters in sequence! + // Let's try a more advanced and strict test to improve the score + // only count it as a match if it's consecutive or a beginning character! + if (targetI !== targetLen) for (;;) { + if (targetI >= targetLen) { + // We failed to find a good spot for this search char, go back to the previous search char and force it forward + if (searchI <= 0) break; // We failed to push chars forward for a better match + + --searchI; + var lastMatch = matchesStrict[--matchesStrictLen]; + targetI = nextBeginningIndexes[lastMatch]; + } else { + var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI]; + if (isMatch) { + matchesStrict[matchesStrictLen++] = targetI; + ++searchI; + if (searchI === searchLen) { + successStrict = true; + break; + } + ++targetI; + } else { + targetI = nextBeginningIndexes[targetI]; + } + } + } + { + // tally up the score & keep track of matches for highlighting later + if (successStrict) { + var matchesBest = matchesStrict; + var matchesBestLen = matchesStrictLen; + } else { + var matchesBest = matchesSimple; + var matchesBestLen = matchesSimpleLen; + } + var score = 0; + var lastTargetI = -1; + for (var i = 0; i < searchLen; ++i) { + var targetI = matchesBest[i]; + // score only goes down if they're not consecutive + if (lastTargetI !== targetI - 1) score -= targetI; + lastTargetI = targetI; + } + if (!successStrict) score *= 1000; + score -= targetLen - searchLen; + prepared.score = score; + prepared.indexes = new Array(matchesBestLen); + for (var i = matchesBestLen - 1; i >= 0; --i) prepared.indexes[i] = matchesBest[i]; + return prepared; + } + }, + prepareLowerCodes: function prepareLowerCodes(str) { + var strLen = str.length; + var lowerCodes = []; // new Array(strLen) sparse array is too slow + var lower = str.toLowerCase(); + for (var i = 0; i < strLen; ++i) lowerCodes[i] = lower.charCodeAt(i); + return lowerCodes; + }, + prepareBeginningIndexes: function prepareBeginningIndexes(target) { + var targetLen = target.length; + var beginningIndexes = []; + var beginningIndexesLen = 0; + var wasUpper = false; + var wasAlphanum = false; + for (var i = 0; i < targetLen; ++i) { + var targetCode = target.charCodeAt(i); + var isUpper = targetCode >= 65 && targetCode <= 90; + var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57; + var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum; + wasUpper = isUpper; + wasAlphanum = isAlphanum; + if (isBeginning) beginningIndexes[beginningIndexesLen++] = i; + } + return beginningIndexes; + }, + prepareNextBeginningIndexes: function prepareNextBeginningIndexes(target) { + var targetLen = target.length; + var beginningIndexes = fuzzysort.prepareBeginningIndexes(target); + var nextBeginningIndexes = []; // new Array(targetLen) sparse array is too slow + var lastIsBeginning = beginningIndexes[0]; + var lastIsBeginningI = 0; + for (var i = 0; i < targetLen; ++i) { + if (lastIsBeginning > i) { + nextBeginningIndexes[i] = lastIsBeginning; + } else { + lastIsBeginning = beginningIndexes[++lastIsBeginningI]; + nextBeginningIndexes[i] = lastIsBeginning === undefined ? targetLen : lastIsBeginning; + } } - dropDown.style.display = 'none'; - removeEvent(document, 'click', hideHandler); - removeEvent(document, 'keydown', hideHandler); - moduleSearch.value = ''; - searchInput(); - } - } - } + return nextBeginningIndexes; + }, + cleanup: cleanup, + new: fuzzysortNew + }; + return fuzzysort; + } // fuzzysortNew - /** - * @param {string} searchText - * @return {string} HTML - */ - function filterModules(searchText) { - var results; - if (searchText === '') { - // Improve on-boarding experience by having an immediate display of - // module names, indicating how the interface works. This also makes - // for a quicker interaction in the common case of small projects. - // Don't mandate typing just to get the menu. - results = dropdownData.options.slice(0, 20).map(function (obj) { - // Fake empty results. https://github.com/farzher/fuzzysort/issues/41 - return { - obj: obj - }; - }); - } else { - results = fuzzysort.go(searchText, dropdownData.options, { - limit: 20, - key: 'name', - allowTypo: true - }); + // This stuff is outside fuzzysortNew, because it's shared with instances of fuzzysort.new() + var isNode = typeof commonjsRequire !== 'undefined' && typeof window === 'undefined'; + var MyMap = typeof Map === 'function' ? Map : function () { + var s = Object.create(null); + this.get = function (k) { + return s[k]; + }; + this.set = function (k, val) { + s[k] = val; + return this; + }; + this.clear = function () { + s = Object.create(null); + }; + }; + var preparedCache = new MyMap(); + var preparedSearchCache = new MyMap(); + var noResults = []; + noResults.total = 0; + var matchesSimple = []; + var matchesStrict = []; + function cleanup() { + preparedCache.clear(); + preparedSearchCache.clear(); + matchesSimple = []; + matchesStrict = []; + } + function defaultScoreFn(a) { + var max = -9007199254740991; + for (var i = a.length - 1; i >= 0; --i) { + var result = a[i]; + if (result === null) continue; + var score = result.score; + if (score > max) max = score; } - return moduleListHtml(results); + if (max === -9007199254740991) return null; + return max; } - // Processes module search box input - var searchInputTimeout; - function searchInput() { - // Use a debounce with a ~0ms timeout. This is effectively instantaneous, - // but is better than undebounced because it avoids an ever-growing - // backlog of unprocessed now-outdated input events if fuzzysearch or - // drodown DOM is slow (e.g. very large test suite). - window$1.clearTimeout(searchInputTimeout); - searchInputTimeout = window$1.setTimeout(function () { - dropDownList.innerHTML = filterModules(moduleSearch.value); - }); + // prop = 'key' 2.5ms optimized for this case, seems to be about as fast as direct obj[prop] + // prop = 'key1.key2' 10ms + // prop = ['key1', 'key2'] 27ms + function getValue(obj, prop) { + var tmp = obj[prop]; + if (tmp !== undefined) return tmp; + var segs = prop; + if (!Array.isArray(prop)) segs = prop.split('.'); + var len = segs.length; + var i = -1; + while (obj && ++i < len) obj = obj[segs[i]]; + return obj; } + function isObj(x) { + return _typeof(x) === 'object'; + } // faster as a function - // Processes checkbox change, or a generic render (initial render, or after reset event) - // Avoid any dropdown rendering here as this is used by toolbarModuleFilter() - // during the initial render, which should not delay test execution. - function selectionChange(evt) { - var checkbox = evt && evt.target || null; - if (checkbox) { - // Update internal state - if (checkbox.checked) { - dropdownData.selectedMap.set(checkbox.value, checkbox.parentNode.textContent); - } else { - dropdownData.selectedMap.delete(checkbox.value); + // Hacked version of https://github.com/lemire/FastPriorityQueue.js + var fastpriorityqueue = function fastpriorityqueue() { + var r = [], + o = 0, + e = {}; + function n() { + for (var e = 0, n = r[e], c = 1; c < o;) { + var f = c + 1; + e = c, f < o && r[f].score < r[c].score && (e = f), r[e - 1 >> 1] = r[e], c = 1 + (e << 1); } - - // Update UI state - toggleClass(checkbox.parentNode, 'checked', checkbox.checked); + for (var a = e - 1 >> 1; e > 0 && n.score < r[a].score; a = (e = a) - 1 >> 1) r[e] = r[a]; + r[e] = n; } - var textForm = dropdownData.selectedMap.size ? dropdownData.selectedMap.size + ' ' + (dropdownData.selectedMap.size === 1 ? 'module' : 'modules') : 'All modules'; - moduleSearch.placeholder = textForm; - moduleSearch.title = 'Type to search through and reduce the list.'; - resetButton.disabled = !dropdownData.isDirty(); - clearButton.style.display = dropdownData.selectedMap.size ? '' : 'none'; - } - return moduleFilter; - } - function appendToolbar(beginDetails) { - var toolbar = id('qunit-testrunner-toolbar'); - if (toolbar) { - toolbar.appendChild(toolbarUrlConfigContainer()); - var toolbarFilters = document.createElement('span'); - toolbarFilters.id = 'qunit-toolbar-filters'; - toolbarFilters.appendChild(toolbarLooseFilter()); - toolbarFilters.appendChild(toolbarModuleFilter(beginDetails)); - var clearfix = document.createElement('div'); - clearfix.className = 'clearfix'; - toolbar.appendChild(toolbarFilters); - toolbar.appendChild(clearfix); - } - } - function appendHeader() { - var header = id('qunit-header'); - if (header) { - header.innerHTML = "
    " + header.innerHTML + ' '; - } + return e.add = function (e) { + var n = o; + r[o++] = e; + for (var c = n - 1 >> 1; n > 0 && e.score < r[c].score; c = (n = c) - 1 >> 1) r[n] = r[c]; + r[n] = e; + }, e.poll = function () { + if (0 !== o) { + var e = r[0]; + return r[0] = r[--o], n(), e; + } + }, e.peek = function (e) { + if (0 !== o) return r[0]; + }, e.replaceTop = function (o) { + r[0] = o, n(); + }, e; + }; + var q = fastpriorityqueue(); // reuse this, except for async, it needs to make its own + + return fuzzysortNew(); + }); // UMD + + // TODO: (performance) wasm version!? + // TODO: (performance) threads? + // TODO: (performance) avoid cache misses + // TODO: (performance) preparedCache is a memory leak + // TODO: (like sublime) backslash === forwardslash + // TODO: (like sublime) spaces: "a b" should do 2 searches 1 for a and 1 for b + // TODO: (scoring) garbage in targets that allows most searches to strict match need a penality + // TODO: (performance) idk if allowTypo is optimized + })(fuzzysort$1); + var fuzzysort = fuzzysort$1.exports; + + var stats = { + failedTests: [], + defined: 0, + completed: 0 + }; + (function () { + // Don't load the HTML Reporter on non-browser environments + if (!window$1 || !document) { + return; } - function appendBanner() { - var banner = id('qunit-banner'); - if (banner) { - banner.className = ''; + QUnit.reporters.perf.init(QUnit); + var config = QUnit.config; + var hiddenTests = []; + var collapseNext = false; + var hasOwn = Object.prototype.hasOwnProperty; + var unfilteredUrl = setUrl({ + filter: undefined, + module: undefined, + moduleId: undefined, + testId: undefined + }); + var dropdownData = null; + function trim(string) { + if (typeof string.trim === 'function') { + return string.trim(); + } else { + return string.replace(/^\s+|\s+$/g, ''); } } - function appendTestResults() { - var tests = id('qunit-tests'); - var result = id('qunit-testresult'); - var controls; - if (result) { - result.parentNode.removeChild(result); - } - if (tests) { - tests.innerHTML = ''; - result = document.createElement('p'); - result.id = 'qunit-testresult'; - result.className = 'result'; - tests.parentNode.insertBefore(result, tests); - result.innerHTML = '
    Running...
     
    ' + '
    ' + '
    '; - controls = id('qunit-testresult-controls'); - } - if (controls) { - controls.appendChild(abortTestsButton()); - } + function addEvent(elem, type, fn) { + elem.addEventListener(type, fn, false); } - function appendFilteredTest() { - var testId = QUnit.config.testId; - if (!testId || testId.length <= 0) { - return ''; - } - return "
    Rerunning selected tests: " + escapeText(testId.join(', ')) + " Run all tests
    "; + function removeEvent(elem, type, fn) { + elem.removeEventListener(type, fn, false); } - function appendUserAgent() { - var userAgent = id('qunit-userAgent'); - if (userAgent) { - userAgent.innerHTML = ''; - userAgent.appendChild(document.createTextNode('QUnit ' + QUnit.version + '; ' + navigator.userAgent)); + function addEvents(elems, type, fn) { + var i = elems.length; + while (i--) { + addEvent(elems[i], type, fn); } } - function appendInterface(beginDetails) { - var qunit = id('qunit'); - - // For compat with QUnit 1.2, and to support fully custom theme HTML, - // we will use any existing elements if no id="qunit" element exists. - // - // Note that we don't fail or fallback to creating it ourselves, - // because not having id="qunit" (and not having the below elements) - // simply means QUnit acts headless, allowing users to use their own - // reporters, or for a test runner to listen for events directly without - // having the HTML reporter actively render anything. - if (qunit) { - qunit.setAttribute('role', 'main'); - - // Since QUnit 1.3, these are created automatically if the page - // contains id="qunit". - qunit.innerHTML = "

    " + escapeText(document.title) + '

    ' + "

    " + "" + appendFilteredTest() + "

    " + "
      "; - } - appendHeader(); - appendBanner(); - appendTestResults(); - appendUserAgent(); - appendToolbar(beginDetails); + function hasClass(elem, name) { + return (' ' + elem.className + ' ').indexOf(' ' + name + ' ') >= 0; } - function appendTest(name, testId, moduleName) { - var tests = id('qunit-tests'); - if (!tests) { - return; + function addClass(elem, name) { + if (!hasClass(elem, name)) { + elem.className += (elem.className ? ' ' : '') + name; } - var title = document.createElement('strong'); - title.innerHTML = getNameHtml(name, moduleName); - var testBlock = document.createElement('li'); - testBlock.appendChild(title); - - // No ID or rerun link for "global failure" blocks - if (testId !== undefined) { - var rerunTrigger = document.createElement('a'); - rerunTrigger.innerHTML = 'Rerun'; - rerunTrigger.href = setUrl({ - testId: testId - }); - testBlock.id = 'qunit-test-output-' + testId; - testBlock.appendChild(rerunTrigger); + } + function toggleClass(elem, name, force) { + if (force || typeof force === 'undefined' && !hasClass(elem, name)) { + addClass(elem, name); + } else { + removeClass(elem, name); } - var assertList = document.createElement('ol'); - assertList.className = 'qunit-assert-list'; - testBlock.appendChild(assertList); - tests.appendChild(testBlock); - return testBlock; } + function removeClass(elem, name) { + var set = ' ' + elem.className + ' '; - // HTML Reporter initialization and load - QUnit.on('runStart', function (runStart) { - stats.defined = runStart.testCounts.total; - }); - QUnit.begin(function (beginDetails) { - // Initialize QUnit elements - // This is done from begin() instead of runStart, because - // urlparams.js uses begin(), which we need to wait for. - // urlparams.js in turn uses begin() to allow plugins to - // add entries to QUnit.config.urlConfig, which may be done - // asynchronously. - // - appendInterface(beginDetails); - }); - function getRerunFailedHtml(failedTests) { - if (failedTests.length === 0) { - return ''; + // Class name may appear multiple times + while (set.indexOf(' ' + name + ' ') >= 0) { + set = set.replace(' ' + name + ' ', ' '); } - var href = setUrl({ - testId: failedTests - }); - return ["
      ", failedTests.length === 1 ? 'Rerun 1 failed test' : 'Rerun ' + failedTests.length + ' failed tests', ''].join(''); + + // Trim for prettiness + elem.className = trim(set); } - QUnit.on('runEnd', function (runEnd) { - var banner = id('qunit-banner'); - var tests = id('qunit-tests'); + function id(name) { + return document.getElementById && document.getElementById(name); + } + function abortTests() { var abortButton = id('qunit-abort-tests-button'); - var assertPassed = config.stats.all - config.stats.bad; - var html = [runEnd.testCounts.total, ' tests completed in ', runEnd.runtime, ' milliseconds, with ', runEnd.testCounts.failed, ' failed, ', runEnd.testCounts.skipped, ' skipped, and ', runEnd.testCounts.todo, ' todo.
      ', "", assertPassed, " assertions of ", config.stats.all, " passed, ", config.stats.bad, ' failed.', getRerunFailedHtml(stats.failedTests)].join(''); - var test; - var assertLi; - var assertList; - - // Update remaining tests to aborted - if (abortButton && abortButton.disabled) { - html = 'Tests aborted after ' + runEnd.runtime + ' milliseconds.'; - for (var i = 0; i < tests.children.length; i++) { - test = tests.children[i]; - if (test.className === '' || test.className === 'running') { - test.className = 'aborted'; - assertList = test.getElementsByTagName('ol')[0]; - assertLi = document.createElement('li'); - assertLi.className = 'fail'; - assertLi.innerHTML = 'Test aborted.'; - assertList.appendChild(assertLi); - } - } - } - if (banner && (!abortButton || abortButton.disabled === false)) { - banner.className = runEnd.status === 'failed' ? 'qunit-fail' : 'qunit-pass'; - } if (abortButton) { - abortButton.parentNode.removeChild(abortButton); - } - if (tests) { - id('qunit-testresult-display').innerHTML = html; - } - if (config.altertitle && document.title) { - // Show ✖ for good, ✔ for bad suite result in title - // use escape sequences in case file gets loaded with non-utf-8 - // charset - document.title = [runEnd.status === 'failed' ? "\u2716" : "\u2714", document.title.replace(/^[\u2714\u2716] /i, '')].join(' '); - } - - // Scroll back to top to show results - if (config.scrolltop && window$1.scrollTo) { - window$1.scrollTo(0, 0); - } - }); - function getNameHtml(name, module) { - var nameHtml = ''; - if (module) { - nameHtml = "" + escapeText(module) + ': '; + abortButton.disabled = true; + abortButton.innerHTML = 'Aborting...'; } - nameHtml += "" + escapeText(name) + ''; - return nameHtml; + QUnit.config.queue.length = 0; + return false; } - function getProgressHtml(stats) { - return [stats.completed, ' / ', stats.defined, ' tests completed.
      '].join(''); + function interceptNavigation(ev) { + // Trim potential accidental whitespace so that QUnit doesn't throw an error about no tests matching the filter. + var filterInputElem = id('qunit-filter-input'); + filterInputElem.value = trim(filterInputElem.value); + applyUrlParams(); + if (ev && ev.preventDefault) { + ev.preventDefault(); + } + return false; } - QUnit.testStart(function (details) { - var running, bad; - appendTest(details.name, details.testId, details.module); - running = id('qunit-testresult-display'); - if (running) { - addClass(running, 'running'); - bad = QUnit.config.reorder && details.previousFailure; - running.innerHTML = [getProgressHtml(stats), bad ? 'Rerunning previously failed test:
      ' : 'Running: ', getNameHtml(details.name, details.module), getRerunFailedHtml(stats.failedTests)].join(''); + function getUrlConfigHtml() { + var selection = false; + var urlConfig = config.urlConfig; + var urlConfigHtml = ''; + for (var i = 0; i < urlConfig.length; i++) { + // Options can be either strings or objects with nonempty "id" properties + var val = config.urlConfig[i]; + if (typeof val === 'string') { + val = { + id: val, + label: val + }; + } + var escaped = escapeText(val.id); + var escapedTooltip = escapeText(val.tooltip); + if (!val.value || typeof val.value === 'string') { + urlConfigHtml += "'; + } else { + urlConfigHtml += "'; + } } - }); - function stripHtml(string) { - // Strip tags, html entity and whitespaces - return string.replace(/<\/?[^>]+(>|$)/g, '').replace(/"/g, '').replace(/\s+/g, ''); + return urlConfigHtml; } - QUnit.log(function (details) { - var testItem = id('qunit-test-output-' + details.testId); - if (!testItem) { - return; + + // Handle "click" events on toolbar checkboxes and "change" for select menus. + // Updates the URL with the new state of `config.urlConfig` values. + function toolbarChanged() { + var field = this; + var params = {}; + + // Detect if field is a select menu or a checkbox + var value; + if ('selectedIndex' in field) { + value = field.options[field.selectedIndex].value || undefined; + } else { + value = field.checked ? field.defaultValue || true : undefined; } - var message = escapeText(details.message) || (details.result ? 'okay' : 'failed'); - message = "" + message + ''; - message += "@ " + details.runtime + ' ms'; - var expected; - var actual; - var diff; - var showDiff = false; + params[field.name] = value; + var updatedUrl = setUrl(params); - // The pushFailure doesn't provide details.expected - // when it calls, it's implicit to also not show expected and diff stuff - // Also, we need to check details.expected existence, as it can exist and be undefined - if (!details.result && hasOwn.call(details, 'expected')) { - if (details.negative) { - expected = 'NOT ' + QUnit.dump.parse(details.expected); - } else { - expected = QUnit.dump.parse(details.expected); - } - actual = QUnit.dump.parse(details.actual); - message += "
      '; - if (actual !== expected) { - message += "'; - if (typeof details.actual === 'number' && typeof details.expected === 'number') { - if (!isNaN(details.actual) && !isNaN(details.expected)) { - showDiff = true; - diff = details.actual - details.expected; - diff = (diff > 0 ? '+' : '') + diff; + // Check if we can apply the change without a page refresh + if (field.name === 'hidepassed' && 'replaceState' in window$1.history) { + QUnit.urlParams[field.name] = value; + config[field.name] = value || false; + var tests = id('qunit-tests'); + if (tests) { + if (field.checked) { + var length = tests.children.length; + var children = tests.children; + for (var i = 0; i < length; i++) { + var test = children[i]; + var className = test ? test.className : ''; + var classNameHasPass = className.indexOf('pass') > -1; + var classNameHasSkipped = className.indexOf('skipped') > -1; + if (classNameHasPass || classNameHasSkipped) { + hiddenTests.push(test); + } } - } else if (typeof details.actual !== 'boolean' && typeof details.expected !== 'boolean') { - diff = QUnit.diff(expected, actual); - // don't show diff if there is zero overlap - showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length; - } - if (showDiff) { - message += "'; + // Optimization: Avoid `for-of` iterator overhead. + for (var _i = 0; _i < hiddenTests.length; _i++) { + tests.removeChild(hiddenTests[_i]); + } + } else { + // Optimization: Avoid `while (arr.length) arr.shift()` which would mutate the array many times. + // As of Chrome 126, HTMLElement.append(...hiddenTests) is still slower than + // calling appendChild in a loop. + for (var _i2 = 0; _i2 < hiddenTests.length; _i2++) { + tests.appendChild(hiddenTests[_i2]); + } + hiddenTests.length = 0; } - } else if (expected.indexOf('[object Array]') !== -1 || expected.indexOf('[object Object]') !== -1) { - message += "'; - } else { - message += "'; } - if (details.source) { - message += "'; + window$1.history.replaceState(null, '', updatedUrl); + } else { + window$1.location = updatedUrl; + } + } + function setUrl(params) { + var querystring = '?'; + var location = window$1.location; + params = extend(extend({}, QUnit.urlParams), params); + for (var key in params) { + // Skip inherited or undefined properties + if (hasOwn.call(params, key) && params[key] !== undefined) { + // Output a parameter for each value of this key + // (but usually just one) + var arrValue = [].concat(params[key]); + for (var i = 0; i < arrValue.length; i++) { + querystring += encodeURIComponent(key); + if (arrValue[i] !== true) { + querystring += '=' + encodeURIComponent(arrValue[i]); + } + querystring += '&'; + } } - message += '
      Expected:
      " + escapeText(expected) + '
      Result:
      " + escapeText(actual) + '
      Diff:
      " + diff + '
      Message: " + 'Diff suppressed as the depth of object is more than current max depth (' + QUnit.config.maxDepth + ').

      Hint: Use QUnit.dump.maxDepth to ' + " run with a higher max depth or " + 'Rerun without max depth.

      Message: " + 'Diff suppressed as the expected and actual results have an equivalent' + ' serialization
      Source:
      " + escapeText(details.source) + '
      '; + } + return location.protocol + '//' + location.host + location.pathname + querystring.slice(0, -1); + } + function applyUrlParams() { + var filter = id('qunit-filter-input').value; + window$1.location = setUrl({ + filter: filter === '' ? undefined : filter, + moduleId: _toConsumableArray(dropdownData.selectedMap.keys()), + // Remove module and testId filter + module: undefined, + testId: undefined + }); + } + function toolbarUrlConfigContainer() { + var urlConfigContainer = document.createElement('span'); + urlConfigContainer.innerHTML = getUrlConfigHtml(); + addClass(urlConfigContainer, 'qunit-url-config'); + addEvents(urlConfigContainer.getElementsByTagName('input'), 'change', toolbarChanged); + addEvents(urlConfigContainer.getElementsByTagName('select'), 'change', toolbarChanged); + return urlConfigContainer; + } + function abortTestsButton() { + var button = document.createElement('button'); + button.id = 'qunit-abort-tests-button'; + button.innerHTML = 'Abort'; + addEvent(button, 'click', abortTests); + return button; + } + function toolbarLooseFilter() { + var filter = document.createElement('form'); + var label = document.createElement('label'); + var input = document.createElement('input'); + var button = document.createElement('button'); + addClass(filter, 'qunit-filter'); + label.innerHTML = 'Filter: '; + input.type = 'text'; + input.value = config.filter || ''; + input.name = 'filter'; + input.id = 'qunit-filter-input'; + button.innerHTML = 'Go'; + label.appendChild(input); + filter.appendChild(label); + filter.appendChild(document.createTextNode(' ')); + filter.appendChild(button); + addEvent(filter, 'submit', interceptNavigation); + return filter; + } + function createModuleListItem(moduleId, name, checked) { + return '
    1. '; + } - // This occurs when pushFailure is set and we have an extracted stack trace - } else if (!details.result && details.source) { - message += '' + "' + '
      Source:
      " + escapeText(details.source) + '
      '; + /** + * @param {Array} Results from fuzzysort + * @return {string} HTML + */ + function moduleListHtml(results) { + var html = ''; + + // Hoist the already selected items, and show them always + // even if not matched by the current search. + dropdownData.selectedMap.forEach(function (name, moduleId) { + html += createModuleListItem(moduleId, name, true); + }); + for (var i = 0; i < results.length; i++) { + var mod = results[i].obj; + if (!dropdownData.selectedMap.has(mod.moduleId)) { + html += createModuleListItem(mod.moduleId, mod.name, false); + } } - var assertList = testItem.getElementsByTagName('ol')[0]; - var assertLi = document.createElement('li'); - assertLi.className = details.result ? 'pass' : 'fail'; - assertLi.innerHTML = message; - assertList.appendChild(assertLi); - }); - QUnit.testDone(function (details) { - var tests = id('qunit-tests'); - var testItem = id('qunit-test-output-' + details.testId); - if (!tests || !testItem) { - return; + return html; + } + function toolbarModuleFilter(beginDetails) { + var initialSelected = null; + dropdownData = { + options: beginDetails.modules.slice(), + selectedMap: new StringMap(), + isDirty: function isDirty() { + return _toConsumableArray(dropdownData.selectedMap.keys()).sort().join(',') !== _toConsumableArray(initialSelected.keys()).sort().join(','); + } + }; + if (config.moduleId.length) { + // The module dropdown is seeded with the runtime configuration of the last run. + // + // We don't reference `config.moduleId` directly after this and keep our own + // copy because: + // 1. This naturally filters out unknown moduleIds. + // 2. Gives us a place to manage and remember unsubmitted checkbox changes. + // 3. Gives us an efficient way to map a selected moduleId to module name + // during rendering. + for (var i = 0; i < beginDetails.modules.length; i++) { + var mod = beginDetails.modules[i]; + if (config.moduleId.indexOf(mod.moduleId) !== -1) { + dropdownData.selectedMap.set(mod.moduleId, mod.name); + } + } } - removeClass(testItem, 'running'); - var status; - if (details.failed > 0) { - status = 'failed'; - } else if (details.todo) { - status = 'todo'; - } else { - status = details.skipped ? 'skipped' : 'passed'; + initialSelected = new StringMap(dropdownData.selectedMap); + var moduleSearch = document.createElement('input'); + moduleSearch.id = 'qunit-modulefilter-search'; + moduleSearch.autocomplete = 'off'; + addEvent(moduleSearch, 'input', searchInput); + addEvent(moduleSearch, 'input', searchFocus); + addEvent(moduleSearch, 'focus', searchFocus); + addEvent(moduleSearch, 'click', searchFocus); + var label = document.createElement('label'); + label.htmlFor = 'qunit-modulefilter-search'; + label.textContent = 'Module:'; + var searchContainer = document.createElement('span'); + searchContainer.id = 'qunit-modulefilter-search-container'; + searchContainer.appendChild(moduleSearch); + var applyButton = document.createElement('button'); + applyButton.textContent = 'Apply'; + applyButton.title = 'Re-run the selected test modules'; + addEvent(applyButton, 'click', applyUrlParams); + var resetButton = document.createElement('button'); + resetButton.textContent = 'Reset'; + resetButton.type = 'reset'; + resetButton.title = 'Restore the previous module selection'; + var clearButton = document.createElement('button'); + clearButton.textContent = 'Select none'; + clearButton.type = 'button'; + clearButton.title = 'Clear the current module selection'; + addEvent(clearButton, 'click', function () { + dropdownData.selectedMap.clear(); + selectionChange(); + searchInput(); + }); + var actions = document.createElement('span'); + actions.id = 'qunit-modulefilter-actions'; + actions.appendChild(applyButton); + actions.appendChild(resetButton); + if (initialSelected.size) { + // Only show clear button if functionally different from reset + actions.appendChild(clearButton); } - var assertList = testItem.getElementsByTagName('ol')[0]; - var good = details.passed; - var bad = details.failed; + var dropDownList = document.createElement('ul'); + dropDownList.id = 'qunit-modulefilter-dropdown-list'; + var dropDown = document.createElement('div'); + dropDown.id = 'qunit-modulefilter-dropdown'; + dropDown.style.display = 'none'; + dropDown.appendChild(actions); + dropDown.appendChild(dropDownList); + addEvent(dropDown, 'change', selectionChange); + searchContainer.appendChild(dropDown); + // Set initial moduleSearch.placeholder and clearButton/resetButton. + selectionChange(); + var moduleFilter = document.createElement('form'); + moduleFilter.id = 'qunit-modulefilter'; + moduleFilter.appendChild(label); + moduleFilter.appendChild(document.createTextNode(' ')); + moduleFilter.appendChild(searchContainer); + addEvent(moduleFilter, 'submit', interceptNavigation); + addEvent(moduleFilter, 'reset', function () { + dropdownData.selectedMap = new StringMap(initialSelected); + // Set moduleSearch.placeholder and reflect non-dirty state + selectionChange(); + searchInput(); + }); - // This test passed if it has no unexpected failed assertions - var testPassed = details.failed > 0 ? details.todo : !details.todo; - if (testPassed) { - // Collapse the passing tests - addClass(assertList, 'qunit-collapsed'); - } else { - stats.failedTests.push(details.testId); - if (config.collapse) { - if (!collapseNext) { - // Skip collapsing the first failing test - collapseNext = true; - } else { - // Collapse remaining tests - addClass(assertList, 'qunit-collapsed'); + // Enables show/hide for the dropdown + function searchFocus() { + if (dropDown.style.display !== 'none') { + return; + } + + // Optimization: Defer rendering options until focussed. + // https://github.com/qunitjs/qunit/issues/1664 + searchInput(); + dropDown.style.display = 'block'; + + // Hide on Escape keydown or on click outside the container + addEvent(document, 'click', hideHandler); + addEvent(document, 'keydown', hideHandler); + function hideHandler(e) { + var inContainer = moduleFilter.contains(e.target); + if (e.keyCode === 27 || !inContainer) { + if (e.keyCode === 27 && inContainer) { + moduleSearch.focus(); + } + dropDown.style.display = 'none'; + removeEvent(document, 'click', hideHandler); + removeEvent(document, 'keydown', hideHandler); + moduleSearch.value = ''; + searchInput(); } } } - // The testItem.firstChild is the test name - var testTitle = testItem.firstChild; - var testCounts = bad ? "" + bad + ', ' + "" + good + ', ' : ''; - testTitle.innerHTML += " (" + testCounts + details.assertions.length + ')'; - stats.completed++; - if (details.skipped) { - testItem.className = 'skipped'; - var skipped = document.createElement('em'); - skipped.className = 'qunit-skipped-label'; - skipped.innerHTML = 'skipped'; - testItem.insertBefore(skipped, testTitle); - } else { - addEvent(testTitle, 'click', function () { - toggleClass(assertList, 'qunit-collapsed'); - }); - testItem.className = testPassed ? 'pass' : 'fail'; - if (details.todo) { - var todoLabel = document.createElement('em'); - todoLabel.className = 'qunit-todo-label'; - todoLabel.innerHTML = 'todo'; - testItem.className += ' todo'; - testItem.insertBefore(todoLabel, testTitle); + /** + * @param {string} searchText + * @return {string} HTML + */ + function filterModules(searchText) { + var results; + if (searchText === '') { + // Improve on-boarding experience by having an immediate display of + // module names, indicating how the interface works. This also makes + // for a quicker interaction in the common case of small projects. + // Don't mandate typing just to get the menu. + results = dropdownData.options.slice(0, 20).map(function (obj) { + // Fake empty results. https://github.com/farzher/fuzzysort/issues/41 + return { + obj: obj + }; + }); + } else { + results = fuzzysort.go(searchText, dropdownData.options, { + limit: 20, + key: 'name', + allowTypo: true + }); } - var time = document.createElement('span'); - time.className = 'runtime'; - time.innerHTML = details.runtime + ' ms'; - testItem.insertBefore(time, assertList); + return moduleListHtml(results); } - // Show the source of the test when showing assertions - if (details.source) { - var sourceName = document.createElement('p'); - sourceName.innerHTML = 'Source: ' + escapeText(details.source); - addClass(sourceName, 'qunit-source'); - if (testPassed) { - addClass(sourceName, 'qunit-collapsed'); - } - addEvent(testTitle, 'click', function () { - toggleClass(sourceName, 'qunit-collapsed'); + // Processes module search box input + var searchInputTimeout; + function searchInput() { + // Use a debounce with a ~0ms timeout. This is effectively instantaneous, + // but is better than undebounced because it avoids an ever-growing + // backlog of unprocessed now-outdated input events if fuzzysearch or + // drodown DOM is slow (e.g. very large test suite). + window$1.clearTimeout(searchInputTimeout); + searchInputTimeout = window$1.setTimeout(function () { + dropDownList.innerHTML = filterModules(moduleSearch.value); }); - testItem.appendChild(sourceName); } - if (config.hidepassed && (status === 'passed' || details.skipped)) { - // use removeChild instead of remove because of support - hiddenTests.push(testItem); - tests.removeChild(testItem); + + // Processes checkbox change, or a generic render (initial render, or after reset event) + // Avoid any dropdown rendering here as this is used by toolbarModuleFilter() + // during the initial render, which should not delay test execution. + function selectionChange(evt) { + var checkbox = evt && evt.target || null; + if (checkbox) { + // Update internal state + if (checkbox.checked) { + dropdownData.selectedMap.set(checkbox.value, checkbox.parentNode.textContent); + } else { + dropdownData.selectedMap.delete(checkbox.value); + } + + // Update UI state + toggleClass(checkbox.parentNode, 'checked', checkbox.checked); + } + var textForm = dropdownData.selectedMap.size ? dropdownData.selectedMap.size + ' ' + (dropdownData.selectedMap.size === 1 ? 'module' : 'modules') : 'All modules'; + moduleSearch.placeholder = textForm; + moduleSearch.title = 'Type to search through and reduce the list.'; + resetButton.disabled = !dropdownData.isDirty(); + clearButton.style.display = dropdownData.selectedMap.size ? '' : 'none'; } - }); - QUnit.on('error', function (error) { - var testItem = appendTest('global failure'); - if (!testItem) { - // HTML Reporter is probably disabled or not yet initialized. - return; + return moduleFilter; + } + function appendToolbar(beginDetails) { + var toolbar = id('qunit-testrunner-toolbar'); + if (toolbar) { + toolbar.appendChild(toolbarUrlConfigContainer()); + var toolbarFilters = document.createElement('span'); + toolbarFilters.id = 'qunit-toolbar-filters'; + toolbarFilters.appendChild(toolbarLooseFilter()); + toolbarFilters.appendChild(toolbarModuleFilter(beginDetails)); + var clearfix = document.createElement('div'); + clearfix.className = 'clearfix'; + toolbar.appendChild(toolbarFilters); + toolbar.appendChild(clearfix); } - - // Render similar to a failed assertion (see above QUnit.log callback) - var message = escapeText(errorString(error)); - message = "" + message + ''; - if (error && error.stack) { - message += '' + "' + '
      Source:
      " + escapeText(error.stack) + '
      '; + } + function appendHeader() { + var header = id('qunit-header'); + if (header) { + header.innerHTML = "" + header.innerHTML + ' '; } - var assertList = testItem.getElementsByTagName('ol')[0]; - var assertLi = document.createElement('li'); - assertLi.className = 'fail'; - assertLi.innerHTML = message; - assertList.appendChild(assertLi); - - // Make it visible - testItem.className = 'fail'; - }); - - // Avoid readyState issue with phantomjs - // Ref: #818 - var usingPhantom = function (p) { - return p && p.version && p.version.major > 0; - }(window$1.phantom); - if (usingPhantom) { - console$1.warn('Support for PhantomJS is deprecated and will be removed in QUnit 3.0.'); } - if (!usingPhantom && document.readyState === 'complete') { - QUnit.load(); - } else { - addEvent(window$1, 'load', QUnit.load); + function appendBanner() { + var banner = id('qunit-banner'); + if (banner) { + banner.className = ''; + } } - - // Wrap window.onerror. We will call the original window.onerror to see if - // the existing handler fully handles the error; if not, we will call the - // QUnit.onError function. - var originalWindowOnError = window$1.onerror; - - // Cover uncaught exceptions - // Returning true will suppress the default browser handler, - // returning false will let it run. - window$1.onerror = function (message, fileName, lineNumber, columnNumber, errorObj) { - var ret = false; - if (originalWindowOnError) { - for (var _len = arguments.length, args = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) { - args[_key - 5] = arguments[_key]; - } - ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber, columnNumber, errorObj].concat(args)); + function appendTestResults() { + var tests = id('qunit-tests'); + var result = id('qunit-testresult'); + var controls; + if (result) { + result.parentNode.removeChild(result); } - - // Treat return value as window.onerror itself does, - // Only do our handling if not suppressed. - if (ret !== true) { - // If there is a current test that sets the internal `ignoreGlobalErrors` field - // (such as during `assert.throws()`), then the error is ignored and native - // error reporting is suppressed as well. This is because in browsers, an error - // can sometimes end up in `window.onerror` instead of in the local try/catch. - // This ignoring of errors does not apply to our general onUncaughtException - // method, nor to our `unhandledRejection` handlers, as those are not meant - // to receive an "expected" error during `assert.throws()`. - if (config.current && config.current.ignoreGlobalErrors) { - return true; - } - - // According to - // https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror, - // most modern browsers support an errorObj argument; use that to - // get a full stack trace if it's available. - var error = errorObj || new Error(message); - if (!error.stack && fileName && lineNumber) { - error.stack = "".concat(fileName, ":").concat(lineNumber); - } - QUnit.onUncaughtException(error); + if (tests) { + tests.innerHTML = ''; + result = document.createElement('p'); + result.id = 'qunit-testresult'; + result.className = 'result'; + tests.parentNode.insertBefore(result, tests); + result.innerHTML = '
      Running...
       
      ' + '
      ' + '
      '; + controls = id('qunit-testresult-controls'); } - return ret; - }; - window$1.addEventListener('unhandledrejection', function (event) { - QUnit.onUncaughtException(event.reason); - }); - })(); - - /* - * This file is a modified version of google-diff-match-patch's JavaScript implementation - * (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js), - * modifications are licensed as more fully set forth in LICENSE.txt. - * - * The original source of google-diff-match-patch is attributable and licensed as follows: - * - * Copyright 2006 Google Inc. - * https://code.google.com/p/google-diff-match-patch/ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * More Info: - * https://code.google.com/p/google-diff-match-patch/ - * - * Usage: QUnit.diff(expected, actual) - * - */ - QUnit.diff = function () { - function DiffMatchPatch() {} - - // DIFF FUNCTIONS - - /** - * The data structure representing a diff is an array of tuples: - * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] - * which means: delete 'Hello', add 'Goodbye' and keep ' world.' - */ - var DIFF_DELETE = -1; - var DIFF_INSERT = 1; - var DIFF_EQUAL = 0; - var hasOwn = Object.prototype.hasOwnProperty; - - /** - * Find the differences between two texts. Simplifies the problem by stripping - * any common prefix or suffix off the texts before diffing. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {boolean=} optChecklines Optional speedup flag. If present and false, - * then don't run a line-level diff first to identify the changed areas. - * Defaults to true, which does a faster, slightly less optimal diff. - * @return {!Array.} Array of diff tuples. - */ - DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) { - // The diff must be complete in up to 1 second. - var deadline = Date.now() + 1000; - - // Check for null inputs. - if (text1 === null || text2 === null) { - throw new Error('Cannot diff null input.'); + if (controls) { + controls.appendChild(abortTestsButton()); } - - // Check for equality (speedup). - if (text1 === text2) { - if (text1) { - return [[DIFF_EQUAL, text1]]; - } - return []; + } + function appendFilteredTest() { + var testId = QUnit.config.testId; + if (!testId || testId.length <= 0) { + return ''; } - if (typeof optChecklines === 'undefined') { - optChecklines = true; + return "
      Rerunning selected tests: " + escapeText(testId.join(', ')) + " Run all tests
      "; + } + function appendUserAgent() { + var userAgent = id('qunit-userAgent'); + if (userAgent) { + userAgent.innerHTML = ''; + userAgent.appendChild(document.createTextNode('QUnit ' + QUnit.version + '; ' + navigator.userAgent)); } + } + function appendInterface(beginDetails) { + var qunit = id('qunit'); - // Trim off common prefix (speedup). - var commonlength = this.diffCommonPrefix(text1, text2); - var commonprefix = text1.substring(0, commonlength); - text1 = text1.substring(commonlength); - text2 = text2.substring(commonlength); - - // Trim off common suffix (speedup). - commonlength = this.diffCommonSuffix(text1, text2); - var commonsuffix = text1.substring(text1.length - commonlength); - text1 = text1.substring(0, text1.length - commonlength); - text2 = text2.substring(0, text2.length - commonlength); - - // Compute the diff on the middle block. - var diffs = this.diffCompute(text1, text2, optChecklines, deadline); + // For compat with QUnit 1.2, and to support fully custom theme HTML, + // we will use any existing elements if no id="qunit" element exists. + // + // Note that we don't fail or fallback to creating it ourselves, + // because not having id="qunit" (and not having the below elements) + // simply means QUnit acts headless, allowing users to use their own + // reporters, or for a test runner to listen for events directly without + // having the HTML reporter actively render anything. + if (qunit) { + qunit.setAttribute('role', 'main'); - // Restore the prefix and suffix. - if (commonprefix) { - diffs.unshift([DIFF_EQUAL, commonprefix]); + // Since QUnit 1.3, these are created automatically if the page + // contains id="qunit". + qunit.innerHTML = "

      " + escapeText(document.title) + '

      ' + "

      " + "" + appendFilteredTest() + "

      " + "
        "; } - if (commonsuffix) { - diffs.push([DIFF_EQUAL, commonsuffix]); + appendHeader(); + appendBanner(); + appendTestResults(); + appendUserAgent(); + appendToolbar(beginDetails); + } + function appendTest(name, testId, moduleName) { + var tests = id('qunit-tests'); + if (!tests) { + return; } - this.diffCleanupMerge(diffs); - return diffs; - }; - - /** - * Reduce the number of edits by eliminating operationally trivial equalities. - * @param {!Array.} diffs Array of diff tuples. - */ - DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) { - var changes, equalities, equalitiesLength, lastequality, pointer, preIns, preDel, postIns, postDel; - changes = false; - equalities = []; // Stack of indices where equalities are found. - equalitiesLength = 0; // Keeping our own length var is faster in JS. - /** @type {?string} */ - lastequality = null; - - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - pointer = 0; // Index of current position. - - // Is there an insertion operation before the last equality. - preIns = false; - - // Is there a deletion operation before the last equality. - preDel = false; - - // Is there an insertion operation after the last equality. - postIns = false; + var title = document.createElement('strong'); + title.className = 'qunit-test-name'; + title.innerHTML = getNameHtml(name, moduleName); + var testBlock = document.createElement('li'); + testBlock.appendChild(title); - // Is there a deletion operation after the last equality. - postDel = false; - while (pointer < diffs.length) { - // Equality found. - if (diffs[pointer][0] === DIFF_EQUAL) { - if (diffs[pointer][1].length < 4 && (postIns || postDel)) { - // Candidate found. - equalities[equalitiesLength++] = pointer; - preIns = postIns; - preDel = postDel; - lastequality = diffs[pointer][1]; - } else { - // Not a candidate, and can never become one. - equalitiesLength = 0; - lastequality = null; - } - postIns = postDel = false; + // No ID or rerun link for "global failure" blocks + if (testId !== undefined) { + var rerunTrigger = document.createElement('a'); + rerunTrigger.innerHTML = 'Rerun'; + rerunTrigger.href = setUrl({ + testId: testId + }); + testBlock.id = 'qunit-test-output-' + testId; + testBlock.appendChild(rerunTrigger); + } + var assertList = document.createElement('ol'); + assertList.className = 'qunit-assert-list'; + testBlock.appendChild(assertList); + tests.appendChild(testBlock); + return testBlock; + } - // An insertion or deletion. - } else { - if (diffs[pointer][0] === DIFF_DELETE) { - postDel = true; - } else { - postIns = true; - } + // HTML Reporter initialization and load + QUnit.on('runStart', function (runStart) { + stats.defined = runStart.testCounts.total; + }); + QUnit.begin(function (beginDetails) { + // Initialize QUnit elements + // This is done from begin() instead of runStart, because + // urlparams.js uses begin(), which we need to wait for. + // urlparams.js in turn uses begin() to allow plugins to + // add entries to QUnit.config.urlConfig, which may be done + // asynchronously. + // + appendInterface(beginDetails); + }); + function getRerunFailedHtml(failedTests) { + if (failedTests.length === 0) { + return ''; + } + var href = setUrl({ + testId: failedTests + }); + return ["
        ", failedTests.length === 1 ? 'Rerun 1 failed test' : 'Rerun ' + failedTests.length + ' failed tests', ''].join(''); + } + QUnit.on('runEnd', function (runEnd) { + var banner = id('qunit-banner'); + var tests = id('qunit-tests'); + var abortButton = id('qunit-abort-tests-button'); + var assertPassed = config.stats.all - config.stats.bad; + var html = [runEnd.testCounts.total, ' tests completed in ', runEnd.runtime, ' milliseconds, with ', runEnd.testCounts.failed, ' failed, ', runEnd.testCounts.skipped, ' skipped, and ', runEnd.testCounts.todo, ' todo.
        ', "", assertPassed, " assertions of ", config.stats.all, " passed, ", config.stats.bad, ' failed.', getRerunFailedHtml(stats.failedTests)].join(''); + var test; + var assertLi; + var assertList; - /* - * Five types to be split: - * ABXYCD - * AXCD - * ABXC - * AXCD - * ABXC - */ - if (lastequality && (preIns && preDel && postIns && postDel || lastequality.length < 2 && preIns + preDel + postIns + postDel === 3)) { - // Duplicate record. - diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); - - // Change second copy to insert. - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - equalitiesLength--; // Throw away the equality we just deleted; - lastequality = null; - if (preIns && preDel) { - // No changes made which could affect previous entry, keep going. - postIns = postDel = true; - equalitiesLength = 0; - } else { - equalitiesLength--; // Throw away the previous equality. - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - postIns = postDel = false; - } - changes = true; + // Update remaining tests to aborted + if (abortButton && abortButton.disabled) { + html = 'Tests aborted after ' + runEnd.runtime + ' milliseconds.'; + for (var i = 0; i < tests.children.length; i++) { + test = tests.children[i]; + if (test.className === '' || test.className === 'running') { + test.className = 'aborted'; + assertList = test.getElementsByTagName('ol')[0]; + assertLi = document.createElement('li'); + assertLi.className = 'fail'; + assertLi.innerHTML = 'Test aborted.'; + assertList.appendChild(assertLi); } } - pointer++; } - if (changes) { - this.diffCleanupMerge(diffs); - } - }; - - /** - * Convert a diff array into a pretty HTML report. - * @param {!Array.} diffs Array of diff tuples. - * @param {integer} string to be beautified. - * @return {string} HTML representation. - */ - DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) { - var html = []; - for (var x = 0; x < diffs.length; x++) { - var op = diffs[x][0]; // Operation (insert, delete, equal) - var data = diffs[x][1]; // Text of change. - switch (op) { - case DIFF_INSERT: - html[x] = '' + escapeText(data) + ''; - break; - case DIFF_DELETE: - html[x] = '' + escapeText(data) + ''; - break; - case DIFF_EQUAL: - html[x] = '' + escapeText(data) + ''; - break; - } + if (banner && (!abortButton || abortButton.disabled === false)) { + banner.className = runEnd.status === 'failed' ? 'qunit-fail' : 'qunit-pass'; } - return html.join(''); - }; - - /** - * Determine the common prefix of two strings. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the start of each - * string. - */ - DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) { - var pointermid, pointermax, pointermin, pointerstart; - - // Quick check for common null cases. - if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { - return 0; - } - - // Binary search. - // Performance analysis: https://neil.fraser.name/news/2007/10/09/ - pointermin = 0; - pointermax = Math.min(text1.length, text2.length); - pointermid = pointermax; - pointerstart = 0; - while (pointermin < pointermid) { - if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + if (abortButton) { + abortButton.parentNode.removeChild(abortButton); } - return pointermid; - }; - - /** - * Determine the common suffix of two strings. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the end of each string. - */ - DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) { - var pointermid, pointermax, pointermin, pointerend; - - // Quick check for common null cases. - if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { - return 0; - } - - // Binary search. - // Performance analysis: https://neil.fraser.name/news/2007/10/09/ - pointermin = 0; - pointermax = Math.min(text1.length, text2.length); - pointermid = pointermax; - pointerend = 0; - while (pointermin < pointermid) { - if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + if (tests) { + id('qunit-testresult-display').innerHTML = html; } - return pointermid; - }; - - /** - * Find the differences between two texts. Assumes that the texts do not - * have any common prefix or suffix. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {boolean} checklines Speedup flag. If false, then don't run a - * line-level diff first to identify the changed areas. - * If true, then run a faster, slightly less optimal diff. - * @param {number} deadline Time when the diff should be complete by. - * @return {!Array.} Array of diff tuples. - * @private - */ - DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) { - var diffs, longtext, shorttext, i, hm, text1A, text2A, text1B, text2B, midCommon, diffsA, diffsB; - if (!text1) { - // Just add some text (speedup). - return [[DIFF_INSERT, text2]]; - } - if (!text2) { - // Just delete some text (speedup). - return [[DIFF_DELETE, text1]]; - } - longtext = text1.length > text2.length ? text1 : text2; - shorttext = text1.length > text2.length ? text2 : text1; - i = longtext.indexOf(shorttext); - if (i !== -1) { - // Shorter text is inside the longer text (speedup). - diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; - - // Swap insertions for deletions if diff is reversed. - if (text1.length > text2.length) { - diffs[0][0] = diffs[2][0] = DIFF_DELETE; - } - return diffs; - } - if (shorttext.length === 1) { - // Single character string. - // After the previous speedup, the character can't be an equality. - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; - } - - // Check to see if the problem can be split in two. - hm = this.diffHalfMatch(text1, text2); - if (hm) { - // A half-match was found, sort out the return data. - text1A = hm[0]; - text1B = hm[1]; - text2A = hm[2]; - text2B = hm[3]; - midCommon = hm[4]; - - // Send both pairs off for separate processing. - diffsA = this.DiffMain(text1A, text2A, checklines, deadline); - diffsB = this.DiffMain(text1B, text2B, checklines, deadline); - - // Merge the results. - return diffsA.concat([[DIFF_EQUAL, midCommon]], diffsB); - } - if (checklines && text1.length > 100 && text2.length > 100) { - return this.diffLineMode(text1, text2, deadline); - } - return this.diffBisect(text1, text2, deadline); - }; - - /** - * Do the two texts share a substring which is at least half the length of the - * longer text? - * This speedup can produce non-minimal diffs. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {Array.} Five element Array, containing the prefix of - * text1, the suffix of text1, the prefix of text2, the suffix of - * text2 and the common middle. Or null if there was no match. - * @private - */ - DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) { - var longtext, shorttext, dmp, text1A, text2B, text2A, text1B, midCommon, hm1, hm2, hm; - longtext = text1.length > text2.length ? text1 : text2; - shorttext = text1.length > text2.length ? text2 : text1; - if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { - return null; // Pointless. + if (config.altertitle && document.title) { + // Show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8 + // charset + document.title = [runEnd.status === 'failed' ? "\u2716" : "\u2714", document.title.replace(/^[\u2714\u2716] /i, '')].join(' '); } - dmp = this; // 'this' becomes 'window' in a closure. - - /** - * Does a substring of shorttext exist within longtext such that the substring - * is at least half the length of longtext? - * Closure, but does not reference any external variables. - * @param {string} longtext Longer string. - * @param {string} shorttext Shorter string. - * @param {number} i Start index of quarter length substring within longtext. - * @return {Array.} Five element Array, containing the prefix of - * longtext, the suffix of longtext, the prefix of shorttext, the suffix - * of shorttext and the common middle. Or null if there was no match. - * @private - */ - function diffHalfMatchI(longtext, shorttext, i) { - var seed, j, bestCommon, prefixLength, suffixLength, bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB; - - // Start with a 1/4 length substring at position i as a seed. - seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); - j = -1; - bestCommon = ''; - while ((j = shorttext.indexOf(seed, j + 1)) !== -1) { - prefixLength = dmp.diffCommonPrefix(longtext.substring(i), shorttext.substring(j)); - suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); - if (bestCommon.length < suffixLength + prefixLength) { - bestCommon = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); - bestLongtextA = longtext.substring(0, i - suffixLength); - bestLongtextB = longtext.substring(i + prefixLength); - bestShorttextA = shorttext.substring(0, j - suffixLength); - bestShorttextB = shorttext.substring(j + prefixLength); - } - } - if (bestCommon.length * 2 >= longtext.length) { - return [bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon]; - } else { - return null; - } + // Scroll back to top to show results + if (config.scrolltop && window$1.scrollTo) { + window$1.scrollTo(0, 0); } - - // First check if the second quarter is the seed for a half-match. - hm1 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 4)); - - // Check again based on the third quarter. - hm2 = diffHalfMatchI(longtext, shorttext, Math.ceil(longtext.length / 2)); - if (!hm1 && !hm2) { - return null; - } else if (!hm2) { - hm = hm1; - } else if (!hm1) { - hm = hm2; - } else { - // Both matched. Select the longest. - hm = hm1[4].length > hm2[4].length ? hm1 : hm2; + }); + function getNameHtml(name, module) { + var nameHtml = ''; + if (module) { + nameHtml = "" + escapeText(module) + ': '; } - - // A half-match was found, sort out the return data. - if (text1.length > text2.length) { - text1A = hm[0]; - text1B = hm[1]; - text2A = hm[2]; - text2B = hm[3]; - } else { - text2A = hm[0]; - text2B = hm[1]; - text1A = hm[2]; - text1B = hm[3]; + nameHtml += "" + escapeText(name) + ''; + return nameHtml; + } + function getProgressHtml(stats) { + return [stats.completed, ' / ', stats.defined, ' tests completed.
        '].join(''); + } + QUnit.testStart(function (details) { + var running, bad; + appendTest(details.name, details.testId, details.module); + running = id('qunit-testresult-display'); + if (running) { + addClass(running, 'running'); + bad = QUnit.config.reorder && details.previousFailure; + running.innerHTML = [getProgressHtml(stats), bad ? 'Rerunning previously failed test:
        ' : 'Running: ', getNameHtml(details.name, details.module), getRerunFailedHtml(stats.failedTests)].join(''); } - midCommon = hm[4]; - return [text1A, text1B, text2A, text2B, midCommon]; - }; - - /** - * Do a quick line-level diff on both strings, then rediff the parts for - * greater accuracy. - * This speedup can produce non-minimal diffs. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} deadline Time when the diff should be complete by. - * @return {!Array.} Array of diff tuples. - * @private - */ - DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) { - var a, diffs, linearray, pointer, countInsert, countDelete, textInsert, textDelete, j; - - // Scan the text on a line-by-line basis first. - a = this.diffLinesToChars(text1, text2); - text1 = a.chars1; - text2 = a.chars2; - linearray = a.lineArray; - diffs = this.DiffMain(text1, text2, false, deadline); - - // Convert the diff back to original text. - this.diffCharsToLines(diffs, linearray); - - // Eliminate freak matches (e.g. blank lines) - this.diffCleanupSemantic(diffs); - - // Rediff any replacement blocks, this time character-by-character. - // Add a dummy entry at the end. - diffs.push([DIFF_EQUAL, '']); - pointer = 0; - countDelete = 0; - countInsert = 0; - textDelete = ''; - textInsert = ''; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - countInsert++; - textInsert += diffs[pointer][1]; - break; - case DIFF_DELETE: - countDelete++; - textDelete += diffs[pointer][1]; - break; - case DIFF_EQUAL: - // Upon reaching an equality, check for prior redundancies. - if (countDelete >= 1 && countInsert >= 1) { - // Delete the offending records and add the merged ones. - diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert); - pointer = pointer - countDelete - countInsert; - a = this.DiffMain(textDelete, textInsert, false, deadline); - for (j = a.length - 1; j >= 0; j--) { - diffs.splice(pointer, 0, a[j]); - } - pointer = pointer + a.length; - } - countInsert = 0; - countDelete = 0; - textDelete = ''; - textInsert = ''; - break; - } - pointer++; + }); + function stripHtml(string) { + // Strip tags, html entity and whitespaces + return string.replace(/<\/?[^>]+(>|$)/g, '').replace(/"/g, '').replace(/\s+/g, ''); + } + QUnit.log(function (details) { + var testItem = id('qunit-test-output-' + details.testId); + if (!testItem) { + return; } - diffs.pop(); // Remove the dummy entry at the end. - - return diffs; - }; + var message = escapeText(details.message) || (details.result ? 'okay' : 'failed'); + message = "" + message + ''; + message += "@ " + details.runtime + ' ms'; + var expected; + var actual; + var diff; + var showDiff = false; - /** - * Find the 'middle snake' of a diff, split the problem in two - * and return the recursively constructed diff. - * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} deadline Time at which to bail if not yet complete. - * @return {!Array.} Array of diff tuples. - * @private - */ - DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) { - var text1Length, text2Length, maxD, vOffset, vLength, v1, v2, x, delta, front, k1start, k1end, k2start, k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2; - - // Cache the text lengths to prevent multiple calls. - text1Length = text1.length; - text2Length = text2.length; - maxD = Math.ceil((text1Length + text2Length) / 2); - vOffset = maxD; - vLength = 2 * maxD; - v1 = new Array(vLength); - v2 = new Array(vLength); - - // Setting all elements to -1 is faster in Chrome & Firefox than mixing - // integers and undefined. - for (x = 0; x < vLength; x++) { - v1[x] = -1; - v2[x] = -1; - } - v1[vOffset + 1] = 0; - v2[vOffset + 1] = 0; - delta = text1Length - text2Length; - - // If the total number of characters is odd, then the front path will collide - // with the reverse path. - front = delta % 2 !== 0; - - // Offsets for start and end of k loop. - // Prevents mapping of space beyond the grid. - k1start = 0; - k1end = 0; - k2start = 0; - k2end = 0; - for (d = 0; d < maxD; d++) { - // Bail out if deadline is reached. - if (Date.now() > deadline) { - break; + // When pushFailure() is called, it is implied that no expected value + // or diff should be shown, because both expected and actual as undefined. + // + // This must check details.expected existence. If it exists as undefined, + // that's a regular assertion for which to render actual/expected and a diff. + var showAnyValues = !details.result && (details.expected !== undefined || details.actual !== undefined); + if (showAnyValues) { + if (details.negative) { + expected = 'NOT ' + QUnit.dump.parse(details.expected); + } else { + expected = QUnit.dump.parse(details.expected); } - - // Walk the front path one step. - for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { - k1Offset = vOffset + k1; - if (k1 === -d || k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1]) { - x1 = v1[k1Offset + 1]; - } else { - x1 = v1[k1Offset - 1] + 1; - } - y1 = x1 - k1; - while (x1 < text1Length && y1 < text2Length && text1.charAt(x1) === text2.charAt(y1)) { - x1++; - y1++; - } - v1[k1Offset] = x1; - if (x1 > text1Length) { - // Ran off the right of the graph. - k1end += 2; - } else if (y1 > text2Length) { - // Ran off the bottom of the graph. - k1start += 2; - } else if (front) { - k2Offset = vOffset + delta - k1; - if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) { - // Mirror x2 onto top-left coordinate system. - x2 = text1Length - v2[k2Offset]; - if (x1 >= x2) { - // Overlap detected. - return this.diffBisectSplit(text1, text2, x1, y1, deadline); - } + actual = QUnit.dump.parse(details.actual); + message += "'; + if (actual !== expected) { + message += "'; + if (typeof details.actual === 'number' && typeof details.expected === 'number') { + if (!isNaN(details.actual) && !isNaN(details.expected)) { + showDiff = true; + diff = details.actual - details.expected; + diff = (diff > 0 ? '+' : '') + diff; } - } - } + } else if (typeof details.actual !== 'boolean' && typeof details.expected !== 'boolean') { + diff = QUnit.diff(expected, actual); - // Walk the reverse path one step. - for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { - k2Offset = vOffset + k2; - if (k2 === -d || k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1]) { - x2 = v2[k2Offset + 1]; - } else { - x2 = v2[k2Offset - 1] + 1; - } - y2 = x2 - k2; - while (x2 < text1Length && y2 < text2Length && text1.charAt(text1Length - x2 - 1) === text2.charAt(text2Length - y2 - 1)) { - x2++; - y2++; + // don't show diff if there is zero overlap + showDiff = stripHtml(diff).length !== stripHtml(expected).length + stripHtml(actual).length; } - v2[k2Offset] = x2; - if (x2 > text1Length) { - // Ran off the left of the graph. - k2end += 2; - } else if (y2 > text2Length) { - // Ran off the top of the graph. - k2start += 2; - } else if (!front) { - k1Offset = vOffset + delta - k2; - if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) { - x1 = v1[k1Offset]; - y1 = vOffset + x1 - k1Offset; - - // Mirror x2 onto top-left coordinate system. - x2 = text1Length - x2; - if (x1 >= x2) { - // Overlap detected. - return this.diffBisectSplit(text1, text2, x1, y1, deadline); - } - } + if (showDiff) { + message += "'; } + } else if (expected.indexOf('[object Array]') !== -1 || expected.indexOf('[object Object]') !== -1) { + message += "'; + } else { + message += "'; } - } - - // Diff took too long and hit the deadline or - // number of diffs equals number of characters, no commonality at all. - return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; - }; + if (details.source) { + message += "'; + } + message += '
        Expected:
        " + escapeText(expected) + '
        Result:
        " + escapeText(actual) + '
        Diff:
        " + diff + '
        Message: " + 'Diff suppressed as the depth of object is more than current max depth (' + QUnit.dump.maxDepth + ').

        Hint: Use QUnit.dump.maxDepth to ' + " run with a higher max depth or " + 'Rerun without max depth.

        Message: " + 'Diff suppressed as the expected and actual results have an equivalent' + ' serialization
        Source:
        " + escapeText(details.source) + '
        '; - /** - * Given the location of the 'middle snake', split the diff in two parts - * and recurse. - * @param {string} text1 Old string to be diffed. - * @param {string} text2 New string to be diffed. - * @param {number} x Index of split point in text1. - * @param {number} y Index of split point in text2. - * @param {number} deadline Time at which to bail if not yet complete. - * @return {!Array.} Array of diff tuples. - * @private - */ - DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) { - var text1a, text1b, text2a, text2b, diffs, diffsb; - text1a = text1.substring(0, x); - text2a = text2.substring(0, y); - text1b = text1.substring(x); - text2b = text2.substring(y); - - // Compute both diffs serially. - diffs = this.DiffMain(text1a, text2a, false, deadline); - diffsb = this.DiffMain(text1b, text2b, false, deadline); - return diffs.concat(diffsb); - }; + // This occurs when pushFailure is set and we have an extracted stack trace + } else if (!details.result && details.source) { + message += '' + "' + '
        Source:
        " + escapeText(details.source) + '
        '; + } + var assertList = testItem.getElementsByTagName('ol')[0]; + var assertLi = document.createElement('li'); + assertLi.className = details.result ? 'pass' : 'fail'; + assertLi.innerHTML = message; + assertList.appendChild(assertLi); + }); + QUnit.testDone(function (details) { + var tests = id('qunit-tests'); + var testItem = id('qunit-test-output-' + details.testId); + if (!tests || !testItem) { + return; + } + removeClass(testItem, 'running'); + var status; + if (details.failed > 0) { + status = 'failed'; + } else if (details.todo) { + status = 'todo'; + } else { + status = details.skipped ? 'skipped' : 'passed'; + } + var assertList = testItem.getElementsByTagName('ol')[0]; + var good = details.passed; + var bad = details.failed; - /** - * Reduce the number of edits by eliminating semantically trivial equalities. - * @param {!Array.} diffs Array of diff tuples. - */ - DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) { - var changes = false; - var equalities = []; // Stack of indices where equalities are found. - var equalitiesLength = 0; // Keeping our own length var is faster in JS. - /** @type {?string} */ - var lastequality = null; - - // Always equal to diffs[equalities[equalitiesLength - 1]][1] - var pointer = 0; // Index of current position. - - // Number of characters that changed prior to the equality. - var lengthInsertions1 = 0; - var lengthDeletions1 = 0; - - // Number of characters that changed after the equality. - var lengthInsertions2 = 0; - var lengthDeletions2 = 0; - while (pointer < diffs.length) { - if (diffs[pointer][0] === DIFF_EQUAL) { - // Equality found. - equalities[equalitiesLength++] = pointer; - lengthInsertions1 = lengthInsertions2; - lengthDeletions1 = lengthDeletions2; - lengthInsertions2 = 0; - lengthDeletions2 = 0; - lastequality = diffs[pointer][1]; - } else { - // An insertion or deletion. - if (diffs[pointer][0] === DIFF_INSERT) { - lengthInsertions2 += diffs[pointer][1].length; + // This test passed if it has no unexpected failed assertions + var testPassed = details.failed > 0 ? details.todo : !details.todo; + if (testPassed) { + // Collapse the passing tests + addClass(assertList, 'qunit-collapsed'); + } else { + stats.failedTests.push(details.testId); + if (config.collapse) { + if (!collapseNext) { + // Skip collapsing the first failing test + collapseNext = true; } else { - lengthDeletions2 += diffs[pointer][1].length; - } - - // Eliminate an equality that is smaller or equal to the edits on both - // sides of it. - if (lastequality && lastequality.length <= Math.max(lengthInsertions1, lengthDeletions1) && lastequality.length <= Math.max(lengthInsertions2, lengthDeletions2)) { - // Duplicate record. - diffs.splice(equalities[equalitiesLength - 1], 0, [DIFF_DELETE, lastequality]); - - // Change second copy to insert. - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - - // Throw away the equality we just deleted. - equalitiesLength--; - - // Throw away the previous equality (it needs to be reevaluated). - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - - // Reset the counters. - lengthInsertions1 = 0; - lengthDeletions1 = 0; - lengthInsertions2 = 0; - lengthDeletions2 = 0; - lastequality = null; - changes = true; + // Collapse remaining tests + addClass(assertList, 'qunit-collapsed'); } } - pointer++; } - // Normalize the diff. - if (changes) { - this.diffCleanupMerge(diffs); - } - var deletion, insertion, overlapLength1, overlapLength2; - - // Find any overlaps between deletions and insertions. - // e.g: abcxxxxxxdef - // -> abcxxxdef - // e.g: xxxabcdefxxx - // -> defxxxabc - // Only extract an overlap if it is as big as the edit ahead or behind it. - pointer = 1; - while (pointer < diffs.length) { - if (diffs[pointer - 1][0] === DIFF_DELETE && diffs[pointer][0] === DIFF_INSERT) { - deletion = diffs[pointer - 1][1]; - insertion = diffs[pointer][1]; - overlapLength1 = this.diffCommonOverlap(deletion, insertion); - overlapLength2 = this.diffCommonOverlap(insertion, deletion); - if (overlapLength1 >= overlapLength2) { - if (overlapLength1 >= deletion.length / 2 || overlapLength1 >= insertion.length / 2) { - // Overlap found. Insert an equality and trim the surrounding edits. - diffs.splice(pointer, 0, [DIFF_EQUAL, insertion.substring(0, overlapLength1)]); - diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlapLength1); - diffs[pointer + 1][1] = insertion.substring(overlapLength1); - pointer++; - } - } else { - if (overlapLength2 >= deletion.length / 2 || overlapLength2 >= insertion.length / 2) { - // Reverse overlap found. - // Insert an equality and swap and trim the surrounding edits. - diffs.splice(pointer, 0, [DIFF_EQUAL, deletion.substring(0, overlapLength2)]); - diffs[pointer - 1][0] = DIFF_INSERT; - diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlapLength2); - diffs[pointer + 1][0] = DIFF_DELETE; - diffs[pointer + 1][1] = deletion.substring(overlapLength2); - pointer++; - } - } - pointer++; + // The testItem.firstChild is the test name + var testTitle = testItem.firstChild; + var testCounts = bad ? "" + bad + ', ' + "" + good + ', ' : ''; + testTitle.innerHTML += " (" + testCounts + details.assertions.length + ')'; + stats.completed++; + if (details.skipped) { + testItem.className = 'skipped'; + var skipped = document.createElement('em'); + skipped.className = 'qunit-skipped-label'; + skipped.innerHTML = 'skipped'; + testItem.insertBefore(skipped, testTitle); + } else { + addEvent(testTitle, 'click', function () { + toggleClass(assertList, 'qunit-collapsed'); + }); + testItem.className = testPassed ? 'pass' : 'fail'; + if (details.todo) { + var todoLabel = document.createElement('em'); + todoLabel.className = 'qunit-todo-label'; + todoLabel.innerHTML = 'todo'; + testItem.className += ' todo'; + testItem.insertBefore(todoLabel, testTitle); } - pointer++; + var time = document.createElement('span'); + time.className = 'runtime'; + time.innerHTML = details.runtime + ' ms'; + testItem.insertBefore(time, assertList); } - }; - /** - * Determine if the suffix of one string is the prefix of another. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {number} The number of characters common to the end of the first - * string and the start of the second string. - * @private - */ - DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) { - // Cache the text lengths to prevent multiple calls. - var text1Length = text1.length; - var text2Length = text2.length; - - // Eliminate the null case. - if (text1Length === 0 || text2Length === 0) { - return 0; + // Show the source of the test when showing assertions + if (details.source) { + var sourceName = document.createElement('p'); + sourceName.innerHTML = 'Source: ' + escapeText(details.source); + addClass(sourceName, 'qunit-source'); + if (testPassed) { + addClass(sourceName, 'qunit-collapsed'); + } + addEvent(testTitle, 'click', function () { + toggleClass(sourceName, 'qunit-collapsed'); + }); + testItem.appendChild(sourceName); } - - // Truncate the longer string. - if (text1Length > text2Length) { - text1 = text1.substring(text1Length - text2Length); - } else if (text1Length < text2Length) { - text2 = text2.substring(0, text1Length); + if (config.hidepassed && (status === 'passed' || details.skipped)) { + // use removeChild instead of remove because of support + hiddenTests.push(testItem); + tests.removeChild(testItem); } - var textLength = Math.min(text1Length, text2Length); - - // Quick check for the worst case. - if (text1 === text2) { - return textLength; + }); + QUnit.on('error', function (error) { + var testItem = appendTest('global failure'); + if (!testItem) { + // HTML Reporter is probably disabled or not yet initialized. + return; } - // Start by looking for a single character match - // and increase length until no match is found. - // Performance analysis: https://neil.fraser.name/news/2010/11/04/ - var best = 0; - var length = 1; - while (true) { - var pattern = text1.substring(textLength - length); - var found = text2.indexOf(pattern); - if (found === -1) { - return best; - } - length += found; - if (found === 0 || text1.substring(textLength - length) === text2.substring(0, length)) { - best = length; - length++; - } + // Render similar to a failed assertion (see above QUnit.log callback) + var message = escapeText(errorString(error)); + message = "" + message + ''; + if (error && error.stack) { + message += '' + "' + '
        Source:
        " + escapeText(error.stack) + '
        '; } - }; + var assertList = testItem.getElementsByTagName('ol')[0]; + var assertLi = document.createElement('li'); + assertLi.className = 'fail'; + assertLi.innerHTML = message; + assertList.appendChild(assertLi); - /** - * Split two texts into an array of strings. Reduce the texts to a string of - * hashes where each Unicode character represents one line. - * @param {string} text1 First string. - * @param {string} text2 Second string. - * @return {{chars1: string, chars2: string, lineArray: !Array.}} - * An object containing the encoded text1, the encoded text2 and - * the array of unique strings. - * The zeroth element of the array of unique strings is intentionally blank. - * @private - */ - DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) { - var lineArray = []; // E.g. lineArray[4] === 'Hello\n' - var lineHash = {}; // E.g. lineHash['Hello\n'] === 4 + // Make it visible + testItem.className = 'fail'; + }); - // '\x00' is a valid character, but various debuggers don't like it. - // So we'll insert a junk entry to avoid generating a null character. - lineArray[0] = ''; + // Avoid readyState issue with phantomjs + // Ref: #818 + var usingPhantom = function (p) { + return p && p.version && p.version.major > 0; + }(window$1.phantom); + if (usingPhantom) { + console$1.warn('Support for PhantomJS is deprecated and will be removed in QUnit 3.0.'); + } + if (!usingPhantom && document.readyState === 'complete') { + QUnit.autostart(); + } else { + addEvent(window$1, 'load', QUnit.autostart); + } - /** - * Split a text into an array of strings. Reduce the texts to a string of - * hashes where each Unicode character represents one line. - * Modifies linearray and linehash through being a closure. - * @param {string} text String to encode. - * @return {string} Encoded string. - * @private - */ - function diffLinesToCharsMunge(text) { - var chars = ''; - - // Walk the text, pulling out a substring for each line. - // text.split('\n') would would temporarily double our memory footprint. - // Modifying text would create many large strings to garbage collect. - var lineStart = 0; - var lineEnd = -1; - - // Keeping our own length variable is faster than looking it up. - var lineArrayLength = lineArray.length; - while (lineEnd < text.length - 1) { - lineEnd = text.indexOf('\n', lineStart); - if (lineEnd === -1) { - lineEnd = text.length - 1; - } - var line = text.substring(lineStart, lineEnd + 1); - lineStart = lineEnd + 1; - if (hasOwn.call(lineHash, line)) { - chars += String.fromCharCode(lineHash[line]); - } else { - chars += String.fromCharCode(lineArrayLength); - lineHash[line] = lineArrayLength; - lineArray[lineArrayLength++] = line; - } - } - return chars; - } - var chars1 = diffLinesToCharsMunge(text1); - var chars2 = diffLinesToCharsMunge(text2); - return { - chars1: chars1, - chars2: chars2, - lineArray: lineArray - }; - }; + // Wrap window.onerror. We will call the original window.onerror to see if + // the existing handler fully handles the error; if not, we will call the + // QUnit.onError function. + var originalWindowOnError = window$1.onerror; - /** - * Rehydrate the text in a diff from a string of line hashes to real lines of - * text. - * @param {!Array.} diffs Array of diff tuples. - * @param {!Array.} lineArray Array of unique strings. - * @private - */ - DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) { - for (var x = 0; x < diffs.length; x++) { - var chars = diffs[x][1]; - var text = []; - for (var y = 0; y < chars.length; y++) { - text[y] = lineArray[chars.charCodeAt(y)]; + // Cover uncaught exceptions + // Returning true will suppress the default browser handler, + // returning false will let it run. + window$1.onerror = function (message, fileName, lineNumber, columnNumber, errorObj) { + var ret = false; + if (originalWindowOnError) { + for (var _len = arguments.length, args = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) { + args[_key - 5] = arguments[_key]; } - diffs[x][1] = text.join(''); + ret = originalWindowOnError.call.apply(originalWindowOnError, [this, message, fileName, lineNumber, columnNumber, errorObj].concat(args)); } - }; - - /** - * Reorder and merge like edit sections. Merge equalities. - * Any edit section can move as long as it doesn't cross an equality. - * @param {!Array.} diffs Array of diff tuples. - */ - DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) { - diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. - var pointer = 0; - var countDelete = 0; - var countInsert = 0; - var textDelete = ''; - var textInsert = ''; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - countInsert++; - textInsert += diffs[pointer][1]; - pointer++; - break; - case DIFF_DELETE: - countDelete++; - textDelete += diffs[pointer][1]; - pointer++; - break; - case DIFF_EQUAL: - // Upon reaching an equality, check for prior redundancies. - if (countDelete + countInsert > 1) { - if (countDelete !== 0 && countInsert !== 0) { - // Factor out any common prefixes. - var commonlength = this.diffCommonPrefix(textInsert, textDelete); - if (commonlength !== 0) { - if (pointer - countDelete - countInsert > 0 && diffs[pointer - countDelete - countInsert - 1][0] === DIFF_EQUAL) { - diffs[pointer - countDelete - countInsert - 1][1] += textInsert.substring(0, commonlength); - } else { - diffs.splice(0, 0, [DIFF_EQUAL, textInsert.substring(0, commonlength)]); - pointer++; - } - textInsert = textInsert.substring(commonlength); - textDelete = textDelete.substring(commonlength); - } - - // Factor out any common suffixies. - commonlength = this.diffCommonSuffix(textInsert, textDelete); - if (commonlength !== 0) { - diffs[pointer][1] = textInsert.substring(textInsert.length - commonlength) + diffs[pointer][1]; - textInsert = textInsert.substring(0, textInsert.length - commonlength); - textDelete = textDelete.substring(0, textDelete.length - commonlength); - } - } - // Delete the offending records and add the merged ones. - if (countDelete === 0) { - diffs.splice(pointer - countInsert, countDelete + countInsert, [DIFF_INSERT, textInsert]); - } else if (countInsert === 0) { - diffs.splice(pointer - countDelete, countDelete + countInsert, [DIFF_DELETE, textDelete]); - } else { - diffs.splice(pointer - countDelete - countInsert, countDelete + countInsert, [DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]); - } - pointer = pointer - countDelete - countInsert + (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1; - } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { - // Merge this equality with the previous one. - diffs[pointer - 1][1] += diffs[pointer][1]; - diffs.splice(pointer, 1); - } else { - pointer++; - } - countInsert = 0; - countDelete = 0; - textDelete = ''; - textInsert = ''; - break; - } - } - if (diffs[diffs.length - 1][1] === '') { - diffs.pop(); // Remove the dummy entry at the end. - } - - // Second pass: look for single edits surrounded on both sides by equalities - // which can be shifted sideways to eliminate an equality. - // e.g: ABAC -> ABAC - var changes = false; - pointer = 1; - - // Intentionally ignore the first and last element (don't need checking). - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { - var diffPointer = diffs[pointer][1]; - var position = diffPointer.substring(diffPointer.length - diffs[pointer - 1][1].length); - - // This is a single edit surrounded by equalities. - if (position === diffs[pointer - 1][1]) { - // Shift the edit over the previous equality. - diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); - diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; - diffs.splice(pointer - 1, 1); - changes = true; - } else if (diffPointer.substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { - // Shift the edit over the next equality. - diffs[pointer - 1][1] += diffs[pointer + 1][1]; - diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; - diffs.splice(pointer + 1, 1); - changes = true; - } + // Treat return value as window.onerror itself does, + // Only do our handling if not suppressed. + if (ret !== true) { + // If there is a current test that sets the internal `ignoreGlobalErrors` field + // (such as during `assert.throws()`), then the error is ignored and native + // error reporting is suppressed as well. This is because in browsers, an error + // can sometimes end up in `window.onerror` instead of in the local try/catch. + // This ignoring of errors does not apply to our general onUncaughtException + // method, nor to our `unhandledRejection` handlers, as those are not meant + // to receive an "expected" error during `assert.throws()`. + if (config.current && config.current.ignoreGlobalErrors) { + return true; } - pointer++; - } - // If shifts were made, the diff needs reordering and another shift sweep. - if (changes) { - this.diffCleanupMerge(diffs); + // According to + // https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror, + // most modern browsers support an errorObj argument; use that to + // get a full stack trace if it's available. + var error = errorObj || new Error(message); + if (!error.stack && fileName && lineNumber) { + error.stack = "".concat(fileName, ":").concat(lineNumber); + } + QUnit.onUncaughtException(error); } + return ret; }; - return function (o, n) { - var diff, output, text; - diff = new DiffMatchPatch(); - output = diff.DiffMain(o, n); - diff.diffCleanupEfficiency(output); - text = diff.diffPrettyHtml(output); - return text; - }; - }(); + window$1.addEventListener('unhandledrejection', function (event) { + QUnit.onUncaughtException(event.reason); + }); + })(); })(); diff --git a/wicket-examples/src/main/webapp/js-test/tests/ajax/form.js b/wicket-examples/src/main/webapp/js-test/tests/ajax/form.js index 6b79e070293..a5ed3af1156 100644 --- a/wicket-examples/src/main/webapp/js-test/tests/ajax/form.js +++ b/wicket-examples/src/main/webapp/js-test/tests/ajax/form.js @@ -34,7 +34,7 @@ $q(document).ready(function() { $emailInput = $('input[name=email]', $form); // enter just the name field - $nameInput.focus(); + $nameInput.trigger('focus'); var name = 'Aj'; $nameInput.val(name); @@ -84,7 +84,7 @@ $q(document).ready(function() { $emailInput = $('input[name=email]', $form); // enter just the name field - $nameInput.focus(); + $nameInput.trigger('focus'); var name = 'abcdef'; $nameInput.val(name); diff --git a/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/autocomplete/wicket-autocomplete.js b/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/autocomplete/wicket-autocomplete.js index eb3afea13dd..e194d294d24 100644 --- a/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/autocomplete/wicket-autocomplete.js +++ b/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/autocomplete/wicket-autocomplete.js @@ -665,7 +665,7 @@ if (document.activeElement !== input) { ignoreOneFocusGain = true; - input.focus(); + input.trigger('focus'); } return true; }; diff --git a/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/modal/trap-focus.js b/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/modal/trap-focus.js index 63bf36f0d41..8157833042b 100644 --- a/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/modal/trap-focus.js +++ b/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/modal/trap-focus.js @@ -70,12 +70,12 @@ if (e.shiftKey) { if (e.target === firstFocusable || $element.is(e.target)) { e.preventDefault(); - lastFocusable.focus(); + lastFocusable.trigger('focus'); } } else { if (e.target === lastFocusable || $element.is(e.target)) { e.preventDefault(); - firstFocusable.focus(); + firstFocusable.trigger('focus'); } } } @@ -91,13 +91,13 @@ $(document).off("focusin", focusin); // ... pull in focus - findFocusable($element).first().focus(); + findFocusable($element).first().trigger('focus'); // ... and install new handler focusin = function() { if (!$.contains($element[0], document.activeElement) && $element[0] !== document.activeElement) { // focus is outside of element, so pull in focus - findFocusable($element).first().focus(); + findFocusable($element).first().trigger('focus'); } }; $(document).on("focusin", focusin); @@ -110,7 +110,7 @@ // ... restore old focus if (oldActive) { try { - oldActive.focus(); + oldActive.trigger('focus'); Wicket.Log.debug("trap-focus: restored focus to element ", oldActive); } catch (error) { Wicket.Log.error("trap-focus: error restoring focus. Attempted to set focus to element, but got an exception", oldActive, error); diff --git a/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/form/palette/palette.js b/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/form/palette/palette.js index 16ec0148f87..16df1386fd7 100644 --- a/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/form/palette/palette.js +++ b/wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/form/palette/palette.js @@ -86,7 +86,7 @@ if(!box.options[i-1].selected) { box.insertBefore(box.options[i],box.options[i-1]); dirty=true; - box.focus(); + box.trigger('focus'); } } } From a8e1a3d0ed134395daf066ac70cc972cd8a439dc Mon Sep 17 00:00:00 2001 From: Martin Grigorov Date: Thu, 30 Apr 2026 10:45:32 +0300 Subject: [PATCH 2/2] Test both jQuery 4.x and 3.x --- testing/wicket-js-tests/Gruntfile.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/testing/wicket-js-tests/Gruntfile.js b/testing/wicket-js-tests/Gruntfile.js index 85eda6ed714..6ee82e34ce6 100644 --- a/testing/wicket-js-tests/Gruntfile.js +++ b/testing/wicket-js-tests/Gruntfile.js @@ -106,7 +106,8 @@ module.exports = function(grunt) { all: { options: { urls: [ - 'http://localhost:38887/test/js/all.html?4.0.0' + 'http://localhost:38887/test/js/all.html?4.0.0', + 'http://localhost:38887/test/js/all.html?3.7.1' ], puppeteer: { headless: true,