diff --git a/node_modules/side-channel-map/CHANGELOG.md b/node_modules/side-channel-map/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b6ccea906b109d2fbdeab5033ef37fcf3c677451 --- /dev/null +++ b/node_modules/side-channel-map/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/side-channel-map/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [Deps] update `call-bound` [`6d05aaa`](https://github.com/ljharb/side-channel-map/commit/6d05aaa4ce5f2be4e7825df433d650696f0ba40f) +- [types] fix generics ordering [`11c0184`](https://github.com/ljharb/side-channel-map/commit/11c0184132ac11fdc16857e12682e148e5e9ee74) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`ad877b4`](https://github.com/ljharb/side-channel-map/commit/ad877b42926d46d63fff76a2bd01d2b4a01959a9) +- Initial commit [`28f8879`](https://github.com/ljharb/side-channel-map/commit/28f8879c512abe8fcf9b6a4dc7754a0287e5eba4) +- npm init [`2c9604e`](https://github.com/ljharb/side-channel-map/commit/2c9604e5aa40223e425ea7cea78f8a07697504bd) +- Only apps should have lockfiles [`5e7ba9c`](https://github.com/ljharb/side-channel-map/commit/5e7ba9cffe3ef42095815adc8ac1255b49bbadf5) diff --git a/node_modules/side-channel-map/LICENSE b/node_modules/side-channel-map/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f82f38963b0d282b529f64def2bcd40be3a9a947 --- /dev/null +++ b/node_modules/side-channel-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel-map/README.md b/node_modules/side-channel-map/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8fa6f77f07d10658117ff4f4ed4af647e3bd7c40 --- /dev/null +++ b/node_modules/side-channel-map/README.md @@ -0,0 +1,62 @@ +# side-channel-map [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a Map. + +Warning: if the `key` is an object, this implementation will leak memory until you `delete` it. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-map +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelMap = require('side-channel-map'); + +const channel = getSideChannelMap(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-map +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-map.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-map.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-map +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-map/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-map#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-map.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-map.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-map.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-map +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-map/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-map/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-map +[actions-url]: https://github.com/ljharb/side-channel-map/actions diff --git a/node_modules/side-channel-map/index.d.ts b/node_modules/side-channel-map/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de33e899e66db27eac77bb85d1b8afe183272e85 --- /dev/null +++ b/node_modules/side-channel-map/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelMap(): getSideChannelMap.Channel; + +declare const x: false | typeof getSideChannelMap; + +export = x; diff --git a/node_modules/side-channel-map/index.js b/node_modules/side-channel-map/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e111100bfd6cc8b296a20276d8238e3a910f676d --- /dev/null +++ b/node_modules/side-channel-map/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $Map = GetIntrinsic('%Map%', true); + +/** @type {(thisArg: Map, key: K) => V} */ +var $mapGet = callBound('Map.prototype.get', true); +/** @type {(thisArg: Map, key: K, value: V) => void} */ +var $mapSet = callBound('Map.prototype.set', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapHas = callBound('Map.prototype.has', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapDelete = callBound('Map.prototype.delete', true); +/** @type {(thisArg: Map) => number} */ +var $mapSize = callBound('Map.prototype.size', true); + +/** @type {import('.')} */ +module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; +}; diff --git a/node_modules/side-channel-map/package.json b/node_modules/side-channel-map/package.json new file mode 100644 index 0000000000000000000000000000000000000000..18e80805905c32cf286aa286e1a0c8f8248ec574 --- /dev/null +++ b/node_modules/side-channel-map/package.json @@ -0,0 +1,80 @@ +{ + "name": "side-channel-map", + "version": "1.0.1", + "description": "Store information about any JS value in a side channel, using a Map", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-map.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-map/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-map#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-map/test/index.js b/node_modules/side-channel-map/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..17433239ee490b8f734c5c60198eae699e201c65 --- /dev/null +++ b/node_modules/side-channel-map/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelMap = require('../'); + +test('getSideChannelMap', { skip: typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no Maps', { skip: typeof Map === 'function' }, function (t) { + t.equal(getSideChannelMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-map/tsconfig.json b/node_modules/side-channel-map/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/side-channel-map/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-weakmap/.editorconfig b/node_modules/side-channel-weakmap/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..72e0ebaa7f319d2bde03e55c8e58748245095f06 --- /dev/null +++ b/node_modules/side-channel-weakmap/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-weakmap/.eslintrc b/node_modules/side-channel-weakmap/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9b13ad8ba555410581c1b389ca2cdfbd9d91310d --- /dev/null +++ b/node_modules/side-channel-weakmap/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-weakmap/.github/FUNDING.yml b/node_modules/side-channel-weakmap/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ae71cdb9425d0394e2ee363df151086c081c4c9 --- /dev/null +++ b/node_modules/side-channel-weakmap/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-weakmap +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-weakmap/.nycrc b/node_modules/side-channel-weakmap/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/side-channel-weakmap/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-weakmap/CHANGELOG.md b/node_modules/side-channel-weakmap/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..aba7ab0412975a41899d61be28ff104c1db3fbf8 --- /dev/null +++ b/node_modules/side-channel-weakmap/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`1b62e94`](https://github.com/ljharb/side-channel-weakmap/commit/1b62e94a2ad6ed30b640ba73c4a2535836c67289) + +## [v1.0.1](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`08a4a5d`](https://github.com/ljharb/side-channel-weakmap/commit/08a4a5dbffedc3ebc79f1aaaf5a3dd6d2196dc1b) +- [Deps] update `side-channel-map` [`b53fe44`](https://github.com/ljharb/side-channel-weakmap/commit/b53fe447dfdd3a9aebedfd015b384eac17fce916) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`53c0fa4`](https://github.com/ljharb/side-channel-weakmap/commit/53c0fa4788435a006f58b9d7b43cb65989ecee49) +- Initial commit [`a157947`](https://github.com/ljharb/side-channel-weakmap/commit/a157947f26fcaf2c4a941d3a044e76bf67343532) +- npm init [`54dfc55`](https://github.com/ljharb/side-channel-weakmap/commit/54dfc55bafb16265910d5aad4e743c43aee5bbbb) +- Only apps should have lockfiles [`0ddd6c7`](https://github.com/ljharb/side-channel-weakmap/commit/0ddd6c7b07fe8ee04d67b2e9f7255af7ce62c07d) diff --git a/node_modules/side-channel-weakmap/LICENSE b/node_modules/side-channel-weakmap/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3900dd7e2ffe6d5205fde1cd3f890aa51ea36234 --- /dev/null +++ b/node_modules/side-channel-weakmap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/side-channel-weakmap/README.md b/node_modules/side-channel-weakmap/README.md new file mode 100644 index 0000000000000000000000000000000000000000..856ee3643b0832a52930b5e346539d9593640094 --- /dev/null +++ b/node_modules/side-channel-weakmap/README.md @@ -0,0 +1,62 @@ +# side-channel-weakmap [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-weakmap +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-weakmap'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-weakmap +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-weakmap.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-weakmap +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-weakmap#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-weakmap.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-weakmap.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-weakmap.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-weakmap +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-weakmap/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-weakmap/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-weakmap +[actions-url]: https://github.com/ljharb/side-channel-weakmap/actions diff --git a/node_modules/side-channel-weakmap/index.d.ts b/node_modules/side-channel-weakmap/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce1bc2a4ae2ea0be0eac679b305b6d20d69a7793 --- /dev/null +++ b/node_modules/side-channel-weakmap/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelWeakMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + } +} + +declare function getSideChannelWeakMap(): getSideChannelWeakMap.Channel; + +declare const x: false | typeof getSideChannelWeakMap; + +export = x; diff --git a/node_modules/side-channel-weakmap/index.js b/node_modules/side-channel-weakmap/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e5b8183d9717d5917efee321be4bf12c01c025cb --- /dev/null +++ b/node_modules/side-channel-weakmap/index.js @@ -0,0 +1,84 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); +var getSideChannelMap = require('side-channel-map'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); + +/** @type {(thisArg: WeakMap, key: K) => V} */ +var $weakMapGet = callBound('WeakMap.prototype.get', true); +/** @type {(thisArg: WeakMap, key: K, value: V) => void} */ +var $weakMapSet = callBound('WeakMap.prototype.set', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapHas = callBound('WeakMap.prototype.has', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + +/** @type {import('.')} */ +module.exports = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; diff --git a/node_modules/side-channel-weakmap/package.json b/node_modules/side-channel-weakmap/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9ef6583335d8670f8f86c7508cd047c6ae224a68 --- /dev/null +++ b/node_modules/side-channel-weakmap/package.json @@ -0,0 +1,87 @@ +{ + "name": "side-channel-weakmap", + "version": "1.0.2", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-weakmap.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-weakmap/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-weakmap#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-weakmap/test/index.js b/node_modules/side-channel-weakmap/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a01248b5729c1308909cdd62a8344b8de9b19c89 --- /dev/null +++ b/node_modules/side-channel-weakmap/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelWeakMap = require('../'); + +test('getSideChannelMap', { skip: typeof WeakMap !== 'function' && typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelWeakMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no WeakMaps and/or Maps', { skip: typeof WeakMap === 'function' || typeof Map === 'function' }, function (t) { + t.equal(getSideChannelWeakMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-weakmap/tsconfig.json b/node_modules/side-channel-weakmap/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/side-channel-weakmap/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/siginfo/.travis.yml b/node_modules/siginfo/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f54568c078cb484fb8e3f258fceb8b4f4a96252 --- /dev/null +++ b/node_modules/siginfo/.travis.yml @@ -0,0 +1,13 @@ +notifications: + email: false +language: node_js +node_js: +- node +deploy: + provider: npm + email: + secure: Y10Dvn9UbfpZPbulnl/e7dsiN/1xr06h7k6nJZyxRzr9Hh0UUFPism6k5CFaSegyPIF7sODNBQz4lvXIi2NwcvTLQruw5ehXW0NJ/G7x1TU94pzzhVJ31KB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RTLf56+x/kJZ4kVJjHuyb/98pS4F7etJ2SpZqt1cVUFd/AYtnxL3jKiUhJLNL8hNUIH3eSpMfZUOUxGv1OWuwgyEhSONkITF2VPn4yuyxS23Ewq4LLj/u/9sPlLaGSN4Avaw21gi6L+M9x620sTZHYtNLniVMTAu6aPiM32zPreK2I= + on: + tags: true diff --git a/node_modules/siginfo/LICENSE b/node_modules/siginfo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b45703b88a6742577786fa46c73b018dbe75cf26 --- /dev/null +++ b/node_modules/siginfo/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2017, Emil Bay + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/siginfo/README.md b/node_modules/siginfo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3552e2ad95f08f009f8fc6c495d299ddc8ae790e --- /dev/null +++ b/node_modules/siginfo/README.md @@ -0,0 +1,47 @@ +# `siginfo` + +[![Build Status](https://travis-ci.org/emilbayes/siginfo.svg?branch=master)](https://travis-ci.org/eemilbayes/siginfo) + +> Utility module to print pretty messages on SIGINFO/SIGUSR1 + +`SIGINFO` on BSD / macOS and `SIGUSR1` on Linux, usually triggered by +`Ctrl + T`, are by convention used to print information about +a long running process internal state. Eg. `dd` will tell you how many blocks it +has written and at what speed, while `xz` will tell you progress, compression +ratio and estimated time remaining. + +This module wraps both signals, checks if the process is connected to TTY and +lets you do whatever you want. + +## Usage + +```js +var siginfo = require('siginfo') +var pkg = require('./package.json') + +siginfo(function () { + console.dir({ + version: pkg.version, + uptime: process.uptime() + }) +}) + +``` + +## API + +### `var removeListener = siginfo(queryFn, [force])` + +`queryFn` can be used for whatever you want (logging, sending a UDP message, etc.). +Setting `force = true` will attach the event handlers whether a TTY is present +or not. + +## Install + +```sh +npm install siginfo +``` + +## License + +[ISC](LICENSE) diff --git a/node_modules/siginfo/index.js b/node_modules/siginfo/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5092b6115d70e97ec511c1ed98e622f83eef9925 --- /dev/null +++ b/node_modules/siginfo/index.js @@ -0,0 +1,20 @@ +module.exports = function (query, force) { + var isAttached = false + if (process.stderr.isTTY || force === true) { + isAttached = true + process.on('SIGINFO', onsiginfo) + process.on('SIGUSR1', onsiginfo) + } + + return function () { + if (isAttached === true) { + process.removeListener('SIGINFO', onsiginfo) + process.removeListener('SIGUSR1', onsiginfo) + isAttached = false + } + } + + function onsiginfo () { + query() + } +} diff --git a/node_modules/siginfo/package.json b/node_modules/siginfo/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f0e7154346583f6d5df9c690ef0abc76531e6dc --- /dev/null +++ b/node_modules/siginfo/package.json @@ -0,0 +1,32 @@ +{ + "name": "siginfo", + "version": "2.0.0", + "description": "Utility module to print pretty messages on SIGINFO/SIGUSR1", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^14.3.4" + }, + "scripts": { + "test": "standard" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/emilbayes/siginfo.git" + }, + "keywords": [ + "siginfo", + "sigusr1", + "ctrl", + "t", + "info", + "progress", + "inspect" + ], + "author": "Emil Bay ", + "license": "ISC", + "bugs": { + "url": "https://github.com/emilbayes/siginfo/issues" + }, + "homepage": "https://github.com/emilbayes/siginfo#readme" +} diff --git a/node_modules/siginfo/test.js b/node_modules/siginfo/test.js new file mode 100644 index 0000000000000000000000000000000000000000..eaf6824f64e295ce5ff64a08fcc316fc9524ed9d --- /dev/null +++ b/node_modules/siginfo/test.js @@ -0,0 +1,16 @@ +var siginfo = require('.') +var pkg = require('./package.json') + +var stop = siginfo(function () { + console.dir({ + version: pkg.version, + uptime: process.uptime() + }) +}) + +process.stdout.resume() + +setTimeout(function () { + stop() + process.exit(0) +}, 2000) diff --git a/node_modules/signal-exit/LICENSE.txt b/node_modules/signal-exit/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..954f2fa8235009998fe29a775bbaf8c23f5e2d50 --- /dev/null +++ b/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/signal-exit/README.md b/node_modules/signal-exit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c55cd45ee316e8025759f5da2a124446814cc387 --- /dev/null +++ b/node_modules/signal-exit/README.md @@ -0,0 +1,74 @@ +# signal-exit + +When you want to fire an event no matter how a process exits: + +- reaching the end of execution. +- explicitly having `process.exit(code)` called. +- having `process.kill(pid, sig)` called. +- receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +// Hybrid module, either works +import { onExit } from 'signal-exit' +// or: +// const { onExit } = require('signal-exit') + +onExit((code, signal) => { + console.log('process exited!', code, signal) +}) +``` + +## API + +`remove = onExit((code, signal) => {}, options)` + +The return value of the function is a function that will remove +the handler. + +Note that the function _only_ fires for signals if the signal +would cause the process to exit. That is, there are no other +listeners, and it is a fatal signal. + +If the global `process` object is not suitable for this purpose +(ie, it's unset, or doesn't have an `emit` method, etc.) then the +`onExit` function is a no-op that returns a no-op `remove` method. + +### Options + +- `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. + +### Capturing Signal Exits + +If the handler returns an exact boolean `true`, and the exit is a +due to signal, then the signal will be considered handled, and +will _not_ trigger a synthetic `process.kill(process.pid, +signal)` after firing the `onExit` handlers. + +In this case, it your responsibility as the caller to exit with a +signal (for example, by calling `process.kill()`) if you wish to +preserve the same exit status that would otherwise have occurred. +If you do not, then the process will likely exit gracefully with +status 0 at some point, assuming that no other terminating signal +or other exit trigger occurs. + +Prior to calling handlers, the `onExit` machinery is unloaded, so +any subsequent exits or signals will not be handled, even if the +signal is captured and the exit is thus prevented. + +Note that numeric code exits may indicate that the process is +already committed to exiting, for example due to a fatal +exception or unhandled promise rejection, and so there is no way to +prevent it safely. + +### Browser Fallback + +The `'signal-exit/browser'` module is the same fallback shim that +just doesn't do anything, but presents the same function +interface. + +Patches welcome to add something that hooks onto +`window.onbeforeunload` or similar, but it might just not be a +thing that makes sense there. diff --git a/node_modules/signal-exit/package.json b/node_modules/signal-exit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ac176cec743748840fdb8f143beb60bf47e599ac --- /dev/null +++ b/node_modules/signal-exit/package.json @@ -0,0 +1,106 @@ +{ + "name": "signal-exit", + "version": "4.1.0", + "description": "when you want to fire an event no matter how a process exits.", + "main": "./dist/cjs/index.js", + "module": "./dist/mjs/index.js", + "browser": "./dist/mjs/browser.js", + "types": "./dist/mjs/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/mjs/index.d.ts", + "default": "./dist/mjs/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./signals": { + "import": { + "types": "./dist/mjs/signals.d.ts", + "default": "./dist/mjs/signals.js" + }, + "require": { + "types": "./dist/cjs/signals.d.ts", + "default": "./dist/cjs/signals.js" + } + }, + "./browser": { + "import": { + "types": "./dist/mjs/browser.d.ts", + "default": "./dist/mjs/browser.js" + }, + "require": { + "types": "./dist/cjs/browser.d.ts", + "default": "./dist/cjs/browser.js" + } + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=14" + }, + "repository": { + "type": "git", + "url": "https://github.com/tapjs/signal-exit.git" + }, + "keywords": [ + "signal", + "exit" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "@types/cross-spawn": "^6.0.2", + "@types/node": "^18.15.11", + "@types/signal-exit": "^3.0.1", + "@types/tap": "^15.0.8", + "c8": "^7.13.0", + "prettier": "^2.8.6", + "tap": "^16.3.4", + "ts-node": "^10.9.1", + "typedoc": "^0.23.28", + "typescript": "^5.0.2" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "preprepare": "rm -rf dist", + "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "c8 tap", + "snap": "c8 tap", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "tap": { + "coverage": false, + "jobs": 1, + "node-arg": [ + "--no-warnings", + "--loader", + "ts-node/esm" + ], + "ts": false + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/simple-concat/.travis.yml b/node_modules/simple-concat/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..c159f6acecab74f3b3ec5c09a970e9f3c226e667 --- /dev/null +++ b/node_modules/simple-concat/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - lts/* diff --git a/node_modules/simple-concat/LICENSE b/node_modules/simple-concat/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c7e6852752b72edbf0eb6b2adef53f0863ae5876 --- /dev/null +++ b/node_modules/simple-concat/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/simple-concat/README.md b/node_modules/simple-concat/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b7d39bdea998f5dc6ad2c3d9637586eb453a87b3 --- /dev/null +++ b/node_modules/simple-concat/README.md @@ -0,0 +1,44 @@ +# simple-concat [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/simple-concat/master.svg +[travis-url]: https://travis-ci.org/feross/simple-concat +[npm-image]: https://img.shields.io/npm/v/simple-concat.svg +[npm-url]: https://npmjs.org/package/simple-concat +[downloads-image]: https://img.shields.io/npm/dm/simple-concat.svg +[downloads-url]: https://npmjs.org/package/simple-concat +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### Super-minimalist version of [`concat-stream`](https://github.com/maxogden/concat-stream). Less than 15 lines! + +## install + +``` +npm install simple-concat +``` + +## usage + +This example is longer than the implementation. + +```js +var s = new stream.PassThrough() +concat(s, function (err, buf) { + if (err) throw err + console.error(buf) +}) +s.write('abc') +setTimeout(function () { + s.write('123') +}, 10) +setTimeout(function () { + s.write('456') +}, 20) +setTimeout(function () { + s.end('789') +}, 30) +``` + +## license + +MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/simple-concat/index.js b/node_modules/simple-concat/index.js new file mode 100644 index 0000000000000000000000000000000000000000..59237fc6284738fdb149b4c4a9be0e123711a295 --- /dev/null +++ b/node_modules/simple-concat/index.js @@ -0,0 +1,15 @@ +/*! simple-concat. MIT License. Feross Aboukhadijeh */ +module.exports = function (stream, cb) { + var chunks = [] + stream.on('data', function (chunk) { + chunks.push(chunk) + }) + stream.once('end', function () { + if (cb) cb(null, Buffer.concat(chunks)) + cb = null + }) + stream.once('error', function (err) { + if (cb) cb(err) + cb = null + }) +} diff --git a/node_modules/simple-concat/package.json b/node_modules/simple-concat/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2bb2c60a2f9e995a7e3d5c94a9c93290ba047aea --- /dev/null +++ b/node_modules/simple-concat/package.json @@ -0,0 +1,47 @@ +{ + "name": "simple-concat", + "description": "Super-minimalist version of `concat-stream`. Less than 15 lines!", + "version": "1.0.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/simple-concat/issues" + }, + "dependencies": {}, + "devDependencies": { + "standard": "*", + "tape": "^5.0.1" + }, + "homepage": "https://github.com/feross/simple-concat", + "keywords": [ + "concat", + "concat-stream", + "concat stream" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/simple-concat.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/simple-concat/test/basic.js b/node_modules/simple-concat/test/basic.js new file mode 100644 index 0000000000000000000000000000000000000000..4bf6f9c2d9d82844996f27791e73defb2c66933e --- /dev/null +++ b/node_modules/simple-concat/test/basic.js @@ -0,0 +1,41 @@ +var concat = require('../') +var stream = require('stream') +var test = require('tape') + +test('basic', function (t) { + t.plan(2) + var s = new stream.PassThrough() + concat(s, function (err, buf) { + t.error(err) + t.deepEqual(buf, Buffer.from('abc123456789')) + }) + s.write('abc') + setTimeout(function () { + s.write('123') + }, 10) + setTimeout(function () { + s.write('456') + }, 20) + setTimeout(function () { + s.end('789') + }, 30) +}) + +test('error', function (t) { + t.plan(2) + var s = new stream.PassThrough() + concat(s, function (err, buf) { + t.ok(err, 'got expected error') + t.ok(!buf) + }) + s.write('abc') + setTimeout(function () { + s.write('123') + }, 10) + setTimeout(function () { + s.write('456') + }, 20) + setTimeout(function () { + s.emit('error', new Error('error')) + }, 30) +}) diff --git a/node_modules/simple-get/.github/dependabot.yml b/node_modules/simple-get/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..0221fbcbc3977776e0c6d60f760fbe147f2e81e5 --- /dev/null +++ b/node_modules/simple-get/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: daily + labels: + - dependency + versioning-strategy: increase-if-necessary + - package-ecosystem: github-actions + directory: / + schedule: + interval: daily + labels: + - dependency diff --git a/node_modules/simple-get/.github/workflows/ci.yml b/node_modules/simple-get/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..822d21cc9d5264b5439f9bfaea12f0e162064cc3 --- /dev/null +++ b/node_modules/simple-get/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: ci +'on': + - push + - pull_request +jobs: + test: + name: Node ${{ matrix.node }} / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + node: + - '14' + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: ${{ matrix.node }} + - run: npm install + - run: npm run build --if-present + - run: npm test diff --git a/node_modules/simple-get/LICENSE b/node_modules/simple-get/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c7e6852752b72edbf0eb6b2adef53f0863ae5876 --- /dev/null +++ b/node_modules/simple-get/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/simple-get/README.md b/node_modules/simple-get/README.md new file mode 100644 index 0000000000000000000000000000000000000000..63c6a6bae8888b6749dcc0fab06816e16ee5d485 --- /dev/null +++ b/node_modules/simple-get/README.md @@ -0,0 +1,333 @@ +# simple-get [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[ci-image]: https://img.shields.io/github/workflow/status/feross/simple-get/ci/master +[ci-url]: https://github.com/feross/simple-get/actions +[npm-image]: https://img.shields.io/npm/v/simple-get.svg +[npm-url]: https://npmjs.org/package/simple-get +[downloads-image]: https://img.shields.io/npm/dm/simple-get.svg +[downloads-url]: https://npmjs.org/package/simple-get +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### Simplest way to make http get requests + +## features + +This module is the lightest possible wrapper on top of node.js `http`, but supporting these essential features: + +- follows redirects +- automatically handles gzip/deflate responses +- supports HTTPS +- supports specifying a timeout +- supports convenience `url` key so there's no need to use `url.parse` on the url when specifying options +- composes well with npm packages for features like cookies, proxies, form data, & OAuth + +All this in < 100 lines of code. + +## install + +``` +npm install simple-get +``` + +## usage + +Note, all these examples also work in the browser with [browserify](http://browserify.org/). + +### simple GET request + +Doesn't get easier than this: + +```js +const get = require('simple-get') + +get('http://example.com', function (err, res) { + if (err) throw err + console.log(res.statusCode) // 200 + res.pipe(process.stdout) // `res` is a stream +}) +``` + +### even simpler GET request + +If you just want the data, and don't want to deal with streams: + +```js +const get = require('simple-get') + +get.concat('http://example.com', function (err, res, data) { + if (err) throw err + console.log(res.statusCode) // 200 + console.log(data) // Buffer('this is the server response') +}) +``` + +### POST, PUT, PATCH, HEAD, DELETE support + +For `POST`, call `get.post` or use option `{ method: 'POST' }`. + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com', + body: 'this is the POST body' +} +get.post(opts, function (err, res) { + if (err) throw err + res.pipe(process.stdout) // `res` is a stream +}) +``` + +#### A more complex example: + +```js +const get = require('simple-get') + +get({ + url: 'http://example.com', + method: 'POST', + body: 'this is the POST body', + + // simple-get accepts all options that node.js `http` accepts + // See: http://nodejs.org/api/http.html#http_http_request_options_callback + headers: { + 'user-agent': 'my cool app' + } +}, function (err, res) { + if (err) throw err + + // All properties/methods from http.IncomingResponse are available, + // even if a gunzip/inflate transform stream was returned. + // See: http://nodejs.org/api/http.html#http_http_incomingmessage + res.setTimeout(10000) + console.log(res.headers) + + res.on('data', function (chunk) { + // `chunk` is the decoded response, after it's been gunzipped or inflated + // (if applicable) + console.log('got a chunk of the response: ' + chunk) + })) + +}) +``` + +### JSON + +You can serialize/deserialize request and response with JSON: + +```js +const get = require('simple-get') + +const opts = { + method: 'POST', + url: 'http://example.com', + body: { + key: 'value' + }, + json: true +} +get.concat(opts, function (err, res, data) { + if (err) throw err + console.log(data.key) // `data` is an object +}) +``` + +### Timeout + +You can set a timeout (in milliseconds) on the request with the `timeout` option. +If the request takes longer than `timeout` to complete, then the entire request +will fail with an `Error`. + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com', + timeout: 2000 // 2 second timeout +} + +get(opts, function (err, res) {}) +``` + +### One Quick Tip + +It's a good idea to set the `'user-agent'` header so the provider can more easily +see how their resource is used. + +```js +const get = require('simple-get') +const pkg = require('./package.json') + +get('http://example.com', { + headers: { + 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)` + } +}) +``` + +### Proxies + +You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the +`agent` option to work with proxies: + +```js +const get = require('simple-get') +const tunnel = require('tunnel') + +const opts = { + url: 'http://example.com', + agent: tunnel.httpOverHttp({ + proxy: { + host: 'localhost' + } + }) +} + +get(opts, function (err, res) {}) +``` + +### Cookies + +You can use the [`cookie`](https://github.com/jshttp/cookie) module to include +cookies in a request: + +```js +const get = require('simple-get') +const cookie = require('cookie') + +const opts = { + url: 'http://example.com', + headers: { + cookie: cookie.serialize('foo', 'bar') + } +} + +get(opts, function (err, res) {}) +``` + +### Form data + +You can use the [`form-data`](https://github.com/form-data/form-data) module to +create POST request with form data: + +```js +const fs = require('fs') +const get = require('simple-get') +const FormData = require('form-data') +const form = new FormData() + +form.append('my_file', fs.createReadStream('/foo/bar.jpg')) + +const opts = { + url: 'http://example.com', + body: form +} + +get.post(opts, function (err, res) {}) +``` + +#### Or, include `application/x-www-form-urlencoded` form data manually: + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com', + form: { + key: 'value' + } +} +get.post(opts, function (err, res) {}) +``` + +### Specifically disallowing redirects + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com/will-redirect-elsewhere', + followRedirects: false +} +// res.statusCode will be 301, no error thrown +get(opts, function (err, res) {}) +``` + +### Basic Auth + +```js +const user = 'someuser' +const pass = 'pa$$word' +const encodedAuth = Buffer.from(`${user}:${pass}`).toString('base64') + +get('http://example.com', { + headers: { + authorization: `Basic ${encodedAuth}` + } +}) +``` + +### OAuth + +You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create +a signed OAuth request: + +```js +const get = require('simple-get') +const crypto = require('crypto') +const OAuth = require('oauth-1.0a') + +const oauth = OAuth({ + consumer: { + key: process.env.CONSUMER_KEY, + secret: process.env.CONSUMER_SECRET + }, + signature_method: 'HMAC-SHA1', + hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64') +}) + +const token = { + key: process.env.ACCESS_TOKEN, + secret: process.env.ACCESS_TOKEN_SECRET +} + +const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json' + +const opts = { + url: url, + headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)), + json: true +} + +get(opts, function (err, res) {}) +``` + +### Throttle requests + +You can use [limiter](https://github.com/jhurliman/node-rate-limiter) to throttle requests. This is useful when calling an API that is rate limited. + +```js +const simpleGet = require('simple-get') +const RateLimiter = require('limiter').RateLimiter +const limiter = new RateLimiter(1, 'second') + +const get = (opts, cb) => limiter.removeTokens(1, () => simpleGet(opts, cb)) +get.concat = (opts, cb) => limiter.removeTokens(1, () => simpleGet.concat(opts, cb)) + +var opts = { + url: 'http://example.com' +} + +get.concat(opts, processResult) +get.concat(opts, processResult) + +function processResult (err, res, data) { + if (err) throw err + console.log(data.toString()) +} +``` + +## license + +MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/simple-get/index.js b/node_modules/simple-get/index.js new file mode 100644 index 0000000000000000000000000000000000000000..80e52e8ccade8e92c290462ae404a7ce70a937f1 --- /dev/null +++ b/node_modules/simple-get/index.js @@ -0,0 +1,108 @@ +/*! simple-get. MIT License. Feross Aboukhadijeh */ +module.exports = simpleGet + +const concat = require('simple-concat') +const decompressResponse = require('decompress-response') // excluded from browser build +const http = require('http') +const https = require('https') +const once = require('once') +const querystring = require('querystring') +const url = require('url') + +const isStream = o => o !== null && typeof o === 'object' && typeof o.pipe === 'function' + +function simpleGet (opts, cb) { + opts = Object.assign({ maxRedirects: 10 }, typeof opts === 'string' ? { url: opts } : opts) + cb = once(cb) + + if (opts.url) { + const { hostname, port, protocol, auth, path } = url.parse(opts.url) // eslint-disable-line node/no-deprecated-api + delete opts.url + if (!hostname && !port && !protocol && !auth) opts.path = path // Relative redirect + else Object.assign(opts, { hostname, port, protocol, auth, path }) // Absolute redirect + } + + const headers = { 'accept-encoding': 'gzip, deflate' } + if (opts.headers) Object.keys(opts.headers).forEach(k => (headers[k.toLowerCase()] = opts.headers[k])) + opts.headers = headers + + let body + if (opts.body) { + body = opts.json && !isStream(opts.body) ? JSON.stringify(opts.body) : opts.body + } else if (opts.form) { + body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form) + opts.headers['content-type'] = 'application/x-www-form-urlencoded' + } + + if (body) { + if (!opts.method) opts.method = 'POST' + if (!isStream(body)) opts.headers['content-length'] = Buffer.byteLength(body) + if (opts.json && !opts.form) opts.headers['content-type'] = 'application/json' + } + delete opts.body; delete opts.form + + if (opts.json) opts.headers.accept = 'application/json' + if (opts.method) opts.method = opts.method.toUpperCase() + + const originalHost = opts.hostname // hostname before potential redirect + const protocol = opts.protocol === 'https:' ? https : http // Support http/https urls + const req = protocol.request(opts, res => { + if (opts.followRedirects !== false && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + opts.url = res.headers.location // Follow 3xx redirects + delete opts.headers.host // Discard `host` header on redirect (see #32) + res.resume() // Discard response + + const redirectHost = url.parse(opts.url).hostname // eslint-disable-line node/no-deprecated-api + // If redirected host is different than original host, drop headers to prevent cookie leak (#73) + if (redirectHost !== null && redirectHost !== originalHost) { + delete opts.headers.cookie + delete opts.headers.authorization + } + + if (opts.method === 'POST' && [301, 302].includes(res.statusCode)) { + opts.method = 'GET' // On 301/302 redirect, change POST to GET (see #35) + delete opts.headers['content-length']; delete opts.headers['content-type'] + } + + if (opts.maxRedirects-- === 0) return cb(new Error('too many redirects')) + else return simpleGet(opts, cb) + } + + const tryUnzip = typeof decompressResponse === 'function' && opts.method !== 'HEAD' + cb(null, tryUnzip ? decompressResponse(res) : res) + }) + req.on('timeout', () => { + req.abort() + cb(new Error('Request timed out')) + }) + req.on('error', cb) + + if (isStream(body)) body.on('error', cb).pipe(req) + else req.end(body) + + return req +} + +simpleGet.concat = (opts, cb) => { + return simpleGet(opts, (err, res) => { + if (err) return cb(err) + concat(res, (err, data) => { + if (err) return cb(err) + if (opts.json) { + try { + data = JSON.parse(data.toString()) + } catch (err) { + return cb(err, res, data) + } + } + cb(null, res, data) + }) + }) +} + +;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(method => { + simpleGet[method] = (opts, cb) => { + if (typeof opts === 'string') opts = { url: opts } + return simpleGet(Object.assign({ method: method.toUpperCase() }, opts), cb) + } +}) diff --git a/node_modules/simple-get/package.json b/node_modules/simple-get/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e80fc5eb315786b6f7410be415256000977f8fe9 --- /dev/null +++ b/node_modules/simple-get/package.json @@ -0,0 +1,67 @@ +{ + "name": "simple-get", + "description": "Simplest way to make http get requests. Supports HTTPS, redirects, gzip/deflate, streams in < 100 lines.", + "version": "4.0.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "browser": { + "decompress-response": false + }, + "bugs": { + "url": "https://github.com/feross/simple-get/issues" + }, + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + }, + "devDependencies": { + "self-signed-https": "^1.0.5", + "standard": "*", + "string-to-stream": "^3.0.0", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/simple-get", + "keywords": [ + "request", + "http", + "GET", + "get request", + "http.get", + "redirects", + "follow redirects", + "gzip", + "deflate", + "https", + "http-https", + "stream", + "simple request", + "simple get" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/simple-get.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/simple-update-notifier/LICENSE b/node_modules/simple-update-notifier/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e0b0c116923cb899cb0ebc49528551dde1f6ab9 --- /dev/null +++ b/node_modules/simple-update-notifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Alex Brazier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/simple-update-notifier/README.md b/node_modules/simple-update-notifier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ec177944638c4be4d4d8cf639d00bab0cc774acc --- /dev/null +++ b/node_modules/simple-update-notifier/README.md @@ -0,0 +1,82 @@ +# simple-update-notifier [![GitHub stars](https://img.shields.io/github/stars/alexbrazier/simple-update-notifier?label=Star%20Project&style=social)](https://github.com/alexbrazier/simple-update-notifier/stargazers) + +[![CI](https://github.com/alexbrazier/simple-update-notifier/workflows/Build%20and%20Deploy/badge.svg)](https://github.com/alexbrazier/simple-update-notifier/actions) +[![Dependencies](https://img.shields.io/librariesio/release/npm/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier?activeTab=dependencies) +[![npm](https://img.shields.io/npm/v/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) +[![npm bundle size](https://img.shields.io/bundlephobia/min/simple-update-notifier)](https://bundlephobia.com/result?p=simple-update-notifier) +[![npm downloads](https://img.shields.io/npm/dw/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) +[![License](https://img.shields.io/npm/l/simple-update-notifier)](./LICENSE) + +Simple update notifier to check for npm updates for cli applications. + +Demo in terminal showing an update is required + +Checks for updates for an npm module and outputs to the command line if there is one available. The result is cached for the specified time so it doesn't check every time the app runs. + +## Install + +```bash +npm install simple-update-notifier +OR +yarn add simple-update-notifier +``` + +## Usage + +```js +import updateNotifier from 'simple-update-notifier'; +import packageJson from './package.json' assert { type: 'json' }; + +updateNotifier({ pkg: packageJson }); +``` + +### Options + +#### pkg + +Type: `object` + +##### name + +_Required_\ +Type: `string` + +##### version + +_Required_\ +Type: `string` + +#### updateCheckInterval + +Type: `number`\ +Default: `1000 * 60 * 60 * 24` _(1 day)_ + +How often to check for updates. + +#### shouldNotifyInNpmScript + +Type: `boolean`\ +Default: `false` + +Allows notification to be shown when running as an npm script. + +#### distTag + +Type: `string`\ +Default: `'latest'` + +Which [dist-tag](https://docs.npmjs.com/adding-dist-tags-to-packages) to use to find the latest version. + +#### alwaysRun + +Type: `boolean`\ +Default: `false` + +When set, `updateCheckInterval` will not be respected and a check for an update will always be performed. + +#### debug + +Type: `boolean`\ +Default: `false` + +When set, logs explaining the decision will be output to `stderr` whenever the module opts to not print an update notification diff --git a/node_modules/simple-update-notifier/build/index.d.ts b/node_modules/simple-update-notifier/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60f53e0560e592029577d1e0c965d55c252b5e36 --- /dev/null +++ b/node_modules/simple-update-notifier/build/index.d.ts @@ -0,0 +1,13 @@ +interface IUpdate { + pkg: { + name: string; + version: string; + }; + updateCheckInterval?: number; + shouldNotifyInNpmScript?: boolean; + distTag?: string; + alwaysRun?: boolean; + debug?: boolean; +} +declare const simpleUpdateNotifier: (args: IUpdate) => Promise; +export { simpleUpdateNotifier as default }; diff --git a/node_modules/simple-update-notifier/build/index.js b/node_modules/simple-update-notifier/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d7c3cde2ef4e3a4b4e97ed23d3645735f3f6d0cb --- /dev/null +++ b/node_modules/simple-update-notifier/build/index.js @@ -0,0 +1,210 @@ +'use strict'; + +var process$1 = require('process'); +var semver = require('semver'); +var os = require('os'); +var path = require('path'); +var fs = require('fs'); +var https = require('https'); + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var packageJson = process$1.env.npm_package_json; +var userAgent = process$1.env.npm_config_user_agent; +var isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +var isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); +var isNpm = isNpm6 || isNpm7; +var isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +var isNpmOrYarn = isNpm || isYarn; + +var homeDirectory = os.homedir(); +var configDir = process.env.XDG_CONFIG_HOME || + path.join(homeDirectory, '.config', 'simple-update-notifier'); +var getConfigFile = function (packageName) { + return path.join(configDir, "".concat(packageName.replace('@', '').replace('/', '__'), ".json")); +}; +var createConfigDir = function () { + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } +}; +var getLastUpdate = function (packageName) { + var configFile = getConfigFile(packageName); + try { + if (!fs.existsSync(configFile)) { + return undefined; + } + var file = JSON.parse(fs.readFileSync(configFile, 'utf8')); + return file.lastUpdateCheck; + } + catch (_a) { + return undefined; + } +}; +var saveLastUpdate = function (packageName) { + var configFile = getConfigFile(packageName); + fs.writeFileSync(configFile, JSON.stringify({ lastUpdateCheck: new Date().getTime() })); +}; + +var getDistVersion = function (packageName, distTag) { return __awaiter(void 0, void 0, void 0, function () { + var url; + return __generator(this, function (_a) { + url = "https://registry.npmjs.org/-/package/".concat(packageName, "/dist-tags"); + return [2 /*return*/, new Promise(function (resolve, reject) { + https + .get(url, function (res) { + var body = ''; + res.on('data', function (chunk) { return (body += chunk); }); + res.on('end', function () { + try { + var json = JSON.parse(body); + var version = json[distTag]; + if (!version) { + reject(new Error('Error getting version')); + } + resolve(version); + } + catch (_a) { + reject(new Error('Could not parse version response')); + } + }); + }) + .on('error', function (err) { return reject(err); }); + })]; + }); +}); }; + +var hasNewVersion = function (_a) { + var pkg = _a.pkg, _b = _a.updateCheckInterval, updateCheckInterval = _b === void 0 ? 1000 * 60 * 60 * 24 : _b, _c = _a.distTag, distTag = _c === void 0 ? 'latest' : _c, alwaysRun = _a.alwaysRun, debug = _a.debug; + return __awaiter(void 0, void 0, void 0, function () { + var lastUpdateCheck, latestVersion; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + createConfigDir(); + lastUpdateCheck = getLastUpdate(pkg.name); + if (!(alwaysRun || + !lastUpdateCheck || + lastUpdateCheck < new Date().getTime() - updateCheckInterval)) return [3 /*break*/, 2]; + return [4 /*yield*/, getDistVersion(pkg.name, distTag)]; + case 1: + latestVersion = _d.sent(); + saveLastUpdate(pkg.name); + if (semver.gt(latestVersion, pkg.version)) { + return [2 /*return*/, latestVersion]; + } + else if (debug) { + console.error("Latest version (".concat(latestVersion, ") not newer than current version (").concat(pkg.version, ")")); + } + return [3 /*break*/, 3]; + case 2: + if (debug) { + console.error("Too recent to check for a new update. simpleUpdateNotifier() interval set to ".concat(updateCheckInterval, "ms but only ").concat(new Date().getTime() - lastUpdateCheck, "ms since last check.")); + } + _d.label = 3; + case 3: return [2 /*return*/, false]; + } + }); + }); +}; + +var borderedText = function (text) { + var lines = text.split('\n'); + var width = Math.max.apply(Math, lines.map(function (l) { return l.length; })); + var res = ["\u250C".concat('─'.repeat(width + 2), "\u2510")]; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + res.push("\u2502 ".concat(line.padEnd(width), " \u2502")); + } + res.push("\u2514".concat('─'.repeat(width + 2), "\u2518")); + return res.join('\n'); +}; + +var simpleUpdateNotifier = function (args) { return __awaiter(void 0, void 0, void 0, function () { + var latestVersion, err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!args.alwaysRun && + (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript))) { + if (args.debug) { + console.error('Opting out of running simpleUpdateNotifier()'); + } + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, hasNewVersion(args)]; + case 2: + latestVersion = _a.sent(); + if (latestVersion) { + console.error(borderedText("New version of ".concat(args.pkg.name, " available!\nCurrent Version: ").concat(args.pkg.version, "\nLatest Version: ").concat(latestVersion))); + } + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + // Catch any network errors or cache writing errors so module doesn't cause a crash + if (args.debug && err_1 instanceof Error) { + console.error('Unexpected error in simpleUpdateNotifier():', err_1); + } + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); +}); }; + +module.exports = simpleUpdateNotifier; diff --git a/node_modules/simple-update-notifier/package.json b/node_modules/simple-update-notifier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4d710a72e90eba53c3e080174ce488e85608e6d4 --- /dev/null +++ b/node_modules/simple-update-notifier/package.json @@ -0,0 +1,100 @@ +{ + "name": "simple-update-notifier", + "version": "2.0.0", + "description": "Simple update notifier to check for npm updates for cli applications", + "main": "build/index.js", + "types": "build/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/alexbrazier/simple-update-notifier.git" + }, + "homepage": "https://github.com/alexbrazier/simple-update-notifier.git", + "author": "alexbrazier", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "jest src --noStackTrace", + "build": "rollup -c rollup.config.js --bundleConfigAsCjs", + "prettier:check": "prettier --check src/**/*.ts", + "prettier": "prettier --write src/**/*.ts", + "eslint": "eslint src/**/*.ts", + "lint": "yarn prettier:check && yarn eslint", + "prepare": "yarn lint && yarn build", + "release": "release-it" + }, + "dependencies": { + "semver": "^7.5.3" + }, + "devDependencies": { + "@babel/preset-env": "^7.22.5", + "@babel/preset-typescript": "^7.22.5", + "@release-it/conventional-changelog": "^5.1.1", + "@types/jest": "^29.5.2", + "@types/node": "^20.3.1", + "@typescript-eslint/eslint-plugin": "^5.60.0", + "@typescript-eslint/parser": "^5.60.0", + "eslint": "^8.43.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^29.5.0", + "prettier": "^2.8.8", + "release-it": "^15.11.0", + "rollup": "^3.25.2", + "rollup-plugin-ts": "^3.2.0", + "typescript": "^5.1.3" + }, + "resolutions": { + "semver": "^7.5.3" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org/" + }, + "files": [ + "build", + "src" + ], + "release-it": { + "git": { + "commitMessage": "chore: release ${version}", + "tagName": "v${version}" + }, + "npm": { + "publish": true + }, + "github": { + "release": true + }, + "plugins": { + "@release-it/conventional-changelog": { + "preset": "angular", + "infile": "CHANGELOG.md" + } + } + }, + "eslintConfig": { + "plugins": [ + "@typescript-eslint", + "prettier" + ], + "extends": [ + "prettier", + "eslint:recommended", + "plugin:@typescript-eslint/recommended" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "prettier/prettier": [ + "error", + { + "quoteProps": "consistent", + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false + } + ] + } + } +} diff --git a/node_modules/simple-update-notifier/src/borderedText.ts b/node_modules/simple-update-notifier/src/borderedText.ts new file mode 100644 index 0000000000000000000000000000000000000000..7145ac2f43189ec3c945d1009df3dfe3d4c92d36 --- /dev/null +++ b/node_modules/simple-update-notifier/src/borderedText.ts @@ -0,0 +1,12 @@ +const borderedText = (text: string) => { + const lines = text.split('\n'); + const width = Math.max(...lines.map((l) => l.length)); + const res = [`┌${'─'.repeat(width + 2)}┐`]; + for (const line of lines) { + res.push(`│ ${line.padEnd(width)} │`); + } + res.push(`└${'─'.repeat(width + 2)}┘`); + return res.join('\n'); +}; + +export default borderedText; diff --git a/node_modules/simple-update-notifier/src/cache.spec.ts b/node_modules/simple-update-notifier/src/cache.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..49e1cb276993af3991196dca44a43f9f14da17a9 --- /dev/null +++ b/node_modules/simple-update-notifier/src/cache.spec.ts @@ -0,0 +1,17 @@ +import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; + +createConfigDir(); + +jest.useFakeTimers().setSystemTime(new Date('2022-01-01')); + +const fakeTime = new Date('2022-01-01').getTime(); + +test('can save update then get the update details', () => { + saveLastUpdate('test'); + expect(getLastUpdate('test')).toBe(fakeTime); +}); + +test('prefixed module can save update then get the update details', () => { + saveLastUpdate('@alexbrazier/test'); + expect(getLastUpdate('@alexbrazier/test')).toBe(fakeTime); +}); diff --git a/node_modules/simple-update-notifier/src/cache.ts b/node_modules/simple-update-notifier/src/cache.ts new file mode 100644 index 0000000000000000000000000000000000000000..e11deba0ae1e8694311a9cc792014d727534d0df --- /dev/null +++ b/node_modules/simple-update-notifier/src/cache.ts @@ -0,0 +1,44 @@ +import os from 'os'; +import path from 'path'; +import fs from 'fs'; + +const homeDirectory = os.homedir(); +const configDir = + process.env.XDG_CONFIG_HOME || + path.join(homeDirectory, '.config', 'simple-update-notifier'); + +const getConfigFile = (packageName: string) => { + return path.join( + configDir, + `${packageName.replace('@', '').replace('/', '__')}.json` + ); +}; + +export const createConfigDir = () => { + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } +}; + +export const getLastUpdate = (packageName: string) => { + const configFile = getConfigFile(packageName); + + try { + if (!fs.existsSync(configFile)) { + return undefined; + } + const file = JSON.parse(fs.readFileSync(configFile, 'utf8')); + return file.lastUpdateCheck as number; + } catch { + return undefined; + } +}; + +export const saveLastUpdate = (packageName: string) => { + const configFile = getConfigFile(packageName); + + fs.writeFileSync( + configFile, + JSON.stringify({ lastUpdateCheck: new Date().getTime() }) + ); +}; diff --git a/node_modules/simple-update-notifier/src/getDistVersion.spec.ts b/node_modules/simple-update-notifier/src/getDistVersion.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..b78a42e5aa90f08aa6508eb9243e612b8f7c9040 --- /dev/null +++ b/node_modules/simple-update-notifier/src/getDistVersion.spec.ts @@ -0,0 +1,35 @@ +import Stream from 'stream'; +import https from 'https'; +import getDistVersion from './getDistVersion'; + +jest.mock('https', () => ({ + get: jest.fn(), +})); + +test('Valid response returns version', async () => { + const st = new Stream(); + (https.get as jest.Mock).mockImplementation((url, cb) => { + cb(st); + + st.emit('data', '{"latest":"1.0.0"}'); + st.emit('end'); + }); + + const version = await getDistVersion('test', 'latest'); + + expect(version).toEqual('1.0.0'); +}); + +test('Invalid response throws error', async () => { + const st = new Stream(); + (https.get as jest.Mock).mockImplementation((url, cb) => { + cb(st); + + st.emit('data', 'some invalid json'); + st.emit('end'); + }); + + expect(getDistVersion('test', 'latest')).rejects.toThrow( + 'Could not parse version response' + ); +}); diff --git a/node_modules/simple-update-notifier/src/getDistVersion.ts b/node_modules/simple-update-notifier/src/getDistVersion.ts new file mode 100644 index 0000000000000000000000000000000000000000..d474e1f9ead19135a390c930e5801f4e6910c0a4 --- /dev/null +++ b/node_modules/simple-update-notifier/src/getDistVersion.ts @@ -0,0 +1,29 @@ +import https from 'https'; + +const getDistVersion = async (packageName: string, distTag: string) => { + const url = `https://registry.npmjs.org/-/package/${packageName}/dist-tags`; + + return new Promise((resolve, reject) => { + https + .get(url, (res) => { + let body = ''; + + res.on('data', (chunk) => (body += chunk)); + res.on('end', () => { + try { + const json = JSON.parse(body); + const version = json[distTag]; + if (!version) { + reject(new Error('Error getting version')); + } + resolve(version); + } catch { + reject(new Error('Could not parse version response')); + } + }); + }) + .on('error', (err) => reject(err)); + }); +}; + +export default getDistVersion; diff --git a/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts b/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..af7ab22cacee30687de862601171a819fd95c782 --- /dev/null +++ b/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts @@ -0,0 +1,82 @@ +import hasNewVersion from './hasNewVersion'; +import { getLastUpdate } from './cache'; +import getDistVersion from './getDistVersion'; + +jest.mock('./getDistVersion', () => jest.fn().mockReturnValue('1.0.0')); +jest.mock('./cache', () => ({ + getLastUpdate: jest.fn().mockReturnValue(undefined), + createConfigDir: jest.fn(), + saveLastUpdate: jest.fn(), +})); + +const pkg = { name: 'test', version: '1.0.0' }; + +afterEach(() => jest.clearAllMocks()); + +const defaultArgs = { + pkg, + shouldNotifyInNpmScript: true, + alwaysRun: true, +}; + +test('it should not trigger update for same version', async () => { + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe(false); +}); + +test('it should trigger update for patch version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('1.0.1'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('1.0.1'); +}); + +test('it should trigger update for minor version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('1.1.0'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('1.1.0'); +}); + +test('it should trigger update for major version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('2.0.0'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('2.0.0'); +}); + +test('it should not trigger update if version is lower', async () => { + (getDistVersion as jest.Mock).mockReturnValue('0.0.9'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe(false); +}); + +it('should trigger update check if last update older than config', async () => { + const TWO_WEEKS = new Date().getTime() - 1000 * 60 * 60 * 24 * 14; + (getLastUpdate as jest.Mock).mockReturnValue(TWO_WEEKS); + const newVersion = await hasNewVersion({ + pkg, + shouldNotifyInNpmScript: true, + }); + + expect(newVersion).toBe(false); + expect(getDistVersion).toHaveBeenCalled(); +}); + +it('should not trigger update check if last update is too recent', async () => { + const TWELVE_HOURS = new Date().getTime() - 1000 * 60 * 60 * 12; + (getLastUpdate as jest.Mock).mockReturnValue(TWELVE_HOURS); + const newVersion = await hasNewVersion({ + pkg, + shouldNotifyInNpmScript: true, + }); + + expect(newVersion).toBe(false); + expect(getDistVersion).not.toHaveBeenCalled(); +}); diff --git a/node_modules/simple-update-notifier/src/hasNewVersion.ts b/node_modules/simple-update-notifier/src/hasNewVersion.ts new file mode 100644 index 0000000000000000000000000000000000000000..31d5069f97d3abf90d2c105374c21c44bde35b82 --- /dev/null +++ b/node_modules/simple-update-notifier/src/hasNewVersion.ts @@ -0,0 +1,40 @@ +import semver from 'semver'; +import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; +import getDistVersion from './getDistVersion'; +import { IUpdate } from './types'; + +const hasNewVersion = async ({ + pkg, + updateCheckInterval = 1000 * 60 * 60 * 24, + distTag = 'latest', + alwaysRun, + debug, +}: IUpdate) => { + createConfigDir(); + const lastUpdateCheck = getLastUpdate(pkg.name); + if ( + alwaysRun || + !lastUpdateCheck || + lastUpdateCheck < new Date().getTime() - updateCheckInterval + ) { + const latestVersion = await getDistVersion(pkg.name, distTag); + saveLastUpdate(pkg.name); + if (semver.gt(latestVersion, pkg.version)) { + return latestVersion; + } else if (debug) { + console.error( + `Latest version (${latestVersion}) not newer than current version (${pkg.version})` + ); + } + } else if (debug) { + console.error( + `Too recent to check for a new update. simpleUpdateNotifier() interval set to ${updateCheckInterval}ms but only ${ + new Date().getTime() - lastUpdateCheck + }ms since last check.` + ); + } + + return false; +}; + +export default hasNewVersion; diff --git a/node_modules/simple-update-notifier/src/index.spec.ts b/node_modules/simple-update-notifier/src/index.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..98ffb5a9201cc15e27251e3bbe4f190a422ab0eb --- /dev/null +++ b/node_modules/simple-update-notifier/src/index.spec.ts @@ -0,0 +1,27 @@ +import simpleUpdateNotifier from '.'; +import hasNewVersion from './hasNewVersion'; + +const consoleSpy = jest.spyOn(console, 'error'); + +jest.mock('./hasNewVersion', () => jest.fn().mockResolvedValue('2.0.0')); + +beforeEach(jest.clearAllMocks); + +test('it logs message if update is available', async () => { + await simpleUpdateNotifier({ + pkg: { name: 'test', version: '1.0.0' }, + alwaysRun: true, + }); + + expect(consoleSpy).toHaveBeenCalledTimes(1); +}); + +test('it does not log message if update is not available', async () => { + (hasNewVersion as jest.Mock).mockResolvedValue(false); + await simpleUpdateNotifier({ + pkg: { name: 'test', version: '2.0.0' }, + alwaysRun: true, + }); + + expect(consoleSpy).toHaveBeenCalledTimes(0); +}); diff --git a/node_modules/simple-update-notifier/src/index.ts b/node_modules/simple-update-notifier/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b0d2cfcd7a4d1596e2257c7fe0d73cdf9bb49e4 --- /dev/null +++ b/node_modules/simple-update-notifier/src/index.ts @@ -0,0 +1,34 @@ +import isNpmOrYarn from './isNpmOrYarn'; +import hasNewVersion from './hasNewVersion'; +import { IUpdate } from './types'; +import borderedText from './borderedText'; + +const simpleUpdateNotifier = async (args: IUpdate) => { + if ( + !args.alwaysRun && + (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript)) + ) { + if (args.debug) { + console.error('Opting out of running simpleUpdateNotifier()'); + } + return; + } + + try { + const latestVersion = await hasNewVersion(args); + if (latestVersion) { + console.error( + borderedText(`New version of ${args.pkg.name} available! +Current Version: ${args.pkg.version} +Latest Version: ${latestVersion}`) + ); + } + } catch (err) { + // Catch any network errors or cache writing errors so module doesn't cause a crash + if (args.debug && err instanceof Error) { + console.error('Unexpected error in simpleUpdateNotifier():', err); + } + } +}; + +export default simpleUpdateNotifier; diff --git a/node_modules/simple-update-notifier/src/isNpmOrYarn.ts b/node_modules/simple-update-notifier/src/isNpmOrYarn.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee4c8371afc074e93c8bd48bfe6ba9257c19cbee --- /dev/null +++ b/node_modules/simple-update-notifier/src/isNpmOrYarn.ts @@ -0,0 +1,12 @@ +import process from 'process'; + +const packageJson = process.env.npm_package_json; +const userAgent = process.env.npm_config_user_agent; +const isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +const isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); + +const isNpm = isNpm6 || isNpm7; +const isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +const isNpmOrYarn = isNpm || isYarn; + +export default isNpmOrYarn; diff --git a/node_modules/simple-update-notifier/src/types.ts b/node_modules/simple-update-notifier/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c395eb002762d0d4cca2b254b073b33db8b83da4 --- /dev/null +++ b/node_modules/simple-update-notifier/src/types.ts @@ -0,0 +1,8 @@ +export interface IUpdate { + pkg: { name: string; version: string }; + updateCheckInterval?: number; + shouldNotifyInNpmScript?: boolean; + distTag?: string; + alwaysRun?: boolean; + debug?: boolean; +} diff --git a/node_modules/simple-xml-to-json/README.md b/node_modules/simple-xml-to-json/README.md new file mode 100644 index 0000000000000000000000000000000000000000..de175a793945c47b61a197ee0e116b8d627db834 --- /dev/null +++ b/node_modules/simple-xml-to-json/README.md @@ -0,0 +1,87 @@ +# A simple XML to JSON converter + +[![npm version](https://img.shields.io/npm/v/simple-xml-to-json.svg?style=flat-square)](https://www.npmjs.com/package/simple-xml-to-json) +[![Test CI](https://github.com/nirgit/simple-xml-to-json/actions/workflows/node.js.yml/badge.svg)](https://github.com/nirgit/simple-xml-to-json/actions/workflows/node.js.yml) +[![codecov](https://codecov.io/gh/nirgit/simple-xml-to-json/branch/master/graph/badge.svg?token=XW7CWWM4RV)](https://codecov.io/gh/nirgit/simple-xml-to-json) + +## Install +Simply install using NPM in your project directory +> npm install simple-xml-to-json + + +## Usage and API +### 1. convertXML(xmlToConvert [,customConverter]) + * `xmlToConvert` \ + * `customConverter` \ + * Returns: \ by default or other if `customConverter` is used + +### 2. createAST(xmlToConvert) + * `xmlToConvert` \ + * Returns: An AST representation of the XML \ + +**CommonJS (Node.js):** +```javascript +const { convertXML, createAST } = require("simple-xml-to-json") + +const myJson = convertXML(myXMLString) +const myYaml = convertXML(myXMLString, yamlConverter) +const myAst = createAST(myXMLString) +``` + +**ESM (modern frontend apps, Node.js with `"type": "module"`, bundlers):** +```javascript +import { convertXML, createAST } from "simple-xml-to-json" + +const myJson = convertXML(myXMLString) +const myYaml = convertXML(myXMLString, yamlConverter) +const myAst = createAST(myXMLString) +``` + +--- +### ![TS](https://raw.githubusercontent.com/nirgit/assets/master/simple-xml-to-json/ts_icon_32.png) Typescript compatible +--- + +## Notes and how to use code +1. The easiest thing to start is to run `node example/example.js` (CJS) or `node example/example.mjs` (ESM) in your terminal and see what happens. +2. There's the `xmlToJson.js` file for convenience. Just pass in the XML as a String. +3. MIT licensed allowing code customization +4. Profit + +## How this works in a nutshell +1. The library converts the XML to an AST +2. There is a JSON converter that takes the AST and spits out a JSON +3. You can write your own converters if you need XML-to-ANY-OTHER-FORMAT + +## Benchmark + +_Take these results with a grain of salt._\ +According to a __simple__ benchmark test I performed in __April 2024__ with a random XML. _YMMV_. +![Benchmark Chart](https://github.com/nirgit/assets/blob/master/simple-xml-to-json/simple-xml-to-json-benchmark-2.png?raw=true) + +* The chart results __may be__ outdated. [Run the test yourself](https://runkit.com/nirgit/6620cf27943a41000847221d) + + +## Current Drawbacks +1. All values are translated to strings in JSON +2. There are currently reserved words in the JSON converter: + * "content" - up to version 1.2.3 + * "children" + +### Default Mapping & Collisions + +By default, an element's **text content** is mapped to a `"content"` property, while its **attributes** are mapped directly to JSON properties of the same name. + +#### The Risk +If an XML element possesses an attribute actually named `content` while also containing text content, a **name collision** occurs. This typically results in a parsing error or data loss due to duplicate keys. + +**Example Collision:** +```xml +text-content + ``` + +### Version 1.2.3+ Fix +To prevent these collisions, versions newer than 1.2.3 will specifically prefix the `"content"` attribute name with an `@` symbol. So the attribute `"content"` now becomes the `"@content"` JSON property. + + +> [!NOTE] +> If you need to, you can write your own converter from the AST created by the parser, and pass it as a 2nd parameter after the xml string diff --git a/node_modules/simple-xml-to-json/lib/simpleXmlToJson.js b/node_modules/simple-xml-to-json/lib/simpleXmlToJson.js new file mode 100644 index 0000000000000000000000000000000000000000..9eeb8f8316e15f591b5a665889495ea45c3fea3b --- /dev/null +++ b/node_modules/simple-xml-to-json/lib/simpleXmlToJson.js @@ -0,0 +1,590 @@ +'use strict'; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var constants; +var hasRequiredConstants; + +function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + + constants = { + BUILD: { + COMPTIME: true + }, + NODE_TYPE: { + ATTRIBUTE: 'ATTRIBUTE', + CONTENT: 'CONTENT', + ELEMENT: 'ELEMENT', + ROOT: 'ROOT' + }, + TOKEN_TYPE: { + OPEN_BRACKET: 'OPEN_BRACKET', + ELEMENT_TYPE: 'ELEMENT_TYPE', + CLOSE_ELEMENT: 'CLOSE_ELEMENT', + ATTRIB_NAME: 'ATTRIB_NAME', + ATTRIB_VALUE: 'ATTRIB_VALUE', + ASSIGN: 'ASSIGN', + CLOSE_BRACKET: 'CLOSE_BRACKET', + CONTENT: 'CONTENT', + EOF: 'EOF' + } + }; + return constants; +} + +var astToJson; +var hasRequiredAstToJson; + +function requireAstToJson () { + if (hasRequiredAstToJson) return astToJson; + hasRequiredAstToJson = 1; + + const { NODE_TYPE } = requireConstants(); + + const convertToJSON = ast => { + return buildJSONFromNode(ast.value.children[0]) + }; + + const buildJSONFromNode = node => { + if (!node) return null + const json = {}; + switch (node.type) { + case "ELEMENT": { + let element = {}; + const attribs = buildAttributes(node.value.attributes); + const children = buildJSONFromNode(node.value.children); + if (attribs) { + element = Object.assign(element, attribs); + } + if (children) { + const jsonChildren = buildChildren(node.value.children); + element = Object.assign(element, jsonChildren); + } + json[node.value.type] = element; + break + } + case "ATTRIBUTE": { + const attribNameAndValue = node.value; + json[attribNameAndValue.name] = attribNameAndValue.value; + break + } + case "CONTENT": { + return {content: node.value} + } + } + + return json + }; + + const buildChildren = children => { + if (!children || !Array.isArray(children) || children.length === 0) return null + if (isContentChildren(children)) { + return { + content: children[0].value + } + } + return { + children: children.map(buildJSONFromNode) + } + }; + + const isContentChildren = children => children && Array.isArray(children) && children.length === 1 && children[0].type === "CONTENT"; + + const buildAttributes = arrayNodes => { + if (arrayNodes && Array.isArray(arrayNodes)) { + const jsonArray = arrayNodes.map(buildJSONFromNode); + return jsonArray.reduce((agg, j) => Object.assign(agg, j), {}) + } + return null + }; + + astToJson = { + convert: convertToJSON + }; + return astToJson; +} + +var model; +var hasRequiredModel; + +function requireModel () { + if (hasRequiredModel) return model; + hasRequiredModel = 1; + + const Token = (type, value) => ({ + type, + value + }); + + model = { + Token + }; + return model; +} + +var lexer; +var hasRequiredLexer; + +function requireLexer () { + if (hasRequiredLexer) return lexer; + hasRequiredLexer = 1; + + const { BUILD, TOKEN_TYPE } = requireConstants(); + const { Token } = requireModel(); + + const EOF_TOKEN = Token("EOF"); + + const isCharBlank = (char) => + char === ' ' || char === '\n' || char === '\r' || char === '\t'; + + const skipXMLDocumentHeader = (xmlAsString, pos) => { + if (xmlAsString.startsWith('') { + return pos + 2 // skip "?>"" + } else { + pos++; + } + } + } + return pos + }; + + const replaceQuotes = (str) => str.replace(/'/g, "'"); + + const getInitialPosForLexer = (xmlAsString) => { + let pos = 0; + while (pos < xmlAsString.length && isCharBlank(xmlAsString[pos])) pos++; + return skipXMLDocumentHeader(xmlAsString, pos) + }; + + function createLexer(xmlAsString) { + let currentToken = null; + let pos = getInitialPosForLexer(xmlAsString); + let scopingElement = []; + + const peek = () => xmlAsString[pos]; + const hasNext = () => currentToken !== EOF_TOKEN && pos < xmlAsString.length; + const isBlankSpace = () => isCharBlank(xmlAsString[pos]); + + const skipQuotes = () => { + if (hasNext() && isQuote(peek())) pos++; + }; + + const isQuote = (char) => '"' === char || "'" === char; + + const skipSpaces = () => { + while (hasNext() && isBlankSpace()) pos++; + }; + + const readAlphaNumericCharsOrBrackets = (areSpecialCharsSupported) => { + if (hasNext()) { + if (xmlAsString[pos] === '<') { + let buffer = '<'; + pos++; + if (hasNext() && xmlAsString[pos] === '/') { + pos++; + buffer = '') { + pos++; + buffer = '/>'; + } + return buffer + } else if (xmlAsString[pos] === '=' || xmlAsString[pos] === '>') { + const buffer = xmlAsString[pos]; + pos++; + return buffer + } + } + return readAlphaNumericChars(!!areSpecialCharsSupported) + }; + + const readAlphaNumericChars = (areSpecialCharsSupported) => { + const ELEMENT_TYPE_MATCHER = /[a-zA-Z0-9_:-]/; + const NAMES_VALS_CONTENT_MATCHER = /[^>=<]/u; + const matcher = areSpecialCharsSupported + ? NAMES_VALS_CONTENT_MATCHER + : ELEMENT_TYPE_MATCHER; + let start = pos; + while (hasNext() && xmlAsString[pos].match(matcher)) pos++; + return replaceQuotes(xmlAsString.substring(start, pos)) + }; + + const isElementBegin = () => + currentToken && currentToken.type === "OPEN_BRACKET"; + const isAssignToAttribute = () => + currentToken && currentToken.type === "ASSIGN"; + + const next = () => { + const prevPos = pos; + skipSpaces(); + const numOfSpacesSkipped = pos - prevPos; + if (!hasNext()) { + currentToken = EOF_TOKEN; + } else if (isElementBegin()) { + // starting new element + skipSpaces(); + const buffer = readAlphaNumericCharsOrBrackets(false); + currentToken = Token("ELEMENT_TYPE", buffer); + scopingElement.push(buffer); + } else if (isAssignToAttribute()) { + // assign value to attribute + skipQuotes(); + const openingQuote = xmlAsString[pos - 1]; + let start = pos; + while (hasNext() && peek() !== openingQuote) pos++; + const buffer = replaceQuotes(xmlAsString.substring(start, pos)); + pos++; + currentToken = Token("ATTRIB_VALUE", buffer); + } else { + skipSpaces(); + let buffer = readAlphaNumericCharsOrBrackets(true); + switch (buffer) { + case '=': { + if (currentToken.type === "ATTRIB_NAME") { + currentToken = Token("ASSIGN"); + } else { + currentToken = Token("CONTENT", buffer); + } + break + } + case '') pos++; + currentToken = Token( + "CLOSE_ELEMENT", + xmlAsString.substring(start, pos) + ); + pos++; // skip the ">" + scopingElement.pop(); + break + } + case '/>': { + const scopingElementName = scopingElement.pop(); + currentToken = Token( + "CLOSE_ELEMENT", + scopingElementName + ); + break + } + case ' + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +* `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on + invalid mapping, it will be ignored. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +* `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer, { + ignoreInvalidMapping: true, +}); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map-js/lib/array-set.js b/node_modules/source-map-js/lib/array-set.js new file mode 100644 index 0000000000000000000000000000000000000000..fbd5c81cae66fa6401f871ac7fb02e96fdb9c213 --- /dev/null +++ b/node_modules/source-map-js/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map-js/lib/base64-vlq.js b/node_modules/source-map-js/lib/base64-vlq.js new file mode 100644 index 0000000000000000000000000000000000000000..612b404018ece911ab71fc0a8db326d16e6b1287 --- /dev/null +++ b/node_modules/source-map-js/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map-js/lib/base64.js b/node_modules/source-map-js/lib/base64.js new file mode 100644 index 0000000000000000000000000000000000000000..8aa86b30264363990334a7df0aa0d0c9cc1aecfc --- /dev/null +++ b/node_modules/source-map-js/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map-js/lib/binary-search.js b/node_modules/source-map-js/lib/binary-search.js new file mode 100644 index 0000000000000000000000000000000000000000..010ac941e1568d59c89b67cb649051a14608ee79 --- /dev/null +++ b/node_modules/source-map-js/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map-js/lib/mapping-list.js b/node_modules/source-map-js/lib/mapping-list.js new file mode 100644 index 0000000000000000000000000000000000000000..06d1274a025a8a30879f31c9c6703a14f79f73b9 --- /dev/null +++ b/node_modules/source-map-js/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map-js/lib/quick-sort.js b/node_modules/source-map-js/lib/quick-sort.js new file mode 100644 index 0000000000000000000000000000000000000000..23f9eda57f7383b5291361e4593cf2fdef5409ba --- /dev/null +++ b/node_modules/source-map-js/lib/quick-sort.js @@ -0,0 +1,132 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +function SortTemplate(comparator) { + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + + return doQuickSort; +} + +function cloneSort(comparator) { + let template = SortTemplate.toString(); + let templateFn = new Function(`return ${template}`)(); + return templateFn(comparator); +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + +let sortCache = new WeakMap(); +exports.quickSort = function (ary, comparator, start = 0) { + let doQuickSort = sortCache.get(comparator); + if (doQuickSort === void 0) { + doQuickSort = cloneSort(comparator); + sortCache.set(comparator, doQuickSort); + } + doQuickSort(ary, comparator, start, ary.length - 1); +}; diff --git a/node_modules/source-map-js/lib/source-map-consumer.d.ts b/node_modules/source-map-js/lib/source-map-consumer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..744bda73d103b79b7e654972b9a42c3c95ff432a --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-consumer.d.ts @@ -0,0 +1 @@ +export { SourceMapConsumer } from '..'; diff --git a/node_modules/source-map-js/lib/source-map-consumer.js b/node_modules/source-map-js/lib/source-map-consumer.js new file mode 100644 index 0000000000000000000000000000000000000000..ee66114636c1e3f1b455457ad9e91b0eeeb2d360 --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-consumer.js @@ -0,0 +1,1188 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + var boundCallback = aCallback.bind(context); + var names = this._names; + var sources = this._sources; + var sourceMapURL = this._sourceMapURL; + + for (var i = 0, n = mappings.length; i < n; i++) { + var mapping = mappings[i]; + var source = mapping.source === null ? null : sources.at(mapping.source); + if(source !== null) { + source = util.computeSourceURL(sourceRoot, source, sourceMapURL); + } + boundCallback({ + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : names.at(mapping.name) + }); + } + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + +const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine; +function sortGenerated(array, start) { + let l = array.length; + let n = array.length - start; + if (n <= 1) { + return; + } else if (n == 2) { + let a = array[start]; + let b = array[start + 1]; + if (compareGenerated(a, b) > 0) { + array[start] = b; + array[start + 1] = a; + } + } else if (n < 20) { + for (let i = start; i < l; i++) { + for (let j = i; j > start; j--) { + let a = array[j - 1]; + let b = array[j]; + if (compareGenerated(a, b) <= 0) { + break; + } + array[j - 1] = b; + array[j] = a; + } + } + } else { + quickSort(array, compareGenerated, start); + } +} +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + let subarrayStart = 0; + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + + sortGenerated(generatedMappings, subarrayStart); + subarrayStart = generatedMappings.length; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + let currentSource = mapping.source; + while (originalMappings.length <= currentSource) { + originalMappings.push(null); + } + if (originalMappings[currentSource] === null) { + originalMappings[currentSource] = []; + } + originalMappings[currentSource].push(mapping); + } + } + } + + sortGenerated(generatedMappings, subarrayStart); + this.__generatedMappings = generatedMappings; + + for (var i = 0; i < originalMappings.length; i++) { + if (originalMappings[i] != null) { + quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource); + } + } + this.__originalMappings = [].concat(...originalMappings); + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content || content === '') { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if(source !== null) { + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map-js/lib/source-map-generator.d.ts b/node_modules/source-map-js/lib/source-map-generator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f59d70aa9ca827224617e01d390c9c10b4e81cbc --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-generator.d.ts @@ -0,0 +1 @@ +export { SourceMapGenerator } from '..'; diff --git a/node_modules/source-map-js/lib/source-map-generator.js b/node_modules/source-map-js/lib/source-map-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..bab04ff85b38eb50f942fb7ba84dd46dfe1f00c6 --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-generator.js @@ -0,0 +1,444 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, { + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + })); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + if (this._validateMapping(generated, original, source, name) === false) { + return; + } + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + var message = 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message); + } + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + var message = 'Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + }); + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message) + } + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map-js/lib/source-node.d.ts b/node_modules/source-map-js/lib/source-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4df6a1aca10c42f674f4403b803ced48e030253f --- /dev/null +++ b/node_modules/source-map-js/lib/source-node.d.ts @@ -0,0 +1 @@ +export { SourceNode } from '..'; diff --git a/node_modules/source-map-js/lib/source-node.js b/node_modules/source-map-js/lib/source-node.js new file mode 100644 index 0000000000000000000000000000000000000000..8bcdbe385d2c0d333bcd62648ca700f13f9d3181 --- /dev/null +++ b/node_modules/source-map-js/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map-js/lib/util.js b/node_modules/source-map-js/lib/util.js new file mode 100644 index 0000000000000000000000000000000000000000..430e2d0ff0b2f2a084d00fbfbcf9a229d0a7bfff --- /dev/null +++ b/node_modules/source-map-js/lib/util.js @@ -0,0 +1,594 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +var MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + var cache = []; + + return function(input) { + for (var i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + var temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + var result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +var normalize = lruMemoize(function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + var parts = []; + var start = 0; + var i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { + var cmp + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map-js/package.json b/node_modules/source-map-js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f58dbeb4eca3ad3118fbd5e2a7f6241d5b5aceaa --- /dev/null +++ b/node_modules/source-map-js/package.json @@ -0,0 +1,71 @@ +{ + "name": "source-map-js", + "description": "Generates and consumes source maps", + "version": "1.2.1", + "homepage": "https://github.com/7rulnik/source-map-js", + "author": "Valentin 7rulnik Semirulnik ", + "contributors": [ + "Nick Fitzgerald ", + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": "7rulnik/source-map-js", + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "clean-publish": "^3.1.0", + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "clean-publish": { + "cleanDocs": true + }, + "typings": "source-map.d.ts" +} diff --git a/node_modules/source-map-js/source-map.d.ts b/node_modules/source-map-js/source-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec8892fa11313d34c668e6f0ca9f80fdd5b53aec --- /dev/null +++ b/node_modules/source-map-js/source-map.d.ts @@ -0,0 +1,104 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string | null; + generatedLine: number; + generatedColumn: number; + originalLine: number | null; + originalColumn: number | null; + name: string | null; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + readonly file: string | undefined | null; + readonly sourceRoot: string | undefined | null; + readonly sourcesContent: readonly string[] | null | undefined; + readonly sources: readonly string[] + + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original?: Position | null; + source?: string | null; + name?: string | null; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer, startOfSourceMap?: StartOfSourceMap): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string | null | undefined): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; + toJSON(): RawSourceMap; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map-js/source-map.js b/node_modules/source-map-js/source-map.js new file mode 100644 index 0000000000000000000000000000000000000000..bc88fe820c87a217d27eb010281fe39b71163835 --- /dev/null +++ b/node_modules/source-map-js/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/source-map-support/LICENSE.md b/node_modules/source-map-support/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..6247ca912cb4bcc379aed9b711290dc3d174f915 --- /dev/null +++ b/node_modules/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Evan Wallace + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/source-map-support/README.md b/node_modules/source-map-support/README.md new file mode 100644 index 0000000000000000000000000000000000000000..40228b7910cd798dd5ff06d68d82255c5b9096bb --- /dev/null +++ b/node_modules/source-map-support/README.md @@ -0,0 +1,284 @@ +# Source Map Support +[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support) + +This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. + +## Installation and Usage + +#### Node support + +``` +$ npm install source-map-support +``` + +Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): + +``` +//# sourceMappingURL=path/to/source.map +``` + +If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be +respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). +The path should either be absolute or relative to the compiled file. + +From here you have two options. + +##### CLI Usage + +```bash +node -r source-map-support/register compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('source-map-support').install(); +``` + +It is also possible to install the source map support directly by +requiring the `register` module which can be handy with ES6: + +```js +import 'source-map-support/register' + +// Instead of: +import sourceMapSupport from 'source-map-support' +sourceMapSupport.install() +``` +Note: if you're using babel-register, it includes source-map-support already. + +It is also very useful with Mocha: + +``` +$ mocha --require source-map-support/register tests/ +``` + +#### Browser support + +This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. + +This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. + +```html + + +``` + +This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: + +```html + +``` + +## Options + +This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: + +```js +require('source-map-support').install({ + handleUncaughtExceptions: false +}); +``` + +This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. + +```js +require('source-map-support').install({ + retrieveSourceMap: function(source) { + if (source === 'compiled.js') { + return { + url: 'original.js', + map: fs.readFileSync('compiled.js.map', 'utf8') + }; + } + return null; + } +}); +``` + +The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. +In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. + +```js +require('source-map-support').install({ + environment: 'node' +}); +``` + +To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. + + +```js +require('source-map-support').install({ + hookRequire: true +}); +``` + +This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. + +## Demos + +#### Basic Demo + +original.js: + +```js +throw new Error('test'); // This is the original code +``` + +compiled.js: + +```js +require('source-map-support').install(); + +throw new Error('test'); // This is the compiled code +// The next line defines the sourceMapping. +//# sourceMappingURL=compiled.js.map +``` + +compiled.js.map: + +```json +{ + "version": 3, + "file": "compiled.js", + "sources": ["original.js"], + "names": [], + "mappings": ";;AAAA,MAAM,IAAI" +} +``` + +Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): + +``` +$ node compiled.js + +original.js:1 +throw new Error('test'); // This is the original code + ^ +Error: test + at Object. (original.js:1:7) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### TypeScript Demo + +demo.ts: + +```typescript +declare function require(name: string); +require('source-map-support').install(); +class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } +} +new Foo(); +``` + +Compile and run the file using the TypeScript compiler from the terminal: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base: + +``` +$ npm install source-map-support typescript +$ node_modules/typescript/bin/tsc -sourcemap demo.ts +$ node -r source-map-support/register demo.js + +demo.ts:5 + bar() { throw new Error('this is a demo'); } + ^ +Error: this is a demo + at Foo.bar (demo.ts:5:17) + at new Foo (demo.ts:4:24) + at Object. (demo.ts:7:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) + at node.js:901:3 +``` + +#### CoffeeScript Demo + +demo.coffee: + +```coffee +require('source-map-support').install() +foo = -> + bar = -> throw new Error 'this is a demo' + bar() +foo() +``` + +Compile and run the file using the CoffeeScript compiler from the terminal: + +```sh +$ npm install source-map-support coffeescript +$ node_modules/.bin/coffee --map --compile demo.coffee +$ node demo.js + +demo.coffee:3 + bar = -> throw new Error 'this is a demo' + ^ +Error: this is a demo + at bar (demo.coffee:3:22) + at foo (demo.coffee:4:3) + at Object. (demo.coffee:5:1) + at Object. (demo.coffee:1:1) + at Module._compile (module.js:456:26) + at Object.Module._extensions..js (module.js:474:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Function.Module.runMain (module.js:497:10) + at startup (node.js:119:16) +``` + +## Tests + +This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: + +* Build the tests using `build.js` +* Launch the HTTP server (`npm run serve-tests`) and visit + * http://127.0.0.1:1336/amd-test + * http://127.0.0.1:1336/browser-test + * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). +* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ + +## License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/node_modules/source-map-support/browser-source-map-support.js b/node_modules/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000000000000000000000000000000000000..782da501459760dd729b76cb0a80358063f70e30 --- /dev/null +++ b/node_modules/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * Support for source maps in V8 stack traces + * https://github.com/evanw/node-source-map-support + */ +/* + The buffer module from node.js, for the browser. + + @author Feross Aboukhadijeh + license MIT +*/ +(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;mm)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q> +18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+ +m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"=== +typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding'); +return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string"); +if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;ba)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||ba.length)throw new TypeError("index out of range"); +}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a, +b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y=b.length||y>=a.length);y++)b[y+ +h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null== +a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length; +break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;hw?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b= +this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;ab&&(a+=" ... "));return""};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead."); +return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/ +2&&(h=w/2);for(w=0;w>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+ +w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a, +b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+ +2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(wb||b>=a.length)throw new TypeError("targetStart out of bounds"); +if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||b>=this.length)throw new TypeError("start out of bounds"); +if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0>=-r;for(r+=m;0>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+= +d,p/=256,f-=8);m=m<z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1); +for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;gl&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!== +m||"process-tick"!==t.data||(t.stopPropagation(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C, +J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine, +c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d, +"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source= +null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+ +k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)]; +var g=this.sources,n;for(n=0;n +g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/, +u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d, +g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine- +g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/, +""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16, +"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F";B=this.getLineNumber();null!=B&&(x+=":"+B,(B= +this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||""):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]= +/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O= +f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F= +(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+ +"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0 C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + var contents = ''; + try { + if (!fs) { + // Use SJAX if we are in the browser + var xhr = new XMLHttpRequest(); + xhr.open('GET', path, /** async */ false); + xhr.send(null); + if (xhr.readyState === 4 && xhr.status === 200) { + contents = xhr.responseText; + } + } else if (fs.existsSync(path)) { + // Otherwise, use the filesystem + contents = fs.readFileSync(path, 'utf8'); + } + } catch (er) { + /* ignore any errors */ + } + + return fileContentsCache[path] = contents; +}); + +// Support URLs relative to a directory, but be careful about a protocol prefix +// in case we are in the browser (i.e. directories may start with "http://" or "file:///") +function supportRelativeURL(file, url) { + if (!file) return url; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +function retrieveSourceMapURL(source) { + var fileData; + + if (isInBrowser()) { + try { + var xhr = new XMLHttpRequest(); + xhr.open('GET', source, false); + xhr.send(null); + fileData = xhr.readyState === 4 ? xhr.responseText : null; + + // Support providing a sourceMappingURL via the SourceMap header + var sourceMapHeader = xhr.getResponseHeader("SourceMap") || + xhr.getResponseHeader("X-SourceMap"); + if (sourceMapHeader) { + return sourceMapHeader; + } + } catch (e) { + } + } + + // Get the URL of the source map + fileData = retrieveFile(source); + var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg; + // Keep executing the search to find the *last* sourceMappingURL to avoid + // picking up sourceMappingURLs from comments, strings, etc. + var lastMatch, match; + while (match = re.exec(fileData)) lastMatch = match; + if (!lastMatch) return null; + return lastMatch[1]; +}; + +// Can be overridden by the retrieveSourceMap option to install. Takes a +// generated source filename; returns a {map, optional url} object, or null if +// there is no source map. The map field may be either a string or the parsed +// JSON object (ie, it must be a valid argument to the SourceMapConsumer +// constructor). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.push(function(source) { + var sourceMappingURL = retrieveSourceMapURL(source); + if (!sourceMappingURL) return null; + + // Read the contents of the source map + var sourceMapData; + if (reSourceMap.test(sourceMappingURL)) { + // Support source map URL as a data url + var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1); + sourceMapData = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // Load all sources stored inline with the source map into the file cache + // to pretend like they are already loaded. They may not exist on disk. + if (sourceMap.map.sourcesContent) { + sourceMap.map.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { + var originalPosition = sourceMap.map.originalPositionFor(position); + + // Only return the original position if a matching line was found. If no + // matching line is found then we return position instead, which will cause + // the stack trace to print the path and line for the compiled file. It is + // better to give a precise location in the compiled file than a vague + // location in the original file. + if (originalPosition.source !== null) { + originalPosition.source = supportRelativeURL( + sourceMap.url, originalPosition.source); + return originalPosition; + } + } + + return position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition({ + source: match[2], + line: +match[3], + column: match[4] - 1 + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + (position.column + 1) + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +// This is copied almost verbatim from the V8 source code at +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The +// implementation of wrapCallSite() used to just forward to the actual source +// code of CallSite.prototype.toString but unfortunately a new release of V8 +// did something to the prototype chain and broke the shim. The only fix I +// could find was copy/paste. +function CallSiteToString() { + var fileName; + var fileLocation = ""; + if (this.isNative()) { + fileLocation = "native"; + } else { + fileName = this.getScriptNameOrSourceURL(); + if (!fileName && this.isEval()) { + fileLocation = this.getEvalOrigin(); + fileLocation += ", "; // Expecting source position to follow. + } + + if (fileName) { + fileLocation += fileName; + } else { + // Source code does not originate from a file and is not native, but we + // can still get the source position inside the source string, e.g. in + // an eval string. + fileLocation += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + var functionName = this.getFunctionName(); + var addSuffix = true; + var isConstructor = this.isConstructor(); + var isMethodCall = !(this.isToplevel() || isConstructor); + if (isMethodCall) { + var typeName = this.getTypeName(); + // Fixes shim to be backward compatable with Node v0 to v4 + if (typeName === "[object Object]") { + typeName = "null"; + } + var methodName = this.getMethodName(); + if (functionName) { + if (typeName && functionName.indexOf(typeName) != 0) { + line += typeName + "."; + } + line += functionName; + if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) { + line += " [as " + methodName + "]"; + } + } else { + line += typeName + "." + (methodName || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } else if (functionName) { + line += functionName; + } else { + line += fileLocation; + addSuffix = false; + } + if (addSuffix) { + line += " (" + fileLocation + ")"; + } + return line; +} + +function cloneCallSite(frame) { + var object = {}; + Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) { + object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name]; + }); + object.toString = CallSiteToString; + return object; +} + +function wrapCallSite(frame, state) { + // provides interface backward compatibility + if (state === undefined) { + state = { nextPosition: null, curPosition: null } + } + if(frame.isNative()) { + state.curPosition = null; + return frame; + } + + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//# sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var line = frame.getLineNumber(); + var column = frame.getColumnNumber() - 1; + + // Fix position in Node where some (internal) code is prepended. + // See https://github.com/evanw/node-source-map-support/issues/36 + // Header removed in node at ^10.16 || >=11.11.0 + // v11 is not an LTS candidate, we can just test the one version with it. + // Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11 + var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/; + var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62; + if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) { + column -= headerLength; + } + + var position = mapSourcePosition({ + source: source, + line: line, + column: column + }); + state.curPosition = position; + frame = cloneCallSite(frame); + var originalFunctionName = frame.getFunctionName; + frame.getFunctionName = function() { + if (state.nextPosition == null) { + return originalFunctionName(); + } + return state.nextPosition.name || originalFunctionName(); + }; + frame.getFileName = function() { return position.source; }; + frame.getLineNumber = function() { return position.line; }; + frame.getColumnNumber = function() { return position.column + 1; }; + frame.getScriptNameOrSourceURL = function() { return position.source; }; + return frame; + } + + // Code called using eval() needs special handling + var origin = frame.isEval() && frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(origin); + frame = cloneCallSite(frame); + frame.getEvalOrigin = function() { return origin; }; + return frame; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// https://v8.dev/docs/stack-trace-api +function prepareStackTrace(error, stack) { + if (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + var name = error.name || 'Error'; + var message = error.message || ''; + var errorString = name + ": " + message; + + var state = { nextPosition: null, curPosition: null }; + var processedStack = []; + for (var i = stack.length - 1; i >= 0; i--) { + processedStack.push('\n at ' + wrapCallSite(stack[i], state)); + state.nextPosition = state.curPosition; + } + state.curPosition = state.nextPosition = null; + return errorString + processedStack.reverse().join(''); +} + +// Generate position and snippet of original source with pointer +function getErrorSource(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var source = match[1]; + var line = +match[2]; + var column = +match[3]; + + // Support the inline sourceContents inside the source map + var contents = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, 'utf8'); + } catch (er) { + contents = ''; + } + } + + // Format the line from the original source code like node does + if (contents) { + var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; + if (code) { + return source + ':' + line + '\n' + code + '\n' + + new Array(column).join(' ') + '^'; + } + } + } + return null; +} + +function printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + var stderr = globalProcessStderr(); + if (stderr && stderr._handle && stderr._handle.setBlocking) { + stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + globalProcessExit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0); + +exports.wrapCallSite = wrapCallSite; +exports.getErrorSource = getErrorSource; +exports.mapSourcePosition = mapSourcePosition; +exports.retrieveSourceMap = retrieveSourceMap; + +exports.install = function(options) { + options = options || {}; + + if (options.environment) { + environment = options.environment; + if (["node", "browser", "auto"].indexOf(environment) === -1) { + throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + retrieveFileHandlers.unshift(options.retrieveFile); + } + + // Allow source maps to be found by methods other than reading the files + // directly from disk. + if (options.retrieveSourceMap) { + if (options.overrideRetrieveSourceMap) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + var installHandler = 'handleUncaughtExceptions' in options ? + options.handleUncaughtExceptions : true; + + // Do not override 'uncaughtException' with our own handler in Node.js + // Worker threads. Workers pass the error to the main thread as an event, + // rather than printing something to stderr and exiting. + try { + // We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify. + var worker_threads = dynamicRequire(module, 'worker_threads'); + if (worker_threads.isMainThread === false) { + installHandler = false; + } + } catch(e) {} + + // Provide the option to not install the uncaught exception handler. This is + // to support other uncaught exception handlers (in test frameworks, for + // example). If this handler is not installed and there are no other uncaught + // exception handlers, uncaught exceptions will be caught by node's built-in + // exception handler and the process will still be terminated. However, the + // generated JavaScript code will be shown above the stack trace instead of + // the original source code. + if (installHandler && hasGlobalProcessEventEmitter()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); + + retrieveSourceMap = handlerExec(retrieveMapHandlers); + retrieveFile = handlerExec(retrieveFileHandlers); +} diff --git a/node_modules/stackback/.npmignore b/node_modules/stackback/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..3c3629e647f5ddf82548912e337bea9826b434af --- /dev/null +++ b/node_modules/stackback/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/stackback/.travis.yml b/node_modules/stackback/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..320698af0f565b2ac32987b5d23ed6aca5c7ef5a --- /dev/null +++ b/node_modules/stackback/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/stackback/README.md b/node_modules/stackback/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fb6bde7486827b31d96cd2bfc1f96fd945bbf011 --- /dev/null +++ b/node_modules/stackback/README.md @@ -0,0 +1,41 @@ +# stackback + +Returns an array of CallSite objects for a captured stacktrace. Useful if you want to access the frame for an error object. + +## use + +```javascript +var stackback = require('stackback'); + +// error generated from somewhere +var err = new Error('some sample error'); + +// stack is an array of CallSite objects +var stack = stackback(err); +``` + +## CallSite object + +From the [V8 StackTrace API](https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi) + +The structured stack trace is an Array of CallSite objects, each of which represents a stack frame. A CallSite object defines the following methods + +getThis: returns the value of this +getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. +getFunction: returns the current function +getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. +getMethodName: returns the name of the property of this or one of its prototypes that holds the current function +getFileName: if this function was defined in a script returns the name of the script +getLineNumber: if this function was defined in a script returns the current line number +getColumnNumber: if this function was defined in a script returns the current column number +getEvalOrigin: if this function was created using a call to eval returns a CallSite object representing the location where eval was called +isToplevel: is this a toplevel invocation, that is, is this the global object? +isEval: does this call take place in code defined by a call to eval? +isNative: is this call in native V8 code? +isConstructor: is this a constructor call? + +## install + +```shell +npm install stackback +``` diff --git a/node_modules/stackback/formatstack.js b/node_modules/stackback/formatstack.js new file mode 100644 index 0000000000000000000000000000000000000000..d64307d210dd134dff936607480695b86f3b6776 --- /dev/null +++ b/node_modules/stackback/formatstack.js @@ -0,0 +1,57 @@ +// Copyright 2012 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +function FormatStackTrace(error, frames) { + var lines = []; + try { + lines.push(error.toString()); + } catch (e) { + try { + lines.push(""); + } catch (ee) { + lines.push(""); + } + } + for (var i = 0; i < frames.length; i++) { + var frame = frames[i]; + var line; + try { + line = frame.toString(); + } catch (e) { + try { + line = ""; + } catch (ee) { + // Any code that reaches this point is seriously nasty! + line = ""; + } + } + lines.push(" at " + line); + } + return lines.join("\n"); +} + +module.exports = FormatStackTrace; diff --git a/node_modules/stackback/index.js b/node_modules/stackback/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8b87042343d7e6fc238075138f72f4ff3fa58d5e --- /dev/null +++ b/node_modules/stackback/index.js @@ -0,0 +1,46 @@ + +// v8 builtin format stack trace +// for when there was no previous prepareStackTrace function to call +var FormatStackTrace = require('./formatstack'); + +// some notes on the behavior below: +// because the 'stack' member is a one shot access variable (the raw stack is +// formatted on accessing it) +// we try to avoid modifying what the user would have wanted +// thus we use the previous value for prepareStackTrace +// +// The reason we store the callsite variable is because prepareStackTrace +// will not be called again once it has been called for a given error object +// but we want to support getting the stack out of the error multiple times (cause why not) +module.exports = function(err) { + + // save original stacktrace + var save = Error.prepareStackTrace; + + // replace capture with our function + Error.prepareStackTrace = function(err, trace) { + + // cache stack frames so we don't have to get them again + // use a non-enumerable property + Object.defineProperty(err, '_sb_callsites', { + value: trace + }); + + return (save || FormatStackTrace)(err, trace); + }; + + // force capture of the stack frames + err.stack; + + // someone already asked for the stack so we can't do this trick + // TODO fallback to string parsing? + if (!err._sb_callsites) { + return []; + } + + // return original capture function + Error.prepareStackTrace = save; + + return err._sb_callsites; +}; + diff --git a/node_modules/stackback/package.json b/node_modules/stackback/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3e8b7b2c023d3535e0869b0959616cda4d654fc8 --- /dev/null +++ b/node_modules/stackback/package.json @@ -0,0 +1,23 @@ +{ + "name": "stackback", + "version": "0.0.2", + "description": "return list of CallSite objects from a captured stacktrace", + "main": "index.js", + "scripts": { + "test": "mocha --ui qunit" + }, + "repository": { + "type": "git", + "url": "git://github.com/shtylman/node-stackback.git" + }, + "keywords": [ + "stacktrace", + "trace", + "stack" + ], + "devDependencies": { + "mocha": "~1.6.0" + }, + "author": "Roman Shtylman ", + "license": "MIT" +} diff --git a/node_modules/stackback/test.js b/node_modules/stackback/test.js new file mode 100644 index 0000000000000000000000000000000000000000..212b414ab496cf76d2a6977bd935ce714508482f --- /dev/null +++ b/node_modules/stackback/test.js @@ -0,0 +1,24 @@ +var assert = require('assert'); +var stackback = require('./'); + +test('capture', function() { + var err = new Error(); + var stack = stackback(err); + assert.equal(stack[0].getFileName(), __filename); +}); + +// calling stackback on the same error twice should work +test('multiple calls', function() { + var err = new Error(); + var stack1 = stackback(err); + var stack2 = stackback(err); + assert.equal(stack1[0].getFileName(), __filename); + assert.deepEqual(stack1, stack2); +}); + +test('string', function() { + var err = new Error(); + stackback(err); + assert.equal(typeof err.stack, 'string'); +}); + diff --git a/node_modules/statuses/HISTORY.md b/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..dc549b8216582796d92fb78868317155cc6d1044 --- /dev/null +++ b/node_modules/statuses/HISTORY.md @@ -0,0 +1,87 @@ +2.0.2 / 2025-06-06 +================== + + * Migrate to `String.prototype.slice()` + +2.0.1 / 2021-01-03 +================== + + * Fix returning values from `Object.prototype` + +2.0.0 / 2020-04-19 +================== + + * Drop support for Node.js 0.6 + * Fix messaging casing of `418 I'm a Teapot` + * Remove code 306 + * Remove `status[code]` exports; use `status.message[code]` + * Remove `status[msg]` exports; use `status.code[msg]` + * Rename `425 Unordered Collection` to standard `425 Too Early` + * Rename `STATUS_CODES` export to `message` + * Return status message for `statuses(code)` when given code + +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/statuses/LICENSE b/node_modules/statuses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28a31618205d7dbeed5b966fe9d2c682bd9367f5 --- /dev/null +++ b/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/statuses/README.md b/node_modules/statuses/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89d542f6a4022fa409b0c38875c1c15991081a23 --- /dev/null +++ b/node_modules/statuses/README.md @@ -0,0 +1,139 @@ +# statuses + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### status(code) + +Returns the status message string for a known HTTP status code. The code +may be a number or a string. An error is thrown for an unknown status code. + + + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status(306) // throws +``` + +### status(msg) + +Returns the numeric status code for a known HTTP status message. The message +is case-insensitive. An error is thrown for an unknown status message. + + + +```js +status('forbidden') // => 403 +status('Forbidden') // => 403 +status('foo') // throws +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### status.code[msg] + +Returns the numeric status code for a known status message (in lower-case), +otherwise `undefined`. + + + +```js +status['not found'] // => 404 +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.message[code] + +Returns the string message for a known numeric status code, otherwise +`undefined`. This object is the same format as the +[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + + + +```js +status.message[404] // => 'Not Found' +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci +[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[node-version-image]: https://badgen.net/npm/node/statuses +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/statuses +[npm-url]: https://npmjs.org/package/statuses +[npm-version-image]: https://badgen.net/npm/v/statuses +[ossf-scorecard-badge]: https://api.securityscorecards.dev/projects/github.com/jshttp/statuses/badge +[ossf-scorecard-visualizer]: https://kooltheba.github.io/openssf-scorecard-api-visualizer/#/projects/github.com/jshttp/statuses diff --git a/node_modules/statuses/codes.json b/node_modules/statuses/codes.json new file mode 100644 index 0000000000000000000000000000000000000000..1333ed10bab28344b55c217d80ce4f6cc2555793 --- /dev/null +++ b/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea351c553520e1bc62d53b97a316194c48ac49e6 --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b5d016edd9c4eef0bb227af4a01c49e73c5f78dc --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "7.19.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.31.0", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0", + "raw-body": "2.5.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/std-env/LICENCE b/node_modules/std-env/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..db8fffe6a1f33b4b247463e60d9528b504a2eba8 --- /dev/null +++ b/node_modules/std-env/LICENCE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/std-env/README.md b/node_modules/std-env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a722f010625fa290d4d6cfc10814e0c77bd758b --- /dev/null +++ b/node_modules/std-env/README.md @@ -0,0 +1,91 @@ +# std-env + +[![npm version](https://img.shields.io/npm/v/std-env.svg?style=flat-square)](http://npmjs.com/package/std-env) +[![npm downloads](https://img.shields.io/npm/dm/std-env.svg?style=flat-square)](http://npmjs.com/package/std-env) +[![bundle size](https://img.shields.io/bundlephobia/min/std-env/latest.svg?style=flat-square)](https://bundlephobia.com/result?p=std-env) + +Runtime-agnostic JS utils for detecting environments, runtimes, CI providers, and AI coding agents. + +## Runtime Detection + +Detects the current JavaScript runtime based on global variables, following the [WinterCG Runtime Keys proposal](https://runtime-keys.proposal.wintercg.org/). + +```ts +import { runtime, runtimeInfo } from "std-env"; + +console.log(runtime); // "" | "node" | "deno" | "bun" | "workerd" ... +console.log(runtimeInfo); // { name: "node" } +``` + +Individual named exports: `isNode`, `isBun`, `isDeno`, `isNetlify`, `isEdgeLight`, `isWorkerd`, `isFastly` + +> [!NOTE] +> `isNode` is also `true` in Bun/Deno with Node.js compatibility mode. Use `runtime === "node"` for strict checks. + +See [./src/runtimes.ts](./src/runtimes.ts) for the full list. + +## Provider Detection + +Detects the current CI/CD provider based on environment variables. + +```ts +import { isCI, provider, providerInfo } from "std-env"; + +console.log({ isCI, provider, providerInfo }); +// { isCI: true, provider: "github_actions", providerInfo: { name: "github_actions", ci: true } } +``` + +Use `detectProvider()` to re-run detection. See [./src/providers.ts](./src/providers.ts) for the full list. + +## Agent Detection + +Detects if the environment is running inside an AI coding agent. + +```ts +import { isAgent, agent, agentInfo } from "std-env"; + +console.log({ isAgent, agent, agentInfo }); +// { isAgent: true, agent: "claude", agentInfo: { name: "claude" } } +``` + +Set the `AI_AGENT` env var to explicitly specify the agent name. Use `detectAgent()` to re-run detection. + +Supported agents: `cursor`, `claude`, `devin`, `replit`, `gemini`, `codex`, `auggie`, `opencode`, `kiro`, `goose`, `pi` + +## Flags + +```js +import { env, isDevelopment, isProduction } from "std-env"; +``` + +| Export | Description | +| ------------------ | ------------------------------------------------------------ | +| `hasTTY` | stdout TTY is available | +| `hasWindow` | Global `window` is available | +| `isCI` | Running in CI | +| `isColorSupported` | Terminal color output supported | +| `isDebug` | `DEBUG` env var is set | +| `isDevelopment` | `NODE_ENV` is `dev`/`development` or `MODE` is `development` | +| `isLinux` | Linux platform | +| `isMacOS` | macOS (darwin) platform | +| `isMinimal` | `MINIMAL` env is set, CI, test, or no TTY | +| `isProduction` | `NODE_ENV` or `MODE` is `production` | +| `isTest` | `NODE_ENV` is `test` or `TEST` env is set | +| `isWindows` | Windows platform | +| `platform` | Value of `process.platform` | +| `nodeVersion` | Node.js version string (e.g. `"22.0.0"`) | +| `nodeMajorVersion` | Node.js major version number (e.g. `22`) | + +See [./src/flags.ts](./src/flags.ts) for details. + +## Environment + +| Export | Description | +| --------- | ---------------------------------------------------- | +| `env` | Universal `process.env` (works across all runtimes) | +| `process` | Universal `process` shim (works across all runtimes) | +| `nodeENV` | Current `NODE_ENV` value (undefined if unset) | + +## License + +MIT diff --git a/node_modules/std-env/package.json b/node_modules/std-env/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a2d4f34cfc104a36841ca9b3550373be952399c6 --- /dev/null +++ b/node_modules/std-env/package.json @@ -0,0 +1,42 @@ +{ + "name": "std-env", + "version": "4.1.0", + "description": "Runtime agnostic JS utils", + "license": "MIT", + "repository": "unjs/std-env", + "files": [ + "dist" + ], + "type": "module", + "sideEffects": false, + "main": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "exports": { + ".": "./dist/index.mjs" + }, + "scripts": { + "build": "obuild", + "dev": "vitest", + "lint": "oxlint . && oxfmt", + "lint:fix": "oxlint --fix . && oxfmt", + "prepack": "obuild", + "release": "pnpm test && pnpm build && changelogen --release --publish && git push --follow-tags", + "test": "pnpm lint && pnpm typecheck && vitest run --coverage", + "typecheck": "tsgo --noEmit" + }, + "devDependencies": { + "@types/node": "^25.2.3", + "@typescript/native-preview": "^7.0.0-dev.20260217.1", + "@vitest/coverage-v8": "^4.0.18", + "changelogen": "^0.6.2", + "esbuild": "^0.27.3", + "mitata": "^1.0.34", + "obuild": "^0.4.28", + "oxfmt": "^0.33.0", + "oxlint": "^1.48.0", + "rollup": "^4.57.1", + "typescript": "^5.9.3", + "vitest": "^4.0.18" + }, + "packageManager": "pnpm@10.30.0" +} diff --git a/node_modules/streamsearch/.eslintrc.js b/node_modules/streamsearch/.eslintrc.js new file mode 100644 index 0000000000000000000000000000000000000000..be9311d02655a22381f13078bfe868bcbd85b3a6 --- /dev/null +++ b/node_modules/streamsearch/.eslintrc.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + extends: '@mscdex/eslint-config', +}; diff --git a/node_modules/streamsearch/.github/workflows/ci.yml b/node_modules/streamsearch/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..29d51782c77a93f2a32774350fb6e6229ebc3408 --- /dev/null +++ b/node_modules/streamsearch/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + tests-linux: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [10.x, 12.x, 14.x, 16.x] + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install module + run: npm install + - name: Run tests + run: npm test diff --git a/node_modules/streamsearch/.github/workflows/lint.yml b/node_modules/streamsearch/.github/workflows/lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..9f9e1f589a30be583a860f928382b3033c38749d --- /dev/null +++ b/node_modules/streamsearch/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: lint + +on: + pull_request: + push: + branches: [ master ] + +env: + NODE_VERSION: 16.x + +jobs: + lint-js: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v1 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Install ESLint + ESLint configs/plugins + run: npm install --only=dev + - name: Lint files + run: npm run lint diff --git a/node_modules/streamsearch/LICENSE b/node_modules/streamsearch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9ea90e03922d5e31b32e5ff84f4e51a6ca0760b5 --- /dev/null +++ b/node_modules/streamsearch/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/streamsearch/README.md b/node_modules/streamsearch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3934d1c7d57119aa31103bc6389838c646e2fc2 --- /dev/null +++ b/node_modules/streamsearch/README.md @@ -0,0 +1,95 @@ +Description +=========== + +streamsearch is a module for [node.js](http://nodejs.org/) that allows searching a stream using the Boyer-Moore-Horspool algorithm. + +This module is based heavily on the Streaming Boyer-Moore-Horspool C++ implementation by Hongli Lai [here](https://github.com/FooBarWidget/boyer-moore-horspool). + + +Requirements +============ + +* [node.js](http://nodejs.org/) -- v10.0.0 or newer + + +Installation +============ + + npm install streamsearch + +Example +======= + +```js + const { inspect } = require('util'); + + const StreamSearch = require('streamsearch'); + + const needle = Buffer.from('\r\n'); + const ss = new StreamSearch(needle, (isMatch, data, start, end) => { + if (data) + console.log('data: ' + inspect(data.toString('latin1', start, end))); + if (isMatch) + console.log('match!'); + }); + + const chunks = [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ]; + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + // output: + // + // data: 'foo' + // data: ' bar' + // match! + // data: 'baz, hello' + // match! + // data: ' world.' + // match! + // data: ' Node.JS rules!!' + // match! + // data: '' + // match! +``` + + +API +=== + +Properties +---------- + +* **maxMatches** - < _integer_ > - The maximum number of matches. Defaults to `Infinity`. + +* **matches** - < _integer_ > - The current match count. + + +Functions +--------- + +* **(constructor)**(< _mixed_ >needle, < _function_ >callback) - Creates and returns a new instance for searching for a _Buffer_ or _string_ `needle`. `callback` is called any time there is non-matching data and/or there is a needle match. `callback` will be called with the following arguments: + + 1. `isMatch` - _boolean_ - Indicates whether a match has been found + + 2. `data` - _mixed_ - If set, this contains data that did not match the needle. + + 3. `start` - _integer_ - The index in `data` where the non-matching data begins (inclusive). + + 4. `end` - _integer_ - The index in `data` where the non-matching data ends (exclusive). + + 5. `isSafeData` - _boolean_ - Indicates if it is safe to store a reference to `data` (e.g. as-is or via `data.slice()`) or not, as in some cases `data` may point to a Buffer whose contents change over time. + +* **destroy**() - _(void)_ - Emits any last remaining unmatched data that may still be buffered and then resets internal state. + +* **push**(< _Buffer_ >chunk) - _integer_ - Processes `chunk`, searching for a match. The return value is the last processed index in `chunk` + 1. + +* **reset**() - _(void)_ - Resets internal state. Useful for when you wish to start searching a new/different stream for example. + diff --git a/node_modules/streamsearch/lib/sbmh.js b/node_modules/streamsearch/lib/sbmh.js new file mode 100644 index 0000000000000000000000000000000000000000..510cae26e67a58d4c1cdfb4ed5afd80c0f50c782 --- /dev/null +++ b/node_modules/streamsearch/lib/sbmh.js @@ -0,0 +1,267 @@ +'use strict'; +/* + Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool +*/ +function memcmp(buf1, pos1, buf2, pos2, num) { + for (let i = 0; i < num; ++i) { + if (buf1[pos1 + i] !== buf2[pos2 + i]) + return false; + } + return true; +} + +class SBMH { + constructor(needle, cb) { + if (typeof cb !== 'function') + throw new Error('Missing match callback'); + + if (typeof needle === 'string') + needle = Buffer.from(needle); + else if (!Buffer.isBuffer(needle)) + throw new Error(`Expected Buffer for needle, got ${typeof needle}`); + + const needleLen = needle.length; + + this.maxMatches = Infinity; + this.matches = 0; + + this._cb = cb; + this._lookbehindSize = 0; + this._needle = needle; + this._bufPos = 0; + + this._lookbehind = Buffer.allocUnsafe(needleLen); + + // Initialize occurrence table. + this._occ = [ + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen + ]; + + // Populate occurrence table with analysis of the needle, ignoring the last + // letter. + if (needleLen > 1) { + for (let i = 0; i < needleLen - 1; ++i) + this._occ[needle[i]] = needleLen - 1 - i; + } + } + + reset() { + this.matches = 0; + this._lookbehindSize = 0; + this._bufPos = 0; + } + + push(chunk, pos) { + let result; + if (!Buffer.isBuffer(chunk)) + chunk = Buffer.from(chunk, 'latin1'); + const chunkLen = chunk.length; + this._bufPos = pos || 0; + while (result !== chunkLen && this.matches < this.maxMatches) + result = feed(this, chunk); + return result; + } + + destroy() { + const lbSize = this._lookbehindSize; + if (lbSize) + this._cb(false, this._lookbehind, 0, lbSize, false); + this.reset(); + } +} + +function feed(self, data) { + const len = data.length; + const needle = self._needle; + const needleLen = needle.length; + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehindSize - 2] + let pos = -self._lookbehindSize; + const lastNeedleCharPos = needleLen - 1; + const lastNeedleChar = needle[lastNeedleCharPos]; + const end = len - needleLen; + const occ = self._occ; + const lookbehind = self._lookbehind; + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= end) { + const nextPos = pos + lastNeedleCharPos; + const ch = (nextPos < 0 + ? lookbehind[self._lookbehindSize + nextPos] + : data[nextPos]); + + if (ch === lastNeedleChar + && matchNeedle(self, data, pos, lastNeedleCharPos)) { + self._lookbehindSize = 0; + ++self.matches; + if (pos > -self._lookbehindSize) + self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // No match. + + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !matchNeedle(self, data, pos, len - pos)) + ++pos; + + if (pos < 0) { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = self._lookbehindSize + pos; + + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + self._cb(false, lookbehind, 0, bytesToCutOff, false); + } + + self._lookbehindSize -= bytesToCutOff; + lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize); + lookbehind.set(data, self._lookbehindSize); + self._lookbehindSize += len; + + self._bufPos = len; + return len; + } + + // Discard lookbehind buffer. + self._cb(false, lookbehind, 0, self._lookbehindSize, false); + self._lookbehindSize = 0; + } + + pos += self._bufPos; + + const firstNeedleChar = needle[0]; + + // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool + // search with optimized character lookup code that only considers + // the current round's haystack data. + while (pos <= end) { + const ch = data[pos + lastNeedleCharPos]; + + if (ch === lastNeedleChar + && data[pos] === firstNeedleChar + && memcmp(needle, 0, data, pos, lastNeedleCharPos)) { + ++self.matches; + if (pos > 0) + self._cb(true, data, self._bufPos, pos, true); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while (pos < len) { + if (data[pos] !== firstNeedleChar + || !memcmp(data, pos, needle, 0, len - pos)) { + ++pos; + continue; + } + data.copy(lookbehind, 0, pos, len); + self._lookbehindSize = len - pos; + break; + } + + // Everything until `pos` is guaranteed not to contain needle data. + if (pos > 0) + self._cb(false, data, self._bufPos, pos < len ? pos : len, true); + + self._bufPos = len; + return len; +} + +function matchNeedle(self, data, pos, len) { + const lb = self._lookbehind; + const lbSize = self._lookbehindSize; + const needle = self._needle; + + for (let i = 0; i < len; ++i, ++pos) { + const ch = (pos < 0 ? lb[lbSize + pos] : data[pos]); + if (ch !== needle[i]) + return false; + } + return true; +} + +module.exports = SBMH; diff --git a/node_modules/streamsearch/package.json b/node_modules/streamsearch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..51df8f9707cebd8469d793a8d90050baac1c4d1d --- /dev/null +++ b/node_modules/streamsearch/package.json @@ -0,0 +1,34 @@ +{ + "name": "streamsearch", + "version": "1.1.0", + "author": "Brian White ", + "description": "Streaming Boyer-Moore-Horspool searching for node.js", + "main": "./lib/sbmh.js", + "engines": { + "node": ">=10.0.0" + }, + "devDependencies": { + "@mscdex/eslint-config": "^1.1.0", + "eslint": "^7.32.0" + }, + "scripts": { + "test": "node test/test.js", + "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js lib test", + "lint:fix": "npm run lint -- --fix" + }, + "keywords": [ + "stream", + "horspool", + "boyer-moore-horspool", + "boyer-moore", + "search" + ], + "licenses": [{ + "type": "MIT", + "url": "http://github.com/mscdex/streamsearch/raw/master/LICENSE" + }], + "repository": { + "type": "git", + "url": "http://github.com/mscdex/streamsearch.git" + } +} diff --git a/node_modules/streamsearch/test/test.js b/node_modules/streamsearch/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..39a04d7f834bea5e8da37c4cf56973a7b3217dd5 --- /dev/null +++ b/node_modules/streamsearch/test/test.js @@ -0,0 +1,70 @@ +'use strict'; + +const assert = require('assert'); + +const StreamSearch = require('../lib/sbmh.js'); + +[ + { + needle: '\r\n', + chunks: [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ], + expect: [ + [false, 'foo'], + [false, ' bar'], + [ true, null], + [false, 'baz, hello'], + [ true, null], + [false, ' world.'], + [ true, null], + [ true, ' Node.JS rules!!'], + [ true, ''], + ], + }, + { + needle: '---foobarbaz', + chunks: [ + '---foobarbaz', + 'asdf', + '\r\n', + '---foobarba', + '---foobar', + 'ba', + '\r\n---foobarbaz--\r\n', + ], + expect: [ + [ true, null], + [false, 'asdf'], + [false, '\r\n'], + [false, '---foobarba'], + [false, '---foobarba'], + [ true, '\r\n'], + [false, '--\r\n'], + ], + }, +].forEach((test, i) => { + console.log(`Running test #${i + 1}`); + const { needle, chunks, expect } = test; + + const results = []; + const ss = new StreamSearch(Buffer.from(needle), + (isMatch, data, start, end) => { + if (data) + data = data.toString('latin1', start, end); + else + data = null; + results.push([isMatch, data]); + }); + + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + assert.deepStrictEqual(results, expect); +}); diff --git a/node_modules/streamx/LICENSE b/node_modules/streamx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c728dc70b96897b4f56c18d41e2965a547f67cfc --- /dev/null +++ b/node_modules/streamx/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/streamx/README.md b/node_modules/streamx/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3ce4305db62bb7f696a580a09a11c55ac230784a --- /dev/null +++ b/node_modules/streamx/README.md @@ -0,0 +1,550 @@ +# streamx + +An iteration of the Node.js core streams with a series of improvements. + +``` +npm install streamx +``` + +[![Build Status](https://github.com/streamxorg/streamx/workflows/Build%20Status/badge.svg)](https://github.com/streamxorg/streamx/actions?query=workflow%3A%22Build+Status%22) + +## Main improvements from Node.js core stream + +#### Proper lifecycle support. + +Streams have an `_open` function that is called before any read/write operation and a `_destroy` +function that is always run as the last part of the stream. + +This makes it easy to maintain state. + +#### Easy error handling + +Fully integrates a `.destroy()` function. When called the stream will wait for any +pending operation to finish and call the stream destroy logic. + +Close is _always_ the last event emitted and `destroy` is always run. + +#### `pipe()` error handles + +`pipe` accepts a callback that is called when the pipeline is fully drained. +It also error handles the streams provided and destroys both streams if either +of them fail. + +#### All streams are both binary and object mode streams + +A `map` function can be provided to map your input data into buffers +or other formats. To indicate how much buffer space each data item takes +an `byteLength` function can be provided as well. + +This removes the need for two modes of streams. + +#### Simplicity + +This is a full rewrite, all contained in one file. + +Lots of stream methods are simplified based on how I and devs I work with actually use streams in the wild. + +#### Backwards compat + +streamx aims to be compatible with Node.js streams whenever it is reasonable to do so. + +This means that streamx streams behave a lot like Node.js streams from the outside but still provides the +improvements above. + +#### Smaller browser footprint + +streamx has a much smaller footprint when compiled for the browser: + +``` +$ for x in stream{,x}; do echo $x: $(browserify -r $x | wc -c) bytes; done +stream: 173844 bytes +streamx: 46943 bytes +``` + +With optimizations turned on, the difference is even more stark: + +``` +$ for x in stream{,x}; do echo $x: $(browserify -r $x -p tinyify | wc -c) bytes; done +stream: 62649 bytes +streamx: 8460 bytes +$ for x in stream{,x}; do echo $x: $(browserify -r $x -p tinyify | gzip | wc -c) "bytes (gzipped)"; done +stream: 18053 bytes (gzipped) +streamx: 2806 bytes (gzipped) +``` + +#### AbortSignal support + +To make it easier to integrate streams in a `async/await` flow, all streams support a `signal` option +that accepts a [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to as an +alternative means to `.destroy` streams. + +## Usage + +```js +const { Readable } = require('streamx') + +const rs = new Readable({ + read(cb) { + this.push('Cool data') + cb(null) + } +}) + +rs.on('data', (data) => console.log('data:', data)) +``` + +## API + +This streamx package contains 4 streams similar to Node.js core. + +## Readable Stream + +#### `rs = new stream.Readable([options])` + +Create a new readable stream. + +Options include: + +``` +{ + highWaterMark: 16384, // max buffer size in bytes + map: (data) => data, // optional function to map input data + byteLength: (data) => size, // optional function that calculates the byte size of input data + signal: abortController.signal, // optional AbortSignal that triggers `.destroy` when on `abort` + eagerOpen: false // eagerly open the stream +} +``` + +In addition you can pass the `open`, `read`, and `destroy` functions as shorthands in +the constructor instead of overwrite the methods below. + +The default byteLength function returns the byte length of buffers and `1024` +for any other object. This means the buffer will contain around 16 non buffers +or buffers worth 16kb when full if the defaults are used. + +If you set highWaterMark to `0` then all read ahead buffering on the stream +is disabled and it will only call `_read` when a user reads rather than ahead of time. + +#### `rs._read(cb)` + +This function is called when the stream wants you to push new data. +Overwrite this and add your own read logic. +You should call the callback when you are fully done with the read. + +Can also be set using `options.read` in the constructor. + +Note that this function differs from Node.js streams in that it takes +the "read finished" callback. + +#### `drained = rs.push(data)` + +Push new data to the stream. Returns true if the buffer is not full +and you should push more data if you can. + +If you call `rs.push(null)` you signal to the stream that no more +data will be pushed and that you want to end the stream. + +#### `data = rs.read()` + +Read a piece of data from the stream buffer. If the buffer is currently empty +`null` will be returned and you should wait for `readable` to be emitted before +trying again. If the stream has been ended it will also return `null`. + +Note that this method differs from Node.js streams in that it does not accept +an optional amounts of bytes to consume. + +#### `rs.unshift(data)` + +Add a piece of data to the front of the buffer. Use this if you read too much +data using the `rs.read()` function. + +#### `rs._open(cb)` + +This function is called once before the first read is issued. Use this function +to implement your own open logic. + +Can also be set using `options.open` in the constructor. + +#### `rs._destroy(cb)` + +This function is called just before the stream is fully destroyed. You should +use this to implement whatever teardown logic you need. The final part of the +stream life cycle is always to call destroy itself so this function will always +be called whether or not the stream ends gracefully or forcefully. + +Can also be set using `options.destroy` in the constructor. + +Note that the `_destroy` might be called without the open function being called +in case no read was ever performed on the stream. + +#### `rs._predestroy()` + +A simple hook that is called as soon as the first `stream.destroy()` call is invoked. + +Use this in case you need to cancel pending reads (if possible) instead of waiting for them to finish. + +Can also be set using `options.predestroy` in the constructor. + +#### `rs.destroy([error])` + +Forcefully destroy the stream. Will call `_destroy` as soon as all pending reads have finished. +Once the stream is fully destroyed `close` will be emitted. + +If you pass an error this error will be emitted just before `close` is, signifying a reason +as to why this stream was destroyed. + +#### `rs.pause()` + +Pauses the stream. You will only need to call this if you want to pause a resumed stream. + +Returns this stream instance. + +#### `rs.resume()` + +Will start reading data from the stream as fast as possible. + +If you do not call this, you need to use the `read()` method to read data or the `pipe()` method to +pipe the stream somewhere else or the `data` handler. + +If none of these option are used the stream will stay paused. + +Returns this stream instance. + +#### `rs.setEncoding(encoding)` + +Set an encoding to change how data is interpreted. E.g. `utf-8`. + +#### `bool = Readable.isPaused(rs)` + +Returns `true` if the stream is paused, else `false`. + +#### `writableStream = rs.pipe(writableStream, [callback])` + +Efficently pipe the readable stream to a writable stream (can be Node.js core stream or a stream from this package). +If you provide a callback the callback is called when the pipeline has fully finished with an optional error in case +it failed. + +To cancel the pipeline destroy either of the streams. + +#### `rs.on('readable')` + +Emitted when data is pushed to the stream if the buffer was previously empty. + +#### `rs.on('data', data)` + +Emitted when data is being read from the stream. If you attach a data handler you are implicitly resuming the stream. + +#### `rs.on('end')` + +Emitted when the readable stream has ended and no data is left in it's buffer. + +#### `rs.on('close')` + +Emitted when the readable stream has fully closed (i.e. it's destroy function has completed) + +#### `rs.on('error', err)` + +Emitted if any of the stream operations fail with an error. `close` is always emitted right after this. + +#### `rs.on('piping', dest)` + +Emitted when the readable stream is pipeing to a destination. + +#### `rs.on('open')` + +Emitted after `rs._open(cb)` execution. + +#### `rs.destroying` + +Boolean property indicating whether or not this stream has started to be destroyed. + +#### `rs.destroyed` + +Boolean property indicating whether or not this stream has been destroyed. + +#### `rs.readable` + +Returns `true` if the stream is an active streamx readable stream. Returns `undefined` if not. + +#### `bool = Readable.isBackpressured(rs)` + +Static method to check if a readable stream is currently under backpressure. + +#### `stream = Readable.from(arrayOrBufferOrStringOrAsyncIterator)` + +Static method to turn an array or buffer or string or AsyncIterator into a readable stream. + +## Writable Stream + +#### `ws = new stream.Writable([options])` + +Create a new writable stream. + +Options include: + +``` +{ + highWaterMark: 16384, // max buffer size in bytes + map: (data) => data, // optional function to map input data + byteLength: (data) => size, // optional function that calculates the byte size of input data + signal: abortController.signal // optional AbortSignal that triggers `.destroy` when on `abort` +} +``` + +In addition you can pass the `open`, `write`, `final`, and `destroy` functions as shorthands in +the constructor instead of overwrite the methods below. + +The default byteLength function returns the byte length of buffers and `1024` +for any other object. This means the buffer will contain around 16 non buffers +or buffers worth 16kb when full if the defaults are used. + +#### `ws._open(cb)` + +This function is called once before the first write is issued. Use this function +to implement your own open logic. + +Can also be set using `options.open` in the constructor. + +#### `ws._destroy(cb)` + +This function is called just before the stream is fully destroyed. You should +use this to implement whatever teardown logic you need. The final part of the +stream life cycle is always to call destroy itself so this function will always +be called whether or not the stream ends gracefully or forcefully. + +Can also be set using `options.destroy` in the constructor. + +Note that the `_destroy` might be called without the open function being called +in case no write was ever performed on the stream. + +#### `ws._predestroy()` + +A simple hook that is called as soon as the first `stream.destroy()` call is invoked. + +Use this in case you need to cancel pending writes (if possible) instead of waiting for them to finish. + +Can also be set using `options.predestroy` in the constructor. + +#### `ws.destroy([error])` + +Forcefully destroy the stream. Will call `_destroy` as soon as all pending reads have finished. +Once the stream is fully destroyed `close` will be emitted. + +If you pass an error this error will be emitted just before `close` is, signifying a reason +as to why this stream was destroyed. + +#### `drained = ws.write(data)` + +Write a piece of data to the stream. Returns `true` if the stream buffer is not full and you +should keep writing to it if you can. If `false` is returned the stream will emit `drain` +once it's buffer is fully drained. + +#### `ws._write(data, callback)` + +This function is called when the stream want to write some data. Use this to implement your own +write logic. When done call the callback and the stream will call it again if more data exists in the buffer. + +Can also be set using `options.write` in the constructor. + +#### `ws._writev(batch, callback)` + +Similar to `_write` but passes an array of all data in the current write buffer instead of the oldest one. +Useful if the destination you are writing the data to supports batching. + +Can also be set using `options.writev` in the constructor. + +#### `ws.end()` + +Gracefully end the writable stream. Call this when you no longer want to write to the stream. + +Once all writes have been fully drained `finish` will be emitted. + +Returns this stream instance. + +#### `ws.cork()` + +Buffer written data in memory. Useful for accumulating small chunks of data into a batch to be consumed by `writev`. + +#### `ws.uncork()` + +Disable `ws.cork()`. + +#### `ws._final(callback)` + +This function is called just before `finish` is emitted, i.e. when all writes have flushed but `ws.end()` +have been called. Use this to implement any logic that should happen after all writes but before finish. + +Can also be set using `options.final` in the constructor. + +#### `ws.on('finish')` + +Emitted when the stream has been ended and all writes have been drained. + +#### `ws.on('close')` + +Emitted when the readable stream has fully closed (i.e. it's destroy function has completed) + +#### `ws.on('error', err)` + +Emitted if any of the stream operations fail with an error. `close` is always emitted right after this. + +#### `ws.on('pipe', src)` + +Emitted when a readable stream is being piped to the writable one. + +#### `ws.on('open')` + +Emitted after `ws._open(cb)` execution. + +#### `ws.on('drain')` + +Emitted after all data was drained if `ws.write(data)` returned `false`. + +#### `ws.destroying` + +Boolean property indicating whether or not this stream has started to be destroyed. + +#### `ws.destroyed` + +Boolean property indicating whether or not this stream has been destroyed. + +#### `ws.writable` + +Returns `true` if the stream is an active streamx writable stream. Returns `undefined` if not. + +#### `bool = Writable.isBackpressured(ws)` + +Static method to check if a writable stream is currently under backpressure. + +#### `bool = await Writable.drained(ws)` + +Static helper to wait for a stream to drain the currently queued writes. +Returns true if they were drained and false otherwise if the stream was destroyed. + +## Duplex Stream + +#### `s = new stream.Duplex([options])` + +A duplex stream is a stream that is both readable and writable. + +Since JS does not support multiple inheritance it inherits directly from Readable +but implements the Writable API as well. + +If you want to provide only a map function for the readable side use `mapReadable` instead. +If you want to provide only a byteLength function for the readable side use `byteLengthReadable` instead. + +Same goes for the writable side but using `mapWritable` and `byteLengthWritable` instead. + +## Transform Stream + +A Transform stream is a duplex stream with an `._transform` template method that allows to +asynchronously map the input to a different output. + +The transform stream overrides the `_write` and `_read` operations of `Readable` and `Writable` but +still allows the setting of these options in the constructor. Usually it is unnecessary to pass +in `read` or `write`/`writev` or to override the corresponding `._read`, `._write` or `._writev` operation. + +#### `ts = new stream.Transform([options])` + +A transform stream is a duplex stream that maps the data written to it and emits that as readable data. + +Has the same options as a duplex stream except you can provide a `transform` function also. + +#### `ts._transform(data, callback)` + +Transform the incoming data. Call `callback(null, mappedData)` or use `ts.push(mappedData)` to +return data to the readable side of the stream. + +Per default the transform function just remits the incoming data making it act as a pass-through stream. + +## Pipeline + +`pipeline` allows to stream form a readable through a set of duplex streams to a writable entry. + +```js +const { pipeline, Readable, Transform, Writable } = require('streamx') +const lastStream = pipeline( + Readable.from([1, 2, 3]), + new Transform({ + transform (from, cb) { + this.push(from.toString()) + cb() + } + }), + new Writable({ + write (data, cb) { + console.log(data) + cb() + } + }) + error => { + // Callback once write has finished + } +) +``` + +#### `lastStream = stream.pipeline(...streams, [done])` + +Pipe all streams together and return the last stream piped to. +When the last stream finishes the pipeline ended succesfully. + +If any of the streams error, whether they are Node.js core streams +or streamx streams, all streams in the pipeline are shutdown. + +Optionally you can pass a done callback to know when the pipeline is done. + +#### `promise = stream.pipelinePromise(...streams)` + +Same as normal pipeline except instead of returning the last stream it returns +a promise representing the done callback. Note you should error handle this +promise if you use this version. + +## Helpers + +#### `bool = isStream(stream)` + +#### `bool = isStreamx(stream)` + +#### `bool = isDisturbed(stream)` + +Indicates if the stream has been opened or started to be destroyed. + +#### `bool = isEnding(stream)` + +Indicates if a readable stream has started it's ending process. + +#### `bool = isEnded(stream)` + +Indicates if a readable stream ended, so all it's readings. + +#### `bool = isFinishing(stream)` + +Indicates if a writable stream has started it's ending process. + +#### `bool = isFinished(stream)` + +Indicates if a writable stream ended, so all it's writings. + +#### `err = getStreamError(stream, [options])` + +Returns `null` if the stream has no errors. + +## Utilities + +Streamx aims to be minimal and stable. It therefore only contains a minimal set of utilities. +To help discover of other modules that help you build streamx apps, we link some useful utilities here + +- [stream-composer](https://github.com/mafintosh/stream-composer) - Compose streams like Node's `stream.compose` and the `duplexify` and `pumpify` modules. +- [teex](https://github.com/mafintosh/teex) - Clone a readable stream into multiple new readable instances. +- [merge-readable](https://github.com/holepunchto/merge-readable) - Merge multiple readers into a new readable with optional mapping of data + +## Contributing + +If you want to help contribute to streamx a good way to start is to help writing more test +cases, compatibility tests, documentation, or performance benchmarks. + +If in doubt open an issue :) + +## License + +MIT diff --git a/node_modules/streamx/index.d.ts b/node_modules/streamx/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7856f0ca2273a2a71ffd6fba21048468505b7055 --- /dev/null +++ b/node_modules/streamx/index.d.ts @@ -0,0 +1,198 @@ +import { BufferEncoding, EventMap, EventEmitter } from './runtime' + +interface StreamCallback { + (err: Error | null): void +} + +type Pipeline = [src: Readable, ...transforms: Duplex[], dest: S] + +declare function pipeline(streams: Pipeline, cb?: StreamCallback): S +declare function pipeline(...args: Pipeline): S +declare function pipeline(...args: [...Pipeline, cb: StreamCallback]): S + +declare function pipelinePromise(...args: Pipeline): Promise + +declare function isStream(stream: Stream): stream is Stream +declare function isStreamx(stream: Stream): boolean +declare function isEnding(stream: Stream): boolean +declare function isEnded(stream: Stream): boolean +declare function isFinishing(stream: Stream): boolean +declare function isFinished(stream: Stream): boolean +declare function isDisturbed(stream: Stream): boolean + +interface GetStreamErrorOptions { + all?: boolean +} + +declare function getStreamError(stream: Stream, opts?: GetStreamErrorOptions): Error | null + +interface StreamEvents extends EventMap { + close: [] + error: [err: Error] +} + +interface StreamOptions { + byteLength?(data: unknown): number + destroy?(this: S, cb: StreamCallback): void + eagerOpen?: boolean + highWaterMark?: number + map?(data: unknown): unknown + open?(this: S, cb: StreamCallback): void + predestroy?(this: S): void + signal?: AbortSignal +} + +interface Stream extends EventEmitter { + _open(cb: StreamCallback): void + _predestroy(): void + _destroy(cb: StreamCallback): void + + readonly readable: boolean + readonly writable: boolean + readonly destroyed: boolean + readonly destroying: boolean + + destroy(err?: Error | null): void +} + +declare class Stream { + constructor(opts?: StreamOptions) +} + +interface WritableEvents extends StreamEvents { + drain: [] + finish: [] + pipe: [src: Readable] +} + +interface WritableOptions extends StreamOptions { + byteLengthWritable?(data: unknown): number + final?(this: S, cb: StreamCallback): void + mapWritable?(data: unknown): unknown + write?(this: S, data: unknown, cb: StreamCallback): void + writev?(this: S, batch: unknown[], cb: StreamCallback): void +} + +interface Writable extends Stream { + _write(data: unknown, cb: StreamCallback): void + _writev(batch: unknown[], cb: StreamCallback): void + _final(cb: StreamCallback): void + + write(data: unknown): unknown + + end(data: unknown): this + + cork(): void + uncork(): void +} + +declare class Writable extends Stream { + constructor(opts?: WritableOptions) + + static isBackpressured(ws: Writable): boolean + + static drained(ws: Writable): Promise +} + +interface ReadableEvents extends StreamEvents { + data: [data: unknown] + end: [] + piping: [dest: Writable] + readable: [] +} + +interface ReadableOptions extends StreamOptions { + byteLengthReadable?(data: unknown): number + encoding?: BufferEncoding + mapReadable?(data: unknown): unknown + read?(this: S, cb: StreamCallback): void +} + +interface Readable + extends Stream, AsyncIterable { + _read(cb: StreamCallback): void + + push(data: unknown | null): boolean + unshift(data: unknown | null): void + read(): unknown | null + + resume(): this + pause(): this + + pipe(dest: S, cb?: StreamCallback): S + + setEncoding(encoding: BufferEncoding): this +} + +declare class Readable extends Stream { + constructor(opts?: ReadableOptions) + + static deferred(fn: () => Promise, opts?: TransformOptions): Transform + + static from(data: unknown | unknown[] | AsyncIterable, opts?: ReadableOptions): Readable + + static isBackpressured(rs: Readable): boolean + + static isPaused(rs: Readable): boolean +} + +interface DuplexEvents extends ReadableEvents, WritableEvents {} + +interface DuplexOptions extends ReadableOptions, WritableOptions {} + +interface Duplex extends Readable, Writable {} + +declare class Duplex extends Stream { + constructor(opts?: DuplexOptions) +} + +interface TransformCallback { + (err: Error | null, mappedData: unknown): void +} + +interface TransformEvents extends DuplexEvents {} + +interface TransformOptions extends DuplexOptions { + flush?(this: S, cb: StreamCallback): void + transform?(this: S, data: unknown, cb: TransformCallback): void +} + +interface Transform extends Duplex { + _flush(cb: StreamCallback): void + _transform(Data: unknown, cb: TransformCallback): void +} + +declare class Transform extends Duplex { + constructor(opts?: TransformOptions) +} + +export { + type Pipeline, + pipeline, + pipelinePromise, + isStream, + isStreamx, + isEnding, + isEnded, + isFinishing, + isFinished, + isDisturbed, + type GetStreamErrorOptions, + getStreamError, + type StreamEvents, + type StreamOptions, + Stream, + type WritableEvents, + type WritableOptions, + Writable, + type ReadableEvents, + type ReadableOptions, + Readable, + type DuplexEvents, + type DuplexOptions, + Duplex, + type TransformEvents, + type TransformOptions, + Transform, + Transform as PassThrough +} diff --git a/node_modules/streamx/index.js b/node_modules/streamx/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6b1b03e686064c62bf0e659b889efe2524bff099 --- /dev/null +++ b/node_modules/streamx/index.js @@ -0,0 +1,1314 @@ +const { EventEmitter } = require('events-universal') +const FIFO = require('fast-fifo') +const TextDecoder = require('text-decoder') + +const StreamError = require('./lib/errors.js') + +// if we do a future major, expect queue microtask to be there always, for now a bit defensive +const qmt = + typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask + +// 29 bits used total (4 from shared, 14 from read, and 11 from write) +const MAX = (1 << 29) - 1 + +// Shared state +const OPENING = 0b0001 +const PREDESTROYING = 0b0010 +const DESTROYING = 0b0100 +const DESTROYED = 0b1000 + +const NOT_OPENING = MAX ^ OPENING +const NOT_PREDESTROYING = MAX ^ PREDESTROYING + +// Read state (4 bit offset from shared state) +const READ_ACTIVE = 0b00000000000001 << 4 +const READ_UPDATING = 0b00000000000010 << 4 +const READ_PRIMARY = 0b00000000000100 << 4 +const READ_QUEUED = 0b00000000001000 << 4 +const READ_RESUMED = 0b00000000010000 << 4 +const READ_PIPE_DRAINED = 0b00000000100000 << 4 +const READ_ENDING = 0b00000001000000 << 4 +const READ_EMIT_DATA = 0b00000010000000 << 4 +const READ_EMIT_READABLE = 0b00000100000000 << 4 +const READ_EMITTED_READABLE = 0b00001000000000 << 4 +const READ_DONE = 0b00010000000000 << 4 +const READ_NEXT_TICK = 0b00100000000000 << 4 +const READ_NEEDS_PUSH = 0b01000000000000 << 4 +const READ_READ_AHEAD = 0b10000000000000 << 4 + +// Combined read state +const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED +const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH +const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE +const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED +const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD + +const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE +const READ_NON_PRIMARY = MAX ^ READ_PRIMARY +const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH) +const READ_PUSHED = MAX ^ READ_NEEDS_PUSH +const READ_PAUSED = MAX ^ READ_RESUMED +const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE) +const READ_NOT_ENDING = MAX ^ READ_ENDING +const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING +const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK +const READ_NOT_UPDATING = MAX ^ READ_UPDATING +const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD +const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD + +// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state) +const WRITE_ACTIVE = 0b00000000001 << 18 +const WRITE_UPDATING = 0b00000000010 << 18 +const WRITE_PRIMARY = 0b00000000100 << 18 +const WRITE_QUEUED = 0b00000001000 << 18 +const WRITE_UNDRAINED = 0b00000010000 << 18 +const WRITE_DONE = 0b00000100000 << 18 +const WRITE_EMIT_DRAIN = 0b00001000000 << 18 +const WRITE_NEXT_TICK = 0b00010000000 << 18 +const WRITE_WRITING = 0b00100000000 << 18 +const WRITE_FINISHING = 0b01000000000 << 18 +const WRITE_CORKED = 0b10000000000 << 18 + +const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING) +const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY +const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING) +const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED +const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED +const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK +const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING +const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED + +// Combined shared state +const ACTIVE = READ_ACTIVE | WRITE_ACTIVE +const NOT_ACTIVE = MAX ^ ACTIVE +const DONE = READ_DONE | WRITE_DONE +const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING +const OPEN_STATUS = DESTROY_STATUS | OPENING +const AUTO_DESTROY = DESTROY_STATUS | DONE +const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY +const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK +const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE +const IS_OPENING = OPEN_STATUS | TICKING + +// Combined shared state and read state +const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE +const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED +const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED +const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE +const SHOULD_NOT_READ = + OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD +const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE +const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY +const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING + +// Combined write state +const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE +const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED +const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE +const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE +const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED +const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE +const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING +const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE +const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE +const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY +const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS + +const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator') + +class WritableState { + constructor( + stream, + { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {} + ) { + this.stream = stream + this.queue = new FIFO() + this.highWaterMark = highWaterMark + this.buffered = 0 + this.error = null + this.pipeline = null + this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr + this.byteLength = byteLengthWritable || byteLength || defaultByteLength + this.map = mapWritable || map + this.afterWrite = afterWrite.bind(this) + this.afterUpdateNextTick = updateWriteNT.bind(this) + } + + get ending() { + return (this.stream._duplexState & WRITE_FINISHING) !== 0 + } + + get ended() { + return (this.stream._duplexState & WRITE_DONE) !== 0 + } + + push(data) { + if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false + if (this.map !== null) data = this.map(data) + + this.buffered += this.byteLength(data) + this.queue.push(data) + + if (this.buffered < this.highWaterMark) { + this.stream._duplexState |= WRITE_QUEUED + return true + } + + this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED + return false + } + + shift() { + const data = this.queue.shift() + + this.buffered -= this.byteLength(data) + if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED + + return data + } + + end(data) { + if (typeof data === 'function') { + this.stream.once('finish', data) + } else if (data !== undefined && data !== null) { + this.push(data) + } + + this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY + } + + autoBatch(data, cb) { + const buffer = [] + const stream = this.stream + + buffer.push(data) + while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { + buffer.push(stream._writableState.shift()) + } + + if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null) + stream._writev(buffer, cb) + } + + update() { + const stream = this.stream + + stream._duplexState |= WRITE_UPDATING + + do { + while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) { + const data = this.shift() + stream._duplexState |= WRITE_ACTIVE_AND_WRITING + stream._write(data, this.afterWrite) + } + + if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary() + } while (this.continueUpdate() === true) + + stream._duplexState &= WRITE_NOT_UPDATING + } + + updateNonPrimary() { + const stream = this.stream + + if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { + stream._duplexState = stream._duplexState | WRITE_ACTIVE + stream._final(afterFinal.bind(this)) + return + } + + if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { + stream._duplexState |= ACTIVE + stream._destroy(afterDestroy.bind(this)) + } + return + } + + if ((stream._duplexState & IS_OPENING) === OPENING) { + stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING + stream._open(afterOpen.bind(this)) + } + } + + continueUpdate() { + if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false + this.stream._duplexState &= WRITE_NOT_NEXT_TICK + return true + } + + updateCallback() { + if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) { + this.update() + } else { + this.updateNextTick() + } + } + + updateNextTick() { + if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return + this.stream._duplexState |= WRITE_NEXT_TICK + if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick) + } +} + +class ReadableState { + constructor( + stream, + { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {} + ) { + this.stream = stream + this.queue = new FIFO() + this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark + this.buffered = 0 + this.readAhead = highWaterMark > 0 + this.error = null + this.pipeline = null + this.byteLength = byteLengthReadable || byteLength || defaultByteLength + this.map = mapReadable || map + this.pipeTo = null + this.afterRead = afterRead.bind(this) + this.afterUpdateNextTick = updateReadNT.bind(this) + } + + get ending() { + return (this.stream._duplexState & READ_ENDING) !== 0 + } + + get ended() { + return (this.stream._duplexState & READ_DONE) !== 0 + } + + pipe(pipeTo, cb) { + if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination') + if (typeof cb !== 'function') cb = null + + this.stream._duplexState |= READ_PIPE_DRAINED + this.pipeTo = pipeTo + this.pipeline = new Pipeline(this.stream, pipeTo, cb) + + if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes + + if (isStreamx(pipeTo)) { + pipeTo._writableState.pipeline = this.pipeline + if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes + pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself + } else { + const onerror = this.pipeline.done.bind(this.pipeline, pipeTo) + const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg + pipeTo.on('error', onerror) + pipeTo.on('close', onclose) + pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) + } + + pipeTo.on('drain', afterDrain.bind(this)) + this.stream.emit('piping', pipeTo) + pipeTo.emit('pipe', this.stream) + } + + push(data) { + const stream = this.stream + + if (data === null) { + this.highWaterMark = 0 + stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED + return false + } + + if (this.map !== null) { + data = this.map(data) + if (data === null) { + stream._duplexState &= READ_PUSHED + return this.buffered < this.highWaterMark + } + } + + this.buffered += this.byteLength(data) + this.queue.push(data) + + stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED + + return this.buffered < this.highWaterMark + } + + shift() { + const data = this.queue.shift() + + this.buffered -= this.byteLength(data) + if (this.buffered === 0) { + this.stream._duplexState &= READ_NOT_QUEUED + } + + return data + } + + unshift(data) { + const pending = [this.map !== null ? this.map(data) : data] + while (this.buffered > 0) pending.push(this.shift()) + + for (let i = 0; i < pending.length - 1; i++) { + const data = pending[i] + this.buffered += this.byteLength(data) + this.queue.push(data) + } + + this.push(pending[pending.length - 1]) + } + + read() { + const stream = this.stream + + if ((stream._duplexState & READ_STATUS) === READ_QUEUED) { + const data = this.shift() + + if (this.pipeTo !== null && this.pipeTo.write(data) === false) { + stream._duplexState &= READ_PIPE_NOT_DRAINED + } + + if ((stream._duplexState & READ_EMIT_DATA) !== 0) { + stream.emit('data', data) + } + + return data + } + + if (this.readAhead === false) { + stream._duplexState |= READ_READ_AHEAD + this.updateNextTick() + } + + return null + } + + drain() { + const stream = this.stream + + while ( + (stream._duplexState & READ_STATUS) === READ_QUEUED && + (stream._duplexState & READ_FLOWING) !== 0 + ) { + const data = this.shift() + + if (this.pipeTo !== null && this.pipeTo.write(data) === false) { + stream._duplexState &= READ_PIPE_NOT_DRAINED + } + + if ((stream._duplexState & READ_EMIT_DATA) !== 0) { + stream.emit('data', data) + } + } + } + + update() { + const stream = this.stream + + stream._duplexState |= READ_UPDATING + + do { + this.drain() + + while ( + this.buffered < this.highWaterMark && + (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD + ) { + stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH + stream._read(this.afterRead) + this.drain() + } + + if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { + stream._duplexState |= READ_EMITTED_READABLE + stream.emit('readable') + } + + if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) { + this.updateNonPrimary() + } + } while (this.continueUpdate() === true) + + stream._duplexState &= READ_NOT_UPDATING + } + + updateNonPrimary() { + const stream = this.stream + + if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) { + stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING + stream.emit('end') + + if ((stream._duplexState & AUTO_DESTROY) === DONE) { + stream._duplexState |= DESTROYING + } + + if (this.pipeTo !== null) { + this.pipeTo.end() + } + } + + if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { + stream._duplexState |= ACTIVE + stream._destroy(afterDestroy.bind(this)) + } + return + } + + if ((stream._duplexState & IS_OPENING) === OPENING) { + stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING + stream._open(afterOpen.bind(this)) + } + } + + continueUpdate() { + if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false + this.stream._duplexState &= READ_NOT_NEXT_TICK + return true + } + + updateCallback() { + if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) { + this.update() + } else { + this.updateNextTick() + } + } + + updateNextTickIfOpen() { + if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return + this.stream._duplexState |= READ_NEXT_TICK + if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick) + } + + updateNextTick() { + if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return + this.stream._duplexState |= READ_NEXT_TICK + if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick) + } +} + +class TransformState { + constructor(stream) { + this.data = null + this.afterTransform = afterTransform.bind(stream) + this.afterFinal = null + } +} + +class Pipeline { + constructor(src, dst, cb) { + this.from = src + this.to = dst + this.afterPipe = cb + this.error = null + this.pipeToFinished = false + } + + finished() { + this.pipeToFinished = true + } + + done(stream, err) { + if (err) this.error = err + + if (stream === this.to) { + this.to = null + + if (this.from !== null) { + if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { + this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed')) + } + return + } + } + + if (stream === this.from) { + this.from = null + + if (this.to !== null) { + if ((stream._duplexState & READ_DONE) === 0) { + this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed')) + } + return + } + } + + if (this.afterPipe !== null) this.afterPipe(this.error) + this.to = this.from = this.afterPipe = null + } +} + +function afterDrain() { + this.stream._duplexState |= READ_PIPE_DRAINED + this.updateCallback() +} + +function afterFinal(err) { + const stream = this.stream + if (err) stream.destroy(err) + + if ((stream._duplexState & DESTROY_STATUS) === 0) { + stream._duplexState |= WRITE_DONE + stream.emit('finish') + } + + if ((stream._duplexState & AUTO_DESTROY) === DONE) { + stream._duplexState |= DESTROYING + } + + stream._duplexState &= WRITE_NOT_FINISHING + + // no need to wait the extra tick here, so we short circuit that + if ((stream._duplexState & WRITE_UPDATING) === 0) { + this.update() + } else { + this.updateNextTick() + } +} + +function afterDestroy(err) { + const stream = this.stream + + if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error + if (err) stream.emit('error', err) + + stream._duplexState |= DESTROYED + stream.emit('close') + + const rs = stream._readableState + const ws = stream._writableState + + if (rs !== null && rs.pipeline !== null) { + rs.pipeline.done(stream, err) + } + + if (ws !== null) { + while (ws.drains !== null && ws.drains.length > 0) { + ws.drains.shift().resolve(false) + } + + if (ws.pipeline !== null) { + ws.pipeline.done(stream, err) + } + } +} + +function afterWrite(err) { + const stream = this.stream + + if (err) stream.destroy(err) + stream._duplexState &= WRITE_NOT_ACTIVE + + if (this.drains !== null) tickDrains(this.drains) + + if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { + stream._duplexState &= WRITE_DRAINED + + if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { + stream.emit('drain') + } + } + + this.updateCallback() +} + +function afterRead(err) { + if (err) this.stream.destroy(err) + this.stream._duplexState &= READ_NOT_ACTIVE + + if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) { + this.stream._duplexState &= READ_NO_READ_AHEAD + } + + this.updateCallback() +} + +function updateReadNT() { + if ((this.stream._duplexState & READ_UPDATING) === 0) { + this.stream._duplexState &= READ_NOT_NEXT_TICK + this.update() + } +} + +function updateWriteNT() { + if ((this.stream._duplexState & WRITE_UPDATING) === 0) { + this.stream._duplexState &= WRITE_NOT_NEXT_TICK + this.update() + } +} + +function tickDrains(drains) { + for (let i = 0; i < drains.length; i++) { + // drains.writes are monotonic, so if one is 0 its always the first one + if (--drains[i].writes === 0) { + drains.shift().resolve(true) + i-- + } + } +} + +function afterOpen(err) { + const stream = this.stream + + if (err) stream.destroy(err) + + if ((stream._duplexState & DESTROYING) === 0) { + if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) { + stream._duplexState |= READ_PRIMARY + } + + if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) { + stream._duplexState |= WRITE_PRIMARY + } + + stream.emit('open') + } + + stream._duplexState &= NOT_ACTIVE + + if (stream._writableState !== null) { + stream._writableState.updateCallback() + } + + if (stream._readableState !== null) { + stream._readableState.updateCallback() + } +} + +function afterTransform(err, data) { + if (data !== undefined && data !== null) this.push(data) + this._writableState.afterWrite(err) +} + +function newListener(name) { + if (this._readableState !== null) { + if (name === 'data') { + this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD + this._readableState.updateNextTick() + } + if (name === 'readable') { + this._duplexState |= READ_EMIT_READABLE + this._readableState.updateNextTick() + } + } + + if (this._writableState !== null) { + if (name === 'drain') { + this._duplexState |= WRITE_EMIT_DRAIN + this._writableState.updateNextTick() + } + } +} + +class Stream extends EventEmitter { + constructor(opts) { + super() + + this._duplexState = 0 + this._readableState = null + this._writableState = null + + if (opts) { + if (opts.open) this._open = opts.open + if (opts.destroy) this._destroy = opts.destroy + if (opts.predestroy) this._predestroy = opts.predestroy + if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this)) + } + + this.on('newListener', newListener) + } + + _open(cb) { + cb(null) + } + + _destroy(cb) { + cb(null) + } + + _predestroy() { + // does nothing + } + + get readable() { + return this._readableState !== null ? true : undefined + } + + get writable() { + return this._writableState !== null ? true : undefined + } + + get destroyed() { + return (this._duplexState & DESTROYED) !== 0 + } + + get destroying() { + return (this._duplexState & DESTROY_STATUS) !== 0 + } + + destroy(err) { + if ((this._duplexState & DESTROY_STATUS) === 0) { + if (!err) err = StreamError.STREAM_DESTROYED() + this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY + + if (this._readableState !== null) { + this._readableState.highWaterMark = 0 + this._readableState.error = err + } + + if (this._writableState !== null) { + this._writableState.highWaterMark = 0 + this._writableState.error = err + } + + this._duplexState |= PREDESTROYING + this._predestroy() + this._duplexState &= NOT_PREDESTROYING + + if (this._readableState !== null) { + this._readableState.updateNextTick() + } + + if (this._writableState !== null) { + this._writableState.updateNextTick() + } + } + } +} + +class Readable extends Stream { + constructor(opts) { + super(opts) + + this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD + this._readableState = new ReadableState(this, opts) + + if (opts) { + if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD + if (opts.read) this._read = opts.read + if (opts.eagerOpen) this._readableState.updateNextTick() + if (opts.encoding) this.setEncoding(opts.encoding) + } + } + + static deferred(fn, opts) { + const out = new PassThrough(opts) + + fn() + .then((src) => { + if (src === null) return out.end() + if (out.destroying) return + pipeline(src, out, noop) + }) + .catch((err) => out.destroy(err)) + + return out + } + + setEncoding(encoding) { + const dec = new TextDecoder(encoding) + const map = this._readableState.map || echo + this._readableState.map = mapOrSkip + return this + + function mapOrSkip(data) { + const next = dec.push(data) + return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next) + } + } + + _read(cb) { + cb(null) + } + + pipe(dest, cb) { + this._readableState.updateNextTick() + this._readableState.pipe(dest, cb) + return dest + } + + read() { + this._readableState.updateNextTick() + return this._readableState.read() + } + + push(data) { + this._readableState.updateNextTickIfOpen() + return this._readableState.push(data) + } + + unshift(data) { + this._readableState.updateNextTickIfOpen() + return this._readableState.unshift(data) + } + + resume() { + this._duplexState |= READ_RESUMED_READ_AHEAD + this._readableState.updateNextTick() + return this + } + + pause() { + this._duplexState &= + this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED + return this + } + + static _fromAsyncIterator(ite, opts) { + let destroy + + const rs = new Readable({ + ...opts, + read(cb) { + ite.next().then(push).then(cb.bind(null, null)).catch(cb) + }, + predestroy() { + destroy = ite.return() + }, + destroy(cb) { + if (!destroy) return cb(null) + destroy.then(cb.bind(null, null)).catch(cb) + } + }) + + return rs + + function push(data) { + if (data.done) rs.push(null) + else rs.push(data.value) + } + } + + static from(data, opts) { + if (isReadStreamx(data)) return data + if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts) + if (!Array.isArray(data)) data = data === undefined ? [] : [data] + + let i = 0 + return new Readable({ + ...opts, + read(cb) { + this.push(i === data.length ? null : data[i++]) + cb(null) + } + }) + } + + static isBackpressured(rs) { + return ( + (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || + rs._readableState.buffered >= rs._readableState.highWaterMark + ) + } + + static isPaused(rs) { + return (rs._duplexState & READ_RESUMED) === 0 + } + + [asyncIterator]() { + const stream = this + + let error = null + let promiseResolve = null + let promiseReject = null + + this.on('error', (err) => { + error = err + }) + this.on('readable', onreadable) + this.on('close', onclose) + + return { + [asyncIterator]() { + return this + }, + next() { + return new Promise(function (resolve, reject) { + promiseResolve = resolve + promiseReject = reject + const data = stream.read() + if (data !== null) ondata(data) + else if ((stream._duplexState & DESTROYED) !== 0) ondata(null) + }) + }, + return() { + return destroy(null) + }, + throw(err) { + return destroy(err) + } + } + + function onreadable() { + if (promiseResolve !== null) ondata(stream.read()) + } + + function onclose() { + if (promiseResolve !== null) ondata(null) + } + + function ondata(data) { + if (promiseReject === null) return + if (error) { + promiseReject(error) + } else if (data === null && (stream._duplexState & READ_DONE) === 0) { + promiseReject(StreamError.STREAM_DESTROYED()) + } else { + promiseResolve({ value: data, done: data === null }) + } + promiseReject = promiseResolve = null + } + + function destroy(err) { + stream.destroy(err) + return new Promise((resolve, reject) => { + if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true }) + stream.once('close', function () { + if (err) reject(err) + else resolve({ value: undefined, done: true }) + }) + }) + } + } +} + +class Writable extends Stream { + constructor(opts) { + super(opts) + + this._duplexState |= OPENING | READ_DONE + this._writableState = new WritableState(this, opts) + + if (opts) { + if (opts.writev) this._writev = opts.writev + if (opts.write) this._write = opts.write + if (opts.final) this._final = opts.final + if (opts.eagerOpen) this._writableState.updateNextTick() + } + } + + cork() { + this._duplexState |= WRITE_CORKED + } + + uncork() { + this._duplexState &= WRITE_NOT_CORKED + this._writableState.updateNextTick() + } + + _writev(batch, cb) { + cb(null) + } + + _write(data, cb) { + this._writableState.autoBatch(data, cb) + } + + _final(cb) { + cb(null) + } + + static isBackpressured(ws) { + return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0 + } + + static drained(ws) { + if (ws.destroyed) return Promise.resolve(false) + + const state = ws._writableState + const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length + const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0) + if (writes === 0) return Promise.resolve(true) + + if (state.drains === null) state.drains = [] + return new Promise((resolve) => { + state.drains.push({ writes, resolve }) + }) + } + + write(data) { + this._writableState.updateNextTick() + return this._writableState.push(data) + } + + end(data) { + this._writableState.updateNextTick() + this._writableState.end(data) + return this + } +} + +class Duplex extends Readable { + // and Writable + constructor(opts) { + super(opts) + + this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD) + this._writableState = new WritableState(this, opts) + + if (opts) { + if (opts.writev) this._writev = opts.writev + if (opts.write) this._write = opts.write + if (opts.final) this._final = opts.final + } + } + + cork() { + this._duplexState |= WRITE_CORKED + } + + uncork() { + this._duplexState &= WRITE_NOT_CORKED + this._writableState.updateNextTick() + } + + _writev(batch, cb) { + cb(null) + } + + _write(data, cb) { + this._writableState.autoBatch(data, cb) + } + + _final(cb) { + cb(null) + } + + write(data) { + this._writableState.updateNextTick() + return this._writableState.push(data) + } + + end(data) { + this._writableState.updateNextTick() + this._writableState.end(data) + return this + } +} + +class Transform extends Duplex { + constructor(opts) { + super(opts) + this._transformState = new TransformState(this) + + if (opts) { + if (opts.transform) this._transform = opts.transform + if (opts.flush) this._flush = opts.flush + } + } + + _write(data, cb) { + if (this._readableState.buffered >= this._readableState.highWaterMark) { + this._transformState.data = data + } else { + this._transform(data, this._transformState.afterTransform) + } + } + + _read(cb) { + if (this._transformState.data !== null) { + const data = this._transformState.data + this._transformState.data = null + cb(null) + this._transform(data, this._transformState.afterTransform) + } else { + cb(null) + } + } + + destroy(err) { + super.destroy(err) + if (this._transformState.data !== null) { + this._transformState.data = null + this._transformState.afterTransform() + } + } + + _transform(data, cb) { + cb(null, data) + } + + _flush(cb) { + cb(null) + } + + _final(cb) { + this._transformState.afterFinal = cb + this._flush(transformAfterFlush.bind(this)) + } +} + +class PassThrough extends Transform {} + +function transformAfterFlush(err, data) { + const cb = this._transformState.afterFinal + if (err) return cb(err) + + if (data !== null && data !== undefined) this.push(data) + this.push(null) + cb(null) +} + +function pipelinePromise(...streams) { + return new Promise((resolve, reject) => { + return pipeline(...streams, (err) => { + if (err) return reject(err) + resolve() + }) + }) +} + +function pipeline(stream, ...streams) { + const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams] + const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null + + if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams') + + let src = all[0] + let dest = null + let error = null + + for (let i = 1; i < all.length; i++) { + dest = all[i] + + if (isStreamx(src)) { + src.pipe(dest, onerror) + } else { + errorHandle(src, true, i > 1, onerror) + src.pipe(dest) + } + + src = dest + } + + if (done) { + let fin = false + + const autoDestroy = + isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy) + + dest.on('error', (err) => { + if (error === null) error = err + }) + + dest.on('finish', () => { + fin = true + if (!autoDestroy) done(error) + }) + + if (autoDestroy) { + dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE()))) + } + } + + return dest + + function errorHandle(s, rd, wr, onerror) { + s.on('error', onerror) + s.on('close', onclose) + + function onclose() { + if (rd && s._readableState && !s._readableState.ended) { + return onerror(StreamError.PREMATURE_CLOSE()) + } + if (wr && s._writableState && !s._writableState.ended) { + return onerror(StreamError.PREMATURE_CLOSE()) + } + } + } + + function onerror(err) { + if (!err || error) return + error = err + + for (const s of all) { + s.destroy(err) + } + } +} + +function echo(s) { + return s +} + +function isStream(stream) { + return !!stream._readableState || !!stream._writableState +} + +function isStreamx(stream) { + return typeof stream._duplexState === 'number' && isStream(stream) +} + +function isEnding(stream) { + return !!stream._readableState && stream._readableState.ending +} + +function isEnded(stream) { + return !!stream._readableState && stream._readableState.ended +} + +function isFinishing(stream) { + return !!stream._writableState && stream._writableState.ending +} + +function isFinished(stream) { + return !!stream._writableState && stream._writableState.ended +} + +function getStreamError(stream, opts = {}) { + const err = + (stream._readableState && stream._readableState.error) || + (stream._writableState && stream._writableState.error) + + // avoid implicit errors by default + return !opts.all && StreamError.isStreamDestroyed(err) ? null : err +} + +function isReadStreamx(stream) { + return isStreamx(stream) && stream.readable +} + +function isDisturbed(stream) { + return ( + (stream._duplexState & OPENING) !== OPENING || + (stream._duplexState & DESTROYING) === DESTROYING || + (stream._duplexState & ACTIVE_OR_TICKING) !== 0 + ) +} + +function isTypedArray(data) { + return typeof data === 'object' && data !== null && typeof data.byteLength === 'number' +} + +function defaultByteLength(data) { + return isTypedArray(data) ? data.byteLength : 1024 +} + +function noop() {} + +function abort() { + this.destroy(StreamError.ABORTED()) +} + +function isWritev(s) { + return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev +} + +module.exports = { + pipeline, + pipelinePromise, + isStream, + isStreamx, + isEnding, + isEnded, + isFinishing, + isFinished, + isDisturbed, + getStreamError, + Stream, + Writable, + Readable, + Duplex, + Transform, + // Export PassThrough for compatibility with Node.js core's stream module + PassThrough +} diff --git a/node_modules/streamx/lib/errors.d.ts b/node_modules/streamx/lib/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3464f5f9e0e0c727f0df7209f623633f03803c4 --- /dev/null +++ b/node_modules/streamx/lib/errors.d.ts @@ -0,0 +1,13 @@ +declare class StreamError extends Error { + readonly code: string + + static isStreamDestroyed(err: Error | null): boolean + static isPrematureClose(err: Error | null): boolean + static isAborted(err: Error | null): boolean + + static STREAM_DESTROYED(): StreamError + static PREMATURE_CLOSE(): StreamError + static ABORTED(): StreamError +} + +export = StreamError diff --git a/node_modules/streamx/lib/errors.js b/node_modules/streamx/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..1a19df942a425b5aa1ef12226d026ad1d2a148af --- /dev/null +++ b/node_modules/streamx/lib/errors.js @@ -0,0 +1,47 @@ +module.exports = class StreamError extends Error { + constructor(msg, code, fn = StreamError) { + super(msg) + + this.code = code + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, fn) + } + } + + static isStreamDestroyed(err) { + return err && err.code === 'STREAM_DESTROYED' + } + + static isPrematureClose(err) { + return err && err.code === 'PREMATURE_CLOSE' + } + + static isAborted(err) { + return err && err.code === 'ABORTED' + } + + static isBadArgument(err) { + return err && err.code === 'BAD_ARGUMENT' + } + + get name() { + return 'StreamError' + } + + static STREAM_DESTROYED() { + return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED) + } + + static PREMATURE_CLOSE(msg = 'Premature close') { + return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE) + } + + static ABORTED() { + return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED) + } + + static BAD_ARGUMENT(msg = 'Bad argument') { + return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT) + } +} diff --git a/node_modules/streamx/package.json b/node_modules/streamx/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7657f46508bc5fb65d33fd84163394a08b0acdab --- /dev/null +++ b/node_modules/streamx/package.json @@ -0,0 +1,51 @@ +{ + "name": "streamx", + "version": "2.28.0", + "description": "An iteration of the Node.js core streams with a series of improvements", + "main": "index.js", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./package": "./package.json", + "./errors": { + "types": "./lib/errors.d.ts", + "default": "./lib/errors" + } + }, + "dependencies": { + "events-universal": "^1.0.0", + "fast-fifo": "^1.3.2", + "text-decoder": "^1.1.0" + }, + "devDependencies": { + "b4a": "^1.6.6", + "brittle": "^3.1.1", + "end-of-stream": "^1.4.4", + "lunte": "^1.8.0", + "prettier": "^3.6.2", + "prettier-config-holepunch": "^2.0.0" + }, + "files": [ + "index.js", + "index.d.ts", + "runtime.d.ts", + "lib" + ], + "scripts": { + "format": "prettier . --write", + "test": "brittle test/all.js && brittle-bare test/all.js", + "lint": "prettier . --check && lunte" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/streamx.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/streamx/issues" + }, + "homepage": "https://github.com/mafintosh/streamx" +} diff --git a/node_modules/streamx/runtime.d.ts b/node_modules/streamx/runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..204685a3699249d18955bdf307c3d84045ced71d --- /dev/null +++ b/node_modules/streamx/runtime.d.ts @@ -0,0 +1,55 @@ +type BufferEncoding = + | 'ascii' + | 'base64' + | 'binary' + | 'hex' + | 'latin1' + | 'ucs-2' + | 'ucs2' + | 'utf-16le' + | 'utf-8' + | 'utf16le' + | 'utf8' + +interface EventMap { + [event: string | symbol]: unknown[] +} + +interface EventHandler { + (...args: A): R +} + +interface EventEmitter { + addListener(name: E, fn: EventHandler): this + + addOnceListener(name: E, fn: EventHandler): this + + prependListener(name: E, fn: EventHandler): this + + prependOnceListener(name: E, fn: EventHandler): this + + removeListener(name: E, fn: EventHandler): this + + removeAllListeners(name?: E): this + + on(name: E, fn: EventHandler): this + + once(name: E, fn: EventHandler): this + + off(name: E, fn: EventHandler): this + + emit(name: E, ...args: M[E]): boolean + + listeners(name: E): EventHandler + + rawListeners(name: E): EventHandler[] + + eventNames(): (keyof M)[] + + listenerCount(name: E): number + + getMaxListeners(): number + setMaxListeners(n: number): void +} + +export { BufferEncoding, EventMap, EventEmitter } diff --git a/node_modules/strict-event-emitter/README.md b/node_modules/strict-event-emitter/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c972baacd488a347733c713f49b85b03d60b2ef5 --- /dev/null +++ b/node_modules/strict-event-emitter/README.md @@ -0,0 +1,79 @@ +# Strict Event Emitter + +A type-safe implementation of `EventEmitter` for browser and Node.js. + +## Motivation + +Despite event emitters potentially accepting any runtime value, defining a strict event contract is crucial when developing complex event-driven architectures. Unfortunately, the native type definitions for Node's `EventEmitter` annotate event names as `string`, which forbids any stricter type validation. + +```js +// index.js +const emitter = new EventEmitter() + +// Let's say our application expects a "ping" +// event with the number payload. +emitter.on('ping', (n: number) => {}) + +// We can, however, emit a different event by mistake. +emitter.emit('pong', 1) + +// Or even the correct event with the wrong data. +emitter.emit('ping', 'wait, not a number') +``` + +The purpose of this library is to provide an `EventEmitter` instance that can accept a generic describing the expected events contract. + +```ts +import { Emitter } from 'strict-event-emitter' + +// Define a strict events contract where keys +// represent event names and values represent +// the list of arguments expected in ".emit()". +type Events = { + ping: [number] +} + +const emitter = new Emitter() +emitter.addListener('ping', (n) => { + // "n" argument type is inferred as "number'. +}) + +emitter.emit('ping', 10) // OK +emitter.emit('unknown', 10) // TypeError (invalid event name) +emitter.emit('ping', 'wait, not a number') // TypeError (invalid data) +``` + +This library is also a custom `EventEmitter` implementation, which makes it compatible with other environments, like browsers or React Native. + +## Getting started + +### Install + +```bash +npm install strict-event-emitter +``` + +### Use + +```ts +import { Emitter } from 'strict-event-emitter' + +// 1. Define an interface that describes your events. +// Set event names as the keys, and their expected payloads as values. +interface Events { + connect: [id: string] + disconnect: [id: string] +} + +// 2. Create a strict emitter and pass the previously defined "Events" +// as its first generic argument. +const emitter = new Emitter() + +// 3. Use the "emitter" the same way you'd use the regular "EventEmitter" instance. +emitter.addListener('connect', (id) => {}) +emitter.emit('connect', 'abc-123') +``` + +## License + +MIT diff --git a/node_modules/strict-event-emitter/lib/index.d.ts b/node_modules/strict-event-emitter/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7068ce7ba148a872781e2ff1ce8160a77e05fb50 --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.d.ts @@ -0,0 +1,81 @@ +declare type EventMap = { + [eventName: string]: Array; +}; +declare type InternalEventNames = 'newListener' | 'removeListener'; +declare type InternalListener = Listener<[ + eventName: keyof Events, + listener: Listener> +]>; +declare type Listener> = (...data: Data) => void; +/** + * Node.js-compatible implementation of `EventEmitter`. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.on('hello', (name) => console.log(name)) + * emitter.emit('hello', 'John') + */ +declare class Emitter { + private events; + private maxListeners; + private hasWarnedAboutPotentialMemoryLeak; + static defaultMaxListeners: number; + static listenerCount(emitter: Emitter, eventName: keyof Events): number; + constructor(); + private _emitInternalEvent; + private _getListeners; + private _removeListener; + private _wrapOnceListener; + setMaxListeners(maxListeners: number): this; + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners(): number; + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames(): Array; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName: EventName, ...data: Events[EventName]): boolean; + addListener(eventName: InternalEventNames, listener: InternalListener): this; + addListener(eventName: EventName, listener: Listener): this; + on(eventName: InternalEventNames, listener: InternalListener): this; + on(eventName: EventName, listener: Listener): this; + once(eventName: InternalEventNames, listener: InternalListener): this; + once(eventName: EventName, listener: Listener): this; + prependListener(eventName: InternalEventNames, listener: InternalListener): this; + prependListener(eventName: EventName, listener: Listener): this; + prependOnceListener(eventName: InternalEventNames, listener: InternalListener): this; + prependOnceListener(eventName: EventName, listener: Listener): this; + removeListener(eventName: InternalEventNames, listener: InternalListener): this; + removeListener(eventName: EventName, listener: Listener): this; + off(eventName: InternalEventNames, listener: InternalListener): this; + off(eventName: EventName, listener: Listener): this; + removeAllListeners(eventName?: InternalEventNames): this; + removeAllListeners(eventName?: EventName): this; + listeners(eventName: InternalEventNames): Array>; + listeners(eventName: EventName): Array>; + listenerCount(eventName: InternalEventNames): number; + listenerCount(eventName: EventName): number; + rawListeners(eventName: EventName): Array>; +} + +declare class MemoryLeakError extends Error { + readonly emitter: Emitter; + readonly type: string | number | symbol; + readonly count: number; + constructor(emitter: Emitter, type: string | number | symbol, count: number); +} + +export { Emitter, EventMap, InternalEventNames, InternalListener, Listener, MemoryLeakError }; diff --git a/node_modules/strict-event-emitter/lib/index.js b/node_modules/strict-event-emitter/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d4bc820d2122dd6551334b1d1d533c43b7ce15f --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.js @@ -0,0 +1,198 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Emitter: () => Emitter, + MemoryLeakError: () => MemoryLeakError +}); +module.exports = __toCommonJS(src_exports); + +// src/MemoryLeakError.ts +var MemoryLeakError = class extends Error { + constructor(emitter, type, count) { + super( + `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` + ); + this.emitter = emitter; + this.type = type; + this.count = count; + this.name = "MaxListenersExceededWarning"; + } +}; + +// src/Emitter.ts +var _Emitter = class { + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.maxListeners = _Emitter.defaultMaxListeners; + this.hasWarnedAboutPotentialMemoryLeak = false; + } + _emitInternalEvent(internalEventName, eventName, listener) { + this.emit( + internalEventName, + ...[eventName, listener] + ); + } + _getListeners(eventName) { + return Array.prototype.concat.apply([], this.events.get(eventName)) || []; + } + _removeListener(listeners, listener) { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + return []; + } + _wrapOnceListener(eventName, listener) { + const onceListener = (...data) => { + this.removeListener(eventName, onceListener); + return listener.apply(this, data); + }; + Object.defineProperty(onceListener, "name", { value: listener.name }); + return onceListener; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners() { + return this.maxListeners; + } + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames() { + return Array.from(this.events.keys()); + } + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName, ...data) { + const listeners = this._getListeners(eventName); + listeners.forEach((listener) => { + listener.apply(this, data); + }); + return listeners.length > 0; + } + addListener(eventName, listener) { + this._emitInternalEvent("newListener", eventName, listener); + const nextListeners = this._getListeners(eventName).concat(listener); + this.events.set(eventName, nextListeners); + if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { + this.hasWarnedAboutPotentialMemoryLeak = true; + const memoryLeakWarning = new MemoryLeakError( + this, + eventName, + this.listenerCount(eventName) + ); + console.warn(memoryLeakWarning); + } + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + return this.addListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + prependListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + const nextListeners = [listener].concat(listeners); + this.events.set(eventName, nextListeners); + } else { + this.events.set(eventName, listeners.concat(listener)); + } + return this; + } + prependOnceListener(eventName, listener) { + return this.prependListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + removeListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + this._removeListener(listeners, listener); + this.events.set(eventName, listeners); + this._emitInternalEvent("removeListener", eventName, listener); + } + return this; + } + /** + * Alias for `emitter.removeListener()`. + * + * @example + * emitter.off('hello', listener) + */ + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(eventName) { + if (eventName) { + this.events.delete(eventName); + } else { + this.events.clear(); + } + return this; + } + /** + * Returns a copy of the array of listeners for the event named `eventName`. + */ + listeners(eventName) { + return Array.from(this._getListeners(eventName)); + } + /** + * Returns the number of listeners listening to the event named `eventName`. + */ + listenerCount(eventName) { + return this._getListeners(eventName).length; + } + rawListeners(eventName) { + return this.listeners(eventName); + } +}; +var Emitter = _Emitter; +Emitter.defaultMaxListeners = 10; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Emitter, + MemoryLeakError +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/strict-event-emitter/lib/index.js.map b/node_modules/strict-event-emitter/lib/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6dd965299dba60a299b38037fa8e7173110d1c47 --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/MemoryLeakError.ts","../src/Emitter.ts"],"sourcesContent":["export * from './Emitter'\nexport * from './MemoryLeakError'\n","import type { Emitter } from './Emitter'\n\nexport class MemoryLeakError extends Error {\n constructor(\n public readonly emitter: Emitter,\n public readonly type: string | number | symbol,\n public readonly count: number\n ) {\n super(\n `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`\n )\n this.name = 'MaxListenersExceededWarning'\n }\n}\n","import { MemoryLeakError } from './MemoryLeakError'\n\nexport type EventMap = {\n [eventName: string]: Array\n}\n\nexport type InternalEventNames = 'newListener' | 'removeListener'\n\nexport type InternalListener = Listener<\n [eventName: keyof Events, listener: Listener>]\n>\n\nexport type Listener> = (...data: Data) => void\n\n/**\n * Node.js-compatible implementation of `EventEmitter`.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.on('hello', (name) => console.log(name))\n * emitter.emit('hello', 'John')\n */\nexport class Emitter {\n private events: Map>>\n private maxListeners: number\n private hasWarnedAboutPotentialMemoryLeak: boolean\n\n static defaultMaxListeners = 10\n\n static listenerCount(\n emitter: Emitter,\n eventName: keyof Events\n ): number {\n return emitter.listenerCount(eventName)\n }\n\n constructor() {\n this.events = new Map()\n this.maxListeners = Emitter.defaultMaxListeners\n this.hasWarnedAboutPotentialMemoryLeak = false\n }\n\n private _emitInternalEvent(\n internalEventName: InternalEventNames,\n eventName: keyof Events,\n listener: Listener>\n ): void {\n this.emit(\n internalEventName,\n // Anything to make TypeScript happy.\n ...([eventName, listener] as Events['newListener'] &\n Events['removeListener'])\n )\n }\n\n private _getListeners(\n eventName: EventName\n ): Array>> {\n // Always return a copy of the listeners array\n // so they are fixed at the time of the \"_getListeners\" call.\n return Array.prototype.concat.apply([], this.events.get(eventName)) || []\n }\n\n private _removeListener(\n listeners: Array>,\n listener: Listener\n ): Array> {\n const index = listeners.indexOf(listener)\n\n if (index > -1) {\n listeners.splice(index, 1)\n }\n\n return []\n }\n\n private _wrapOnceListener(\n eventName: EventName,\n listener: Listener\n ): Listener {\n const onceListener = (...data: Events[keyof Events]) => {\n this.removeListener(eventName, onceListener)\n\n /**\n * @note Return the result of the original listener.\n * This way this wrapped preserves listeners that are async.\n */\n return listener.apply(this, data)\n }\n\n // Inherit the name of the original listener.\n Object.defineProperty(onceListener, 'name', { value: listener.name })\n\n return onceListener\n }\n\n public setMaxListeners(maxListeners: number): this {\n this.maxListeners = maxListeners\n return this\n }\n\n /**\n * Returns the current max listener value for the `Emitter` which is\n * either set by `emitter.setMaxListeners(n)` or defaults to\n * `Emitter.defaultMaxListeners`.\n */\n public getMaxListeners(): number {\n return this.maxListeners\n }\n\n /**\n * Returns an array listing the events for which the emitter has registered listeners.\n * The values in the array will be strings or Symbols.\n */\n public eventNames(): Array {\n return Array.from(this.events.keys())\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named `eventName`,\n * in the order they were registered, passing the supplied arguments to each.\n * Returns `true` if the event has listeners, `false` otherwise.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.emit('hello', 'John')\n */\n public emit(\n eventName: EventName,\n ...data: Events[EventName]\n ): boolean {\n const listeners = this._getListeners(eventName)\n listeners.forEach((listener) => {\n listener.apply(this, data)\n })\n\n return listeners.length > 0\n }\n\n public addListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public addListener(\n eventName: EventName,\n listener: Listener\n ): this\n public addListener(\n eventName: InternalEventNames | keyof Events,\n listener: InternalListener | Listener\n ): this {\n // Emit the `newListener` event before adding the listener.\n this._emitInternalEvent('newListener', eventName, listener)\n\n const nextListeners = this._getListeners(eventName).concat(listener)\n this.events.set(eventName, nextListeners)\n\n if (\n this.maxListeners > 0 &&\n this.listenerCount(eventName) > this.maxListeners &&\n !this.hasWarnedAboutPotentialMemoryLeak\n ) {\n this.hasWarnedAboutPotentialMemoryLeak = true\n\n const memoryLeakWarning = new MemoryLeakError(\n this,\n eventName,\n this.listenerCount(eventName)\n )\n console.warn(memoryLeakWarning)\n }\n\n return this\n }\n\n public on(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public on(\n eventName: EventName,\n listener: Listener\n ): this\n public on(\n eventName: 'removeListener' | EventName,\n listener: Listener\n ): this {\n return this.addListener(eventName, listener)\n }\n\n public once(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public once(\n eventName: EventName,\n listener: Listener\n ): this\n public once(\n eventName: InternalEventNames | EventName,\n listener: Listener\n ): this {\n return this.addListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public prependListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n const nextListeners = [listener].concat(listeners)\n this.events.set(eventName, nextListeners)\n } else {\n this.events.set(eventName, listeners.concat(listener))\n }\n\n return this\n }\n\n public prependOnceListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependOnceListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependOnceListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.prependListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public removeListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public removeListener(\n eventName: EventName,\n listener: Listener\n ): this\n public removeListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n this._removeListener(listeners, listener)\n this.events.set(eventName, listeners)\n\n // Emit the `removeListener` event after removing the listener.\n this._emitInternalEvent('removeListener', eventName, listener)\n }\n\n return this\n }\n\n public off(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public off(\n eventName: EventName,\n listener: Listener\n ): this\n /**\n * Alias for `emitter.removeListener()`.\n *\n * @example\n * emitter.off('hello', listener)\n */\n public off(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.removeListener(eventName, listener)\n }\n\n public removeAllListeners(eventName?: InternalEventNames): this\n public removeAllListeners(\n eventName?: EventName\n ): this\n public removeAllListeners(\n eventName?: InternalEventNames | keyof Events\n ): this {\n if (eventName) {\n this.events.delete(eventName)\n } else {\n this.events.clear()\n }\n\n return this\n }\n\n public listeners(eventName: InternalEventNames): Array>\n public listeners(\n eventName: EventName\n ): Array>\n /**\n * Returns a copy of the array of listeners for the event named `eventName`.\n */\n public listeners(eventName: InternalEventNames | keyof Events) {\n return Array.from(this._getListeners(eventName))\n }\n\n public listenerCount(eventName: InternalEventNames): number\n public listenerCount(\n eventName: EventName\n ): number\n /**\n * Returns the number of listeners listening to the event named `eventName`.\n */\n public listenerCount(eventName: InternalEventNames | keyof Events): number {\n return this._getListeners(eventName).length\n }\n\n public rawListeners(\n eventName: EventName\n ): Array> {\n return this.listeners(eventName)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACkB,SACA,MACA,OAChB;AACA;AAAA,MACE,+CAA+C,SAAS,KAAK,SAAS;AAAA,IACxE;AANgB;AACA;AACA;AAKhB,SAAK,OAAO;AAAA,EACd;AACF;;;ACSO,IAAM,WAAN,MAAuC;AAAA,EAO5C,OAAO,cACL,SACA,WACQ;AACR,WAAO,QAAQ,cAAmB,SAAS;AAAA,EAC7C;AAAA,EAEA,cAAc;AACZ,SAAK,SAAS,oBAAI,IAAI;AACtB,SAAK,eAAe,SAAQ;AAC5B,SAAK,oCAAoC;AAAA,EAC3C;AAAA,EAEQ,mBACN,mBACA,WACA,UACM;AACN,SAAK;AAAA,MACH;AAAA,MAEA,GAAI,CAAC,WAAW,QAAQ;AAAA,IAE1B;AAAA,EACF;AAAA,EAEQ,cACN,WACiC;AAGjC,WAAO,MAAM,UAAU,OAAO,MAAM,CAAC,GAA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A;AAAA;AAAA;AAAA,EASO,UAAU,WAA8C;AAC7D,WAAO,MAAM,KAAK,KAAK,cAAc,SAAS,CAAC;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA,EASO,cAAc,WAAsD;AACzE,WAAO,KAAK,cAAc,SAAS,EAAE;AAAA,EACvC;AAAA,EAEO,aACL,WACoC;AACpC,WAAO,KAAK,UAAU,SAAS;AAAA,EACjC;AACF;AA7TO,IAAM,UAAN;AAAM,QAKJ,sBAAsB;","names":[]} \ No newline at end of file diff --git a/node_modules/strict-event-emitter/lib/index.mjs b/node_modules/strict-event-emitter/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d68faf826181af771158237f8d4ce5a95a08974c --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.mjs @@ -0,0 +1,171 @@ +// src/MemoryLeakError.ts +var MemoryLeakError = class extends Error { + constructor(emitter, type, count) { + super( + `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` + ); + this.emitter = emitter; + this.type = type; + this.count = count; + this.name = "MaxListenersExceededWarning"; + } +}; + +// src/Emitter.ts +var _Emitter = class { + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.maxListeners = _Emitter.defaultMaxListeners; + this.hasWarnedAboutPotentialMemoryLeak = false; + } + _emitInternalEvent(internalEventName, eventName, listener) { + this.emit( + internalEventName, + ...[eventName, listener] + ); + } + _getListeners(eventName) { + return Array.prototype.concat.apply([], this.events.get(eventName)) || []; + } + _removeListener(listeners, listener) { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + return []; + } + _wrapOnceListener(eventName, listener) { + const onceListener = (...data) => { + this.removeListener(eventName, onceListener); + return listener.apply(this, data); + }; + Object.defineProperty(onceListener, "name", { value: listener.name }); + return onceListener; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners() { + return this.maxListeners; + } + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames() { + return Array.from(this.events.keys()); + } + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName, ...data) { + const listeners = this._getListeners(eventName); + listeners.forEach((listener) => { + listener.apply(this, data); + }); + return listeners.length > 0; + } + addListener(eventName, listener) { + this._emitInternalEvent("newListener", eventName, listener); + const nextListeners = this._getListeners(eventName).concat(listener); + this.events.set(eventName, nextListeners); + if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { + this.hasWarnedAboutPotentialMemoryLeak = true; + const memoryLeakWarning = new MemoryLeakError( + this, + eventName, + this.listenerCount(eventName) + ); + console.warn(memoryLeakWarning); + } + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + return this.addListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + prependListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + const nextListeners = [listener].concat(listeners); + this.events.set(eventName, nextListeners); + } else { + this.events.set(eventName, listeners.concat(listener)); + } + return this; + } + prependOnceListener(eventName, listener) { + return this.prependListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + removeListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + this._removeListener(listeners, listener); + this.events.set(eventName, listeners); + this._emitInternalEvent("removeListener", eventName, listener); + } + return this; + } + /** + * Alias for `emitter.removeListener()`. + * + * @example + * emitter.off('hello', listener) + */ + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(eventName) { + if (eventName) { + this.events.delete(eventName); + } else { + this.events.clear(); + } + return this; + } + /** + * Returns a copy of the array of listeners for the event named `eventName`. + */ + listeners(eventName) { + return Array.from(this._getListeners(eventName)); + } + /** + * Returns the number of listeners listening to the event named `eventName`. + */ + listenerCount(eventName) { + return this._getListeners(eventName).length; + } + rawListeners(eventName) { + return this.listeners(eventName); + } +}; +var Emitter = _Emitter; +Emitter.defaultMaxListeners = 10; +export { + Emitter, + MemoryLeakError +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/strict-event-emitter/lib/index.mjs.map b/node_modules/strict-event-emitter/lib/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..26936046f3a77146abe223b67f555d4854c36b31 --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/MemoryLeakError.ts","../src/Emitter.ts"],"sourcesContent":["import type { Emitter } from './Emitter'\n\nexport class MemoryLeakError extends Error {\n constructor(\n public readonly emitter: Emitter,\n public readonly type: string | number | symbol,\n public readonly count: number\n ) {\n super(\n `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`\n )\n this.name = 'MaxListenersExceededWarning'\n }\n}\n","import { MemoryLeakError } from './MemoryLeakError'\n\nexport type EventMap = {\n [eventName: string]: Array\n}\n\nexport type InternalEventNames = 'newListener' | 'removeListener'\n\nexport type InternalListener = Listener<\n [eventName: keyof Events, listener: Listener>]\n>\n\nexport type Listener> = (...data: Data) => void\n\n/**\n * Node.js-compatible implementation of `EventEmitter`.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.on('hello', (name) => console.log(name))\n * emitter.emit('hello', 'John')\n */\nexport class Emitter {\n private events: Map>>\n private maxListeners: number\n private hasWarnedAboutPotentialMemoryLeak: boolean\n\n static defaultMaxListeners = 10\n\n static listenerCount(\n emitter: Emitter,\n eventName: keyof Events\n ): number {\n return emitter.listenerCount(eventName)\n }\n\n constructor() {\n this.events = new Map()\n this.maxListeners = Emitter.defaultMaxListeners\n this.hasWarnedAboutPotentialMemoryLeak = false\n }\n\n private _emitInternalEvent(\n internalEventName: InternalEventNames,\n eventName: keyof Events,\n listener: Listener>\n ): void {\n this.emit(\n internalEventName,\n // Anything to make TypeScript happy.\n ...([eventName, listener] as Events['newListener'] &\n Events['removeListener'])\n )\n }\n\n private _getListeners(\n eventName: EventName\n ): Array>> {\n // Always return a copy of the listeners array\n // so they are fixed at the time of the \"_getListeners\" call.\n return Array.prototype.concat.apply([], this.events.get(eventName)) || []\n }\n\n private _removeListener(\n listeners: Array>,\n listener: Listener\n ): Array> {\n const index = listeners.indexOf(listener)\n\n if (index > -1) {\n listeners.splice(index, 1)\n }\n\n return []\n }\n\n private _wrapOnceListener(\n eventName: EventName,\n listener: Listener\n ): Listener {\n const onceListener = (...data: Events[keyof Events]) => {\n this.removeListener(eventName, onceListener)\n\n /**\n * @note Return the result of the original listener.\n * This way this wrapped preserves listeners that are async.\n */\n return listener.apply(this, data)\n }\n\n // Inherit the name of the original listener.\n Object.defineProperty(onceListener, 'name', { value: listener.name })\n\n return onceListener\n }\n\n public setMaxListeners(maxListeners: number): this {\n this.maxListeners = maxListeners\n return this\n }\n\n /**\n * Returns the current max listener value for the `Emitter` which is\n * either set by `emitter.setMaxListeners(n)` or defaults to\n * `Emitter.defaultMaxListeners`.\n */\n public getMaxListeners(): number {\n return this.maxListeners\n }\n\n /**\n * Returns an array listing the events for which the emitter has registered listeners.\n * The values in the array will be strings or Symbols.\n */\n public eventNames(): Array {\n return Array.from(this.events.keys())\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named `eventName`,\n * in the order they were registered, passing the supplied arguments to each.\n * Returns `true` if the event has listeners, `false` otherwise.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.emit('hello', 'John')\n */\n public emit(\n eventName: EventName,\n ...data: Events[EventName]\n ): boolean {\n const listeners = this._getListeners(eventName)\n listeners.forEach((listener) => {\n listener.apply(this, data)\n })\n\n return listeners.length > 0\n }\n\n public addListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public addListener(\n eventName: EventName,\n listener: Listener\n ): this\n public addListener(\n eventName: InternalEventNames | keyof Events,\n listener: InternalListener | Listener\n ): this {\n // Emit the `newListener` event before adding the listener.\n this._emitInternalEvent('newListener', eventName, listener)\n\n const nextListeners = this._getListeners(eventName).concat(listener)\n this.events.set(eventName, nextListeners)\n\n if (\n this.maxListeners > 0 &&\n this.listenerCount(eventName) > this.maxListeners &&\n !this.hasWarnedAboutPotentialMemoryLeak\n ) {\n this.hasWarnedAboutPotentialMemoryLeak = true\n\n const memoryLeakWarning = new MemoryLeakError(\n this,\n eventName,\n this.listenerCount(eventName)\n )\n console.warn(memoryLeakWarning)\n }\n\n return this\n }\n\n public on(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public on(\n eventName: EventName,\n listener: Listener\n ): this\n public on(\n eventName: 'removeListener' | EventName,\n listener: Listener\n ): this {\n return this.addListener(eventName, listener)\n }\n\n public once(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public once(\n eventName: EventName,\n listener: Listener\n ): this\n public once(\n eventName: InternalEventNames | EventName,\n listener: Listener\n ): this {\n return this.addListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public prependListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n const nextListeners = [listener].concat(listeners)\n this.events.set(eventName, nextListeners)\n } else {\n this.events.set(eventName, listeners.concat(listener))\n }\n\n return this\n }\n\n public prependOnceListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependOnceListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependOnceListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.prependListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public removeListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public removeListener(\n eventName: EventName,\n listener: Listener\n ): this\n public removeListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n this._removeListener(listeners, listener)\n this.events.set(eventName, listeners)\n\n // Emit the `removeListener` event after removing the listener.\n this._emitInternalEvent('removeListener', eventName, listener)\n }\n\n return this\n }\n\n public off(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public off(\n eventName: EventName,\n listener: Listener\n ): this\n /**\n * Alias for `emitter.removeListener()`.\n *\n * @example\n * emitter.off('hello', listener)\n */\n public off(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.removeListener(eventName, listener)\n }\n\n public removeAllListeners(eventName?: InternalEventNames): this\n public removeAllListeners(\n eventName?: EventName\n ): this\n public removeAllListeners(\n eventName?: InternalEventNames | keyof Events\n ): this {\n if (eventName) {\n this.events.delete(eventName)\n } else {\n this.events.clear()\n }\n\n return this\n }\n\n public listeners(eventName: InternalEventNames): Array>\n public listeners(\n eventName: EventName\n ): Array>\n /**\n * Returns a copy of the array of listeners for the event named `eventName`.\n */\n public listeners(eventName: InternalEventNames | keyof Events) {\n return Array.from(this._getListeners(eventName))\n }\n\n public listenerCount(eventName: InternalEventNames): number\n public listenerCount(\n eventName: EventName\n ): number\n /**\n * Returns the number of listeners listening to the event named `eventName`.\n */\n public listenerCount(eventName: InternalEventNames | keyof Events): number {\n return this._getListeners(eventName).length\n }\n\n public rawListeners(\n eventName: EventName\n ): Array> {\n return this.listeners(eventName)\n }\n}\n"],"mappings":";AAEO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACkB,SACA,MACA,OAChB;AACA;AAAA,MACE,+CAA+C,SAAS,KAAK,SAAS;AAAA,IACxE;AANgB;AACA;AACA;AAKhB,S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AI,UAAU,SAAS,GAAG;AACxB,WAAK,gBAAgB,WAAW,QAAQ;AACxC,WAAK,OAAO,IAAI,WAAW,SAAS;AAGpC,WAAK,mBAAmB,kBAAkB,WAAW,QAAQ;AAAA,IAC/D;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBO,IACL,WACA,UACM;AACN,WAAO,KAAK,eAAe,WAAW,QAAQ;AAAA,EAChD;AAAA,EAMO,mBACL,WACM;AACN,QAAI,WAAW;AACb,WAAK,OAAO,OAAO,SAAS;AAAA,IAC9B,OAAO;AACL,WAAK,OAAO,MAAM;AAAA,IACpB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EASO,UAAU,WAA8C;AAC7D,WAAO,MAAM,KAAK,KAAK,cAAc,SAAS,CAAC;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA,EASO,cAAc,WAAsD;AACzE,WAAO,KAAK,cAAc,SAAS,EAAE;AAAA,EACvC;AAAA,EAEO,aACL,WACoC;AACpC,WAAO,KAAK,UAAU,SAAS;AAAA,EACjC;AACF;AA7TO,IAAM,UAAN;AAAM,QAKJ,sBAAsB;","names":[]} \ No newline at end of file diff --git a/node_modules/strict-event-emitter/package.json b/node_modules/strict-event-emitter/package.json new file mode 100644 index 0000000000000000000000000000000000000000..54a40577dd875aa198f5c2f8bee2201718c1b5f8 --- /dev/null +++ b/node_modules/strict-event-emitter/package.json @@ -0,0 +1,41 @@ +{ + "name": "strict-event-emitter", + "version": "0.5.1", + "description": "Type-safe implementation of EventEmitter for browser and Node.js", + "main": "lib/index.js", + "module": "lib/index.mjs", + "typings": "lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "require": "./lib/index.js", + "default": "./lib/index.mjs" + } + }, + "repository": "git@github.com:open-draft/strict-event-emitter.git", + "author": "Artem Zakharchenko ", + "license": "MIT", + "files": [ + "lib" + ], + "devDependencies": { + "@ossjs/release": "^0.8.0", + "@types/events": "^3.0.0", + "@types/jest": "^29.2.4", + "jest": "^29.3.1", + "jest-extended": "^3.2.0", + "rimraf": "^3.0.2", + "ts-jest": "^29.0.3", + "ts-node": "^9.1.1", + "tsup": "^6.2.3", + "typescript": "4.8" + }, + "scripts": { + "dev": "tsc -w", + "test": "jest", + "test:ts": "tsc -p test/typings.tsconfig.json", + "clean": "rimraf ./lib", + "build": "pnpm clean && tsup", + "release": "release publish" + } +} \ No newline at end of file diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..778edb20730ef48c01002248f4d51e7752c13487 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5fd58315ed588027742dde690a31cd0a2610649d --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..2e89e63f7933e42b8ba543ede35d2a8fa3e4f100 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b2bb141160cad31581cf39ee21813196ad13a5cd --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/strip-bom/index.js b/node_modules/strip-bom/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b00feb9a440961c004d6eeaf297bd4cbd04d64a9 --- /dev/null +++ b/node_modules/strip-bom/index.js @@ -0,0 +1,14 @@ +'use strict'; +module.exports = x => { + if (typeof x !== 'string') { + throw new TypeError('Expected a string, got ' + typeof x); + } + + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (x.charCodeAt(0) === 0xFEFF) { + return x.slice(1); + } + + return x; +}; diff --git a/node_modules/strip-bom/license b/node_modules/strip-bom/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/strip-bom/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/strip-bom/package.json b/node_modules/strip-bom/package.json new file mode 100644 index 0000000000000000000000000000000000000000..10f8fdd7e5dba757e3c9557171d01ed5695d80e5 --- /dev/null +++ b/node_modules/strip-bom/package.json @@ -0,0 +1,40 @@ +{ + "name": "strip-bom", + "version": "3.0.0", + "description": "Strip UTF-8 byte order mark (BOM) from a string", + "license": "MIT", + "repository": "sindresorhus/strip-bom", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "strip", + "bom", + "byte", + "order", + "mark", + "unicode", + "utf8", + "utf-8", + "remove", + "delete", + "trim", + "text", + "string" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/strip-bom/readme.md b/node_modules/strip-bom/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..812a98071fb97f94deab51bc003d09f6f0be2cf8 --- /dev/null +++ b/node_modules/strip-bom/readme.md @@ -0,0 +1,36 @@ +# strip-bom [![Build Status](https://travis-ci.org/sindresorhus/strip-bom.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-bom) + +> Strip UTF-8 [byte order mark](http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8) (BOM) from a string + +From Wikipedia: + +> The Unicode Standard permits the BOM in UTF-8, but does not require nor recommend its use. Byte order has no meaning in UTF-8. + + +## Install + +``` +$ npm install --save strip-bom +``` + + +## Usage + +```js +const stripBom = require('strip-bom'); + +stripBom('\uFEFFunicorn'); +//=> 'unicorn' +``` + + +## Related + +- [strip-bom-cli](https://github.com/sindresorhus/strip-bom-cli) - CLI for this module +- [strip-bom-buf](https://github.com/sindresorhus/strip-bom-buf) - Buffer version of this module +- [strip-bom-stream](https://github.com/sindresorhus/strip-bom-stream) - Stream version of this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/strip-json-comments/index.js b/node_modules/strip-json-comments/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e6576e6d3c3883bdfaf1f67a05fd04a8d6927c5 --- /dev/null +++ b/node_modules/strip-json-comments/index.js @@ -0,0 +1,70 @@ +'use strict'; +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +module.exports = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; diff --git a/node_modules/strip-json-comments/license b/node_modules/strip-json-comments/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/strip-json-comments/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/strip-json-comments/package.json b/node_modules/strip-json-comments/package.json new file mode 100644 index 0000000000000000000000000000000000000000..288ecc7745b0d181320327c71716d3d3a1e3669f --- /dev/null +++ b/node_modules/strip-json-comments/package.json @@ -0,0 +1,42 @@ +{ + "name": "strip-json-comments", + "version": "2.0.1", + "description": "Strip comments from JSON. Lets you use comments in your JSON files!", + "license": "MIT", + "repository": "sindresorhus/strip-json-comments", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "json", + "strip", + "remove", + "delete", + "trim", + "comments", + "multiline", + "parse", + "config", + "configuration", + "conf", + "settings", + "util", + "env", + "environment" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/strip-json-comments/readme.md b/node_modules/strip-json-comments/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..0ee58dfe3a2e9bd059402c6b89c1c145305cda47 --- /dev/null +++ b/node_modules/strip-json-comments/readme.md @@ -0,0 +1,64 @@ +# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments) + +> Strip comments from JSON. Lets you use comments in your JSON files! + +This is now possible: + +```js +{ + // rainbows + "unicorn": /* ❤ */ "cake" +} +``` + +It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. + +Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin. + + +## Install + +``` +$ npm install --save strip-json-comments +``` + + +## Usage + +```js +const json = '{/*rainbows*/"unicorn":"cake"}'; + +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` + + +## API + +### stripJsonComments(input, [options]) + +#### input + +Type: `string` + +Accepts a string with JSON and returns a string without comments. + +#### options + +##### whitespace + +Type: `boolean` +Default: `true` + +Replace comments with whitespace instead of stripping them entirely. + + +## Related + +- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module +- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/strnum/CHANGELOG.md b/node_modules/strnum/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..15f39212b16e644cc895fbe86d60d10bb85982cb --- /dev/null +++ b/node_modules/strnum/CHANGELOG.md @@ -0,0 +1,51 @@ + +**2.4.0 / 2026-06-09** +- support unicode numerals using 'anynum' + +**2.3.0 / 2026-05-07** +- support octal and binary, test with @byspec/numbers +- test with @byspec/numbers + + +**2.2.3 / 2026-04-07** +- remove unnecessary files from npm package + +**2.2.2 / 2026-03-23** +- fix for space string + + +**2.2.1 / 2026-03-19** +- fix false positive for eNotation when no leading zeros + +**2.2.0 / 2026-02-28** +- support infinity + +**2.1.0 / 2025-05-01** +- fix e-notation + - to return string when invalid enotation is found. Eg `E24` + - to return valid number when only leading zero before e char is present + +**2.0.5 / 2025-02-27** +- changes done in 1.1.2 + +**1.1.2 / 2025-02-27** +- fix skiplike for 0 + +**1.1.1 / 2025-02-21** +- All recent fixes of version 2 + +**2.0.4 / 2025-02-20** +- remove console log + +**2.0.3 / 2025-02-20** +- fix for string which are falsly identified as e-notation + +**2.0.1 / 2025-02-20** +- fix: handle only zeros +- fix: return original string when NaN + +**2.0.0 / 2025-02-20** +- Migrating to ESM modules. No functional change + +**1.1.0 / 2025-02-20** +- fix (#9): support missing floating point and e notations \ No newline at end of file diff --git a/node_modules/strnum/LICENSE b/node_modules/strnum/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..64505544befa413eb28175a0db3532876a58412a --- /dev/null +++ b/node_modules/strnum/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Natural Intelligence + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/strnum/README.md b/node_modules/strnum/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d95da5ece7d660e4f2f834858c8ba52e0f4d4fa0 --- /dev/null +++ b/node_modules/strnum/README.md @@ -0,0 +1,113 @@ +# strnum +Parse string into Number based on configuration + +[![strnum downloads](https://img.shields.io/npm/dw/strnum.svg)](https://npm-compare.com/strnum) +[![strnum version](https://img.shields.io/npm/v/strnum.svg)](https://www.npmjs.com/package/strnum) +[![strnum license](https://img.shields.io/npm/l/strnum.svg)](https://github.com/NaturalIntelligence/strnum) + +## Users + + + + + +Many React Native projects and plugins + +## Usage + +```bash +npm install strnum +``` +```js +const toNumber = require("strnum"); + +toNumber(undefined) // undefined +toNumber(null)) //null +toNumber("")) // "" +toNumber("string"); //"string") +toNumber("12,12"); //"12,12") +toNumber("12 12"); //"12 12") +toNumber("12-12"); //"12-12") +toNumber("12.12.12"); //"12.12.12") +toNumber("0x2f"); //47) +toNumber("-0x2f"); //-47) +toNumber("0x2f", { hex : true}); //47) +toNumber("-0x2f", { hex : true}); //-47) +toNumber("0x2f", { hex : false}); //"0x2f") +toNumber("-0x2f", { hex : false}); //"-0x2f") +toNumber("06"); //6) +toNumber("06", { leadingZeros : true}); //6) +toNumber("06", { leadingZeros : false}); //"06") + +toNumber("006"); //6) +toNumber("006", { leadingZeros : true}); //6) +toNumber("006", { leadingZeros : false}); //"006") +toNumber("0.0"); //0) +toNumber("00.00"); //0) +toNumber("0.06"); //0.06) +toNumber("00.6"); //0.6) +toNumber(".006"); //0.006) +toNumber("6.0"); //6) +toNumber("06.0"); //6) + +toNumber("0.0", { leadingZeros : false}); //0) +toNumber("00.00", { leadingZeros : false}); //"00.00") +toNumber("0.06", { leadingZeros : false}); //0.06) +toNumber("00.6", { leadingZeros : false}); //"00.6") +toNumber(".006", { leadingZeros : false}); //0.006) +toNumber("6.0" , { leadingZeros : false}); //6) +toNumber("06.0" , { leadingZeros : false}); //"06.0") +toNumber("-06"); //-6) +toNumber("-06", { leadingZeros : true}); //-6) +toNumber("-06", { leadingZeros : false}); //"-06") + +toNumber("-0.0"); //-0) +toNumber("-00.00"); //-0) +toNumber("-0.06"); //-0.06) +toNumber("-00.6"); //-0.6) +toNumber("-.006"); //-0.006) +toNumber("-6.0"); //-6) +toNumber("-06.0"); //-6) + +toNumber("-0.0" , { leadingZeros : false}); //-0) +toNumber("-00.00", { leadingZeros : false}); //"-00.00") +toNumber("-0.06", { leadingZeros : false}); //-0.06) +toNumber("-00.6", { leadingZeros : false}); //"-00.6") +toNumber("-.006", {leadingZeros : false}); //-0.006) +toNumber("-6.0" , { leadingZeros : false}); //-6) +toNumber("-06.0" , { leadingZeros : false}); //"-06.0") +toNumber("420926189200190257681175017717") ; //4.209261892001902e+29) +toNumber("000000000000000000000000017717" , { leadingZeros : false}); //"000000000000000000000000017717") +toNumber("000000000000000000000000017717" , { leadingZeros : true}); //17717) +toNumber("01.0e2" , { leadingZeros : false}); //"01.0e2") +toNumber("-01.0e2" , { leadingZeros : false}); //"-01.0e2") +toNumber("01.0e2") ; //100) +toNumber("-01.0e2") ; //-100) +toNumber("1.0e2") ; //100) + +toNumber("-1.0e2") ; //-100) +toNumber("1.0e-2"); //0.01) + +toNumber("+1212121212"); // 1212121212 +toNumber("+1212121212", { skipLike: /\+[0-9]{10}/} )); //"+1212121212" + +toNumber("1e1000", { unicode: true, infinity: "original" }); //"1e1000" +toNumber("1000", { unicode: true }); //1000 +toNumber("1000", { unicode: false }); //"1000" +``` + +Supported Options +```js +hex: true, //when hexadecimal string should be parsed +leadingZeros: true, //when number with leading zeros like 08 should be parsed. 0.0 is not impacted +eNotation: true, //when number with eNotation or number parsed in eNotation should be considered +skipLike: /regex/ //when string should not be parsed when it matches the specified regular expression +infinity: "original", // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) +unicode: false, //when number with unicode numerals should be parsed +``` + + +# Try out our other work + +WishIn - You need it if negative thoughts take over all the time
+ diff --git a/node_modules/strnum/package.json b/node_modules/strnum/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9a0cf14be8af9b84c109f5d2ac2022329bd3f8a0 --- /dev/null +++ b/node_modules/strnum/package.json @@ -0,0 +1,35 @@ +{ + "name": "strnum", + "version": "2.4.0", + "description": "Parse String to Number based on configuration", + "type": "module", + "main": "strnum.js", + "scripts": { + "test": "jasmine tests/*_test.js" + }, + "keywords": [ + "string", + "number", + "parse", + "convert" + ], + "repository": { + "type": "git", + "url": "https://github.com/NaturalIntelligence/strnum" + }, + "author": "Amit Gupta (https://solothought.work/)", + "license": "MIT", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "devDependencies": { + "@byspec/numbers": "^0.1.1", + "jasmine": "^5.6.0" + }, + "dependencies": { + "anynum": "^1.0.0" + } +} \ No newline at end of file diff --git a/node_modules/strnum/strnum.js b/node_modules/strnum/strnum.js new file mode 100644 index 0000000000000000000000000000000000000000..402436fac9b797670818c244fd45251cb8f6d1b5 --- /dev/null +++ b/node_modules/strnum/strnum.js @@ -0,0 +1,171 @@ +const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/; +const binRegex = /^0b[01]+$/; +const octRegex = /^0o[0-7]+$/; +const numRegex = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/; + +import anynum from "anynum"; + +const consider = { + hex: true, + binary: false, + octal: false, + leadingZeros: true, + decimalPoint: "\.", + eNotation: true, + //skipLike: /regex/, + infinity: "original", // "null", "infinity" (Infinity type), "string" ("Infinity" (the string literal)) + unicode: false, +}; + +export default function toNumber(str, options = {}) { + options = Object.assign({}, consider, options); + if (!str || typeof str !== "string") return str; + + let trimmedStr = str.trim(); + + if (trimmedStr.length === 0) return str; + else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str; + else if (trimmedStr === "0") return 0; + + if (options.unicode) { + trimmedStr = anynum(trimmedStr); + if (trimmedStr === "0") return 0; // re-check after normalization + } + if (options.hex && hexRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 16); + } else if (options.binary && binRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 2); + } else if (options.octal && octRegex.test(trimmedStr)) { + return parse_int(trimmedStr, 8); + } else if (!isFinite(trimmedStr)) { //Infinity + return handleInfinity(str, Number(trimmedStr), options); + } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation + return resolveEnotation(str, trimmedStr, options); + } else { + //separate negative sign, leading zeros, and rest number + const match = numRegex.exec(trimmedStr); + // +00.123 => [ , '+', '00', '.123', .. + if (match) { + const sign = match[1] || ""; + const leadingZeros = match[2]; + let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros + const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000. + str[leadingZeros.length + 1] === "." + : str[leadingZeros.length] === "."; + + //trim ending zeros for floating number + if (!options.leadingZeros //leading zeros are not allowed + && (leadingZeros.length > 1 + || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) { + // 00, 00.3, +03.24, 03, 03.24 + return str; + } + else {//no leading zeros or leading zeros are allowed + const num = Number(trimmedStr); + const parsedStr = String(num); + + if (num === 0) return num; + if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation + if (options.eNotation) return num; + else return str; + } else if (trimmedStr.indexOf(".") !== -1) { //floating number + if (parsedStr === "0") return num; //0.0 + else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000 + else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num; + else return str; + } + + let n = leadingZeros ? numTrimmedByZeros : trimmedStr; + if (leadingZeros) { + // -009 => -9 + return (n === parsedStr) || (sign + n === parsedStr) ? num : str + } else { + // +9 + return (n === parsedStr) || (n === sign + parsedStr) ? num : str + } + } + } else { //non-numeric string + return str; + } + } +} + +const eNotationRegx = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/; +function resolveEnotation(str, trimmedStr, options) { + if (!options.eNotation) return str; + const notation = trimmedStr.match(eNotationRegx); + if (notation) { + let sign = notation[1] || ""; + const eChar = notation[3].indexOf("e") === -1 ? "E" : "e"; + const leadingZeros = notation[2]; + const eAdjacentToLeadingZeros = sign ? // 0E. + str[leadingZeros.length + 1] === eChar + : str[leadingZeros.length] === eChar; + + if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str; + else if (leadingZeros.length === 1 + && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) { + return Number(trimmedStr); + } else if (leadingZeros.length > 0) { + // Has leading zeros — only accept if leadingZeros option allows it + if (options.leadingZeros && !eAdjacentToLeadingZeros) { + trimmedStr = (notation[1] || "") + notation[3]; + return Number(trimmedStr); + } else return str; + } else { + // No leading zeros — always valid e-notation, parse it + return Number(trimmedStr); + } + } else { + return str; + } +} + +/** + * + * @param {string} numStr without leading zeros + * @returns + */ +function trimZeros(numStr) { + if (numStr && numStr.indexOf(".") !== -1) {//float + numStr = numStr.replace(/0+$/, ""); //remove ending zeros + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substring(0, numStr.length - 1); + return numStr; + } + return numStr; +} + +function parse_int(numStr, base) { + const str = numStr.trim(); + if (base === 2 || base === 8) numStr = str.substring(2); + + if (parseInt) return parseInt(numStr, base); + else if (Number.parseInt) return Number.parseInt(numStr, base); + else if (window && window.parseInt) return window.parseInt(numStr, base); + else throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); +} + +/** + * Handle infinite values based on user option + * @param {string} str - original input string + * @param {number} num - parsed number (Infinity or -Infinity) + * @param {object} options - user options + * @returns {string|number|null} based on infinity option + */ +function handleInfinity(str, num, options) { + const isPositive = num === Infinity; + + switch (options.infinity.toLowerCase()) { + case "null": + return null; + case "infinity": + return num; // Return Infinity or -Infinity + case "string": + return isPositive ? "Infinity" : "-Infinity"; + case "original": + default: + return str; // Return original string like "1e1000" + } +} \ No newline at end of file diff --git a/node_modules/strtok3/LICENSE.txt b/node_modules/strtok3/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e35e50810518d587fd5405c7821c766529d20e5 --- /dev/null +++ b/node_modules/strtok3/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2026 Borewit + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/strtok3/README.md b/node_modules/strtok3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2772c264d33b70f251354b2b0eec7af4382a29a7 --- /dev/null +++ b/node_modules/strtok3/README.md @@ -0,0 +1,399 @@ +[![Node.js CI](https://github.com/Borewit/strtok3/actions/workflows/ci.yml/badge.svg)](https://github.com/Borewit/strtok3/actions/workflows/ci.yml) +[![CodeQL](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml/badge.svg?branch=master)](https://github.com/Borewit/strtok3/actions/workflows/codeql.yml) +[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3) +[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30) +[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&utm_medium=referral&utm_content=Borewit/strtok3&utm_campaign=Badge_Grade) +# strtok3 + +A promise based streaming [*tokenizer*](#tokenizer-object) for [Node.js](http://nodejs.org) and browsers. + +The `strtok3` module provides several methods for creating a [*tokenizer*](#tokenizer-object) from various input sources. +Designed for: +* Seamless support in streaming environments. +* Efficiently decode binary data, strings, and numbers. +* Reading [predefined](https://github.com/Borewit/token-types) or custom tokens. +* Offering [*tokenizers*](#tokenizer-object) for reading from [files](#method-strtok3fromfile), [streams](#fromstream-function) or [Uint8Arrays](#frombuffer-function). + +### Features +`strtok3` can read from: +* Files, using a file path as input. +* Node.js [streams](https://nodejs.org/api/stream.html). +* [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). +* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http). +* [Amazon S3](https://aws.amazon.com/s3) chunks with [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3). + +## Installation + +```sh +npm install strtok3 +``` + +### Compatibility + +Starting with version 7, the module has migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). +The distributed JavaScript codebase is compliant with the [ECMAScript 2020 (11th Edition)](https://en.wikipedia.org/wiki/ECMAScript_version_history#11th_Edition_%E2%80%93_ECMAScript_2020) standard. + +Requires a modern browser, Node.js (V8) ≥ 18 engine or Bun (JavaScriptCore) ≥ 1.2. + +For TypeScript CommonJs backward compatibility, you can use [load-esm](https://github.com/Borewit/load-esm). + +> [!NOTE] +> This module requires a [Node.js ≥ 16](https://nodejs.org/en/about/previous-releases) engine. +> It can also be used in a browser environment when bundled with a module bundler. + +## Support the Project +If you find this project useful and would like to support its development, consider sponsoring or contributing: + +- [Become a sponsor to Borewit](https://github.com/sponsors/Borewit) + +- Buy me a coffee: + + Buy me A coffee + +## API Documentation + +### strtok3 methods + +Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer-object): +- [fromBlob](#fromblob-function) +- [fromBuffer](#frombuffer-function) +- [fromFile](#fromfile-function)* +- [fromStream](#fromstream-function)* +- [fromWebStream](#fromwebstream-function) + +> [!NOTE] +> `fromFile` and `fromStream` only available when importing this module with Node.js + +All methods return a [`Tokenizer`](#tokenizer-object), either directly or via a promise. + +#### `fromBlob()` function + +Create a tokenizer from a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + +```ts +function fromBlob(blob: Blob, options?: ITokenizerOptions): BlobTokenizer +``` + +| Parameter | Optional | Type | Description | +|-----------|-----------|---------------------------------------------------|----------------------------------------------------------------------------------------| +| blob | no | [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) | [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [File](https://developer.mozilla.org/en-US/docs/Web/API/File) to read from | +| options | yes | [ITokenizerOptions](#ITokenizerOptions) | Tokenizer options | + +Returns a [*tokenizer*](#tokenizer-object). + +```js +import { fromBlob } from 'strtok3'; +import { openAsBlob } from 'node:fs'; +import * as Token from 'token-types'; + +async function parse() { + const blob = await openAsBlob('somefile.bin'); + + const tokenizer = fromBlob(blob); + + const myUint8Number = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myUint8Number}`); +} + +parse(); + +``` + +#### `fromBuffer()` function + +Create a tokenizer from memory ([Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) or Node.js [Buffer](https://nodejs.org/api/buffer.html)). + +```ts +function fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer +``` + +| Parameter | Optional | Type | Description | +|------------|----------|--------------------------------------------------|-----------------------------------| +| uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Buffer or Uint8Array to read from | +| options | yes | [ITokenizerOptions](#ITokenizerOptions) | Tokenizer options | + +Returns a [*tokenizer*](#tokenizer-object). + +```js +import { fromBuffer } from 'strtok3'; +import * as Token from 'token-types'; + +const tokenizer = fromBuffer(buffer); + +async function parse() { + const myUint8Number = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myUint8Number}`); +} + +parse(); +``` + +#### `fromFile` function + +Creates a [*tokenizer*](#tokenizer-object) from a local file. + +```ts +function fromFile(sourceFilePath: string): Promise +``` + +| Parameter | Type | Description | +|----------------|----------|----------------------------| +| sourceFilePath | `string` | Path to file to read from | + +> [!NOTE] +> - Only available for Node.js engines +> - `fromFile` automatically embeds [file-information](#file-information) + +A Promise resolving to a [*tokenizer*](#tokenizer-object) which can be used to parse a file. + +```js +import { fromFile } from 'strtok3'; +import * as Token from 'token-types'; + +async function parse() { + const tokenizer = await fromFile('somefile.bin'); + try { + const myNumber = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myNumber}`); + } finally { + tokenizer.close(); // Close the file + } +} + +parse(); + + +``` + +#### `fromWebStream()` function + +Create a tokenizer from a [WHATWG ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream). + +```ts +function fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer +``` + +| Parameter | Optional | Type | Description | +|----------------|----------|--------------------------------------------------------------------------|------------------------------------| +| webStream | no | [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) | WHATWG ReadableStream to read from | +| options | yes | [ITokenizerOptions](#ITokenizerOptions) | Tokenizer options | + +Returns a [*tokenizer*](#tokenizer-object). + +```js +import { fromWebStream } from 'strtok3'; +import * as Token from 'token-types'; + +async function parse() { + const tokenizer = fromWebStream(readableStream); + try { + const myUint8Number = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myUint8Number}`); + } finally { + await tokenizer.close(); + } +} + +parse(); +``` + +### `Tokenizer` object +The *tokenizer* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), allowing _reading_ or _peeking_ from the stream. +It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http); + +#### Key Features: + +- Supports seeking within the stream using `tokenizer.ignore()`. +- Offers `peek` methods to preview data without advancing the read pointer. +- Maintains the read position via tokenizer.position. + +#### Tokenizer functions + +_Read_ methods advance the stream pointer, while _peek_ methods do not. + +There are two kind of functions: +1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer-object). The position of the *tokenizer-stream* will advance with the size of the token. +2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead. + +#### `readBuffer` function + +Read data from the _tokenizer_ into provided "buffer" (`Uint8Array`). +`readBuffer(buffer, options?)` + +```ts +readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; +``` + +| Parameter | Type | Description | +|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| buffer | [Buffer](https://nodejs.org/api/buffer.html) | Uint8Array | Target buffer to write the data read to | +| options | [IReadChunkOptions](#ireadchunkoptions-interface) | An integer specifying the number of bytes to read | + +Return promise with number of bytes read. +The number of bytes read may be less than requested if the `mayBeLess` flag is set. + +#### `peekBuffer` function + +Peek (read ahead), from [*tokenizer*](#tokenizer-object), into the buffer without advancing the stream pointer. + +```ts +peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; +``` + +| Parameter | Type | Description | +|------------|-----------------------------------------|-----------------------------------------------------| +| buffer | Buffer | Uint8Array | Target buffer to write the data read (peeked) to. | +| options | [IReadChunkOptions](#ireadchunkoptions-interface) | An integer specifying the number of bytes to read. | | + +Return value `Promise` Promise with number of bytes read. The number of bytes read may be less if the `mayBeLess` flag was set. + +#### `readToken` function + +Read a *token* from the tokenizer-stream. + +```ts +readToken(token: IGetToken, position: number = this.position): Promise +``` + +| Parameter | Type | Description | +|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- | +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return value `Promise`. Promise with number of bytes read. The number of bytes read maybe if less, `mayBeLess` flag was set. + +#### `peek` function + +Peek a *token* from the [*tokenizer*](#tokenizer-object). + +```ts +peekToken(token: IGetToken, position: number = this.position): Promise +``` + +| Parameter | Type | Description | +|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------| +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return a promise with the token value peeked from the [*tokenizer*](#tokenizer-object). + +#### `readNumber` function + +Read a numeric [*token*](#token) from the [*tokenizer*](#tokenizer-object). + +```ts +readNumber(token: IToken): Promise +``` + +| Parameter | Type | Description | +|------------|---------------------------------|----------------------------------------------------| +| token | [IGetToken](#IGetToken) | Numeric token to read from the tokenizer-stream. | + +A promise resolving to a numeric value read and decoded from the *tokenizer-stream*. + +#### `ignore` function + +Advance the offset pointer with the token number of bytes provided. + +```ts +ignore(length: number): Promise +``` + +| Parameter | Type | Description | +|------------|--------|------------------------------------------------------------------| +| length | number | Number of bytes to ignore. Will advance the `tokenizer.position` | + +A promise resolving to the number of bytes ignored from the *tokenizer-stream*. + +#### `close` function +Clean up resources, such as closing a file pointer if applicable. + +#### `Tokenizer` attributes + +- `fileInfo` + + Optional attribute describing the file information, see [IFileInfo](#IFileInfo) + +- `position` + + Pointer to the current position in the [*tokenizer*](#tokenizer-object) stream. + If a *position* is provided to a _read_ or _peek_ method, is should be, at least, equal or greater than this value. + +### `IReadChunkOptions` interface + +Each attribute is optional: + +| Attribute | Type | Description | +|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| length | number | Requested number of bytes to read. | +| position | number | Position where to peek from the file. If position is null, data will be read from the [current file position](#attribute-tokenizerposition). Position may not be less then [tokenizer.position](#attribute-tokenizerposition) | +| mayBeLess | boolean | If and only if set, will not throw an EOF error if less than the requested `mayBeLess` could be read. | + +Example usage: +```js + tokenizer.peekBuffer(buffer, {mayBeLess: true}); +``` + +### `IFileInfo` interface + +Provides optional metadata about the file being tokenized. + +| Attribute | Type | Description | +|-----------|---------|---------------------------------------------------------------------------------------------------| +| size | number | File size in bytes | +| mimeType | string | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. | +| path | string | File path | +| url | string | File URL | + +### `Token` object + +The *token* is basically a description of what to read from the [*tokenizer-stream*](#tokenizer-object). +A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types). + +A token is something which implements the following interface: +```ts +export interface IGetToken { + + /** + * Length in bytes of encoded value + */ + len: number; + + /** + * Decode value from buffer at offset + * @param buf Buffer to read the decoded value from + * @param off Decode offset + */ + get(buf: Uint8Array, off: number): T; +} +``` +The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer. +The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type. + +### Working with Web-API readable stream +To convert a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream]((https://nodejs.org/api/stream.html#stream_readable_streams)), you can use [readable-web-to-node-stream](https://github.com/Borewit/readable-web-to-node-stream) to convert one in another. + +```js +import { fromWebStream } from 'strtok3'; +import { ReadableWebToNodeStream } from 'readable-web-to-node-stream'; + +(async () => { + + const response = await fetch(url); + const readableWebStream = response.body; // Web-API readable stream + const webStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream + + const tokenizer = fromWebStream(webStream); // And we now have tokenizer in a web environment +})(); +``` + +## Dependencies + +Dependencies: +- [@tokenizer/token](https://github.com/Borewit/tokenizer-token): Provides token definitions and utilities used by `strtok3` for interpreting binary data. + +## Licence + +This project is licensed under the [MIT License](LICENSE.txt). Feel free to use, modify, and distribute as needed. diff --git a/node_modules/strtok3/lib/AbstractTokenizer.d.ts b/node_modules/strtok3/lib/AbstractTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01b540eb84e7dca12b2c630484812e71c38e44ac --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.d.ts @@ -0,0 +1,76 @@ +import type { ITokenizer, IFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js'; +import type { IGetToken, IToken } from '@tokenizer/token'; +interface INormalizedReadChunkOptions extends IReadChunkOptions { + length: number; + position: number; + mayBeLess?: boolean; +} +/** + * Core tokenizer + */ +export declare abstract class AbstractTokenizer implements ITokenizer { + private onClose?; + private numBuffer; + abstract fileInfo: IFileInfo; + /** + * Tokenizer-stream position + */ + position: number; + /** + * Constructor + * @param options Tokenizer options + * @protected + */ + protected constructor(options?: ITokenizerOptions); + abstract supportsRandomAccess(): boolean; + /** + * Read buffer from tokenizer + * @param buffer - Target buffer to fill with data read from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + abstract readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Target buffer to fill with data peeked from the tokenizer-stream + * @param options - Peek behaviour options + * @returns Promise with number of bytes read + */ + abstract peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + peekToken(token: IGetToken, position?: number): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IToken): Promise; + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore. Must be ≥ 0. + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + ignore(length: number): Promise; + close(): Promise; + protected normalizeOptions(uint8Array: Uint8Array, options?: IReadChunkOptions): INormalizedReadChunkOptions; + abort(): Promise; +} +export {}; diff --git a/node_modules/strtok3/lib/AbstractTokenizer.js b/node_modules/strtok3/lib/AbstractTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..eaa8a01c036c2c2fb81897c242ecc1bcbedbea75 --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.js @@ -0,0 +1,111 @@ +import { EndOfStreamError } from './stream/index.js'; +/** + * Core tokenizer + */ +export class AbstractTokenizer { + /** + * Constructor + * @param options Tokenizer options + * @protected + */ + constructor(options) { + this.numBuffer = new Uint8Array(8); + /** + * Tokenizer-stream position + */ + this.position = 0; + this.onClose = options?.onClose; + if (options?.abortSignal) { + options.abortSignal.addEventListener('abort', () => { + this.abort(); + }); + } + } + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + async readToken(token, position = this.position) { + const uint8Array = new Uint8Array(token.len); + const len = await this.readBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + async peekToken(token, position = this.position) { + const uint8Array = new Uint8Array(token.len); + const len = await this.peekBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async readNumber(token) { + const len = await this.readBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async peekNumber(token) { + const len = await this.peekBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore. Must be ≥ 0. + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + async ignore(length) { + if (length < 0) { + throw new RangeError('ignore length must be ≥ 0 bytes'); + } + if (this.fileInfo.size !== undefined) { + const bytesLeft = this.fileInfo.size - this.position; + if (length > bytesLeft) { + this.position += bytesLeft; + return bytesLeft; + } + } + this.position += length; + return length; + } + async close() { + await this.abort(); + await this.onClose?.(); + } + normalizeOptions(uint8Array, options) { + if (!this.supportsRandomAccess() && options && options.position !== undefined && options.position < this.position) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + return { + ...{ + mayBeLess: false, + offset: 0, + length: uint8Array.length, + position: this.position + }, ...options + }; + } + abort() { + return Promise.resolve(); // Ignore abort signal + } +} diff --git a/node_modules/strtok3/lib/BlobTokenizer.d.ts b/node_modules/strtok3/lib/BlobTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e0bc9852fb6027a32f13ae942bf98113c5a0037 --- /dev/null +++ b/node_modules/strtok3/lib/BlobTokenizer.d.ts @@ -0,0 +1,29 @@ +import type { ITokenizerOptions, IReadChunkOptions, IRandomAccessFileInfo, IRandomAccessTokenizer } from './types.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export declare class BlobTokenizer extends AbstractTokenizer implements IRandomAccessTokenizer { + private blob; + fileInfo: IRandomAccessFileInfo; + /** + * Construct BufferTokenizer + * @param blob - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(blob: Blob, options?: ITokenizerOptions); + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer + * @param options - Read behaviour options + * @returns {Promise} + */ + peekBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; + supportsRandomAccess(): boolean; + setPosition(position: number): void; +} diff --git a/node_modules/strtok3/lib/BlobTokenizer.js b/node_modules/strtok3/lib/BlobTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..f68dfa243f1b30a77a84cabef4255bf0f3a559fe --- /dev/null +++ b/node_modules/strtok3/lib/BlobTokenizer.js @@ -0,0 +1,53 @@ +import { EndOfStreamError } from './stream/index.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export class BlobTokenizer extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param blob - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(blob, options) { + super(options); + this.blob = blob; + this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: blob.size, mimeType: blob.type } }; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options?.position) { + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(buffer, options) { + const normOptions = this.normalizeOptions(buffer, options); + const bytes2read = Math.min(this.blob.size - normOptions.position, normOptions.length); + if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + const arrayBuffer = await this.blob.slice(normOptions.position, normOptions.position + bytes2read).arrayBuffer(); + buffer.set(new Uint8Array(arrayBuffer)); + return bytes2read; + } + close() { + return super.close(); + } + supportsRandomAccess() { + return true; + } + setPosition(position) { + this.position = position; + } +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.d.ts b/node_modules/strtok3/lib/BufferTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e5c4071e3f5806a470232d9d1dcd0848f81e8ba --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.d.ts @@ -0,0 +1,29 @@ +import type { ITokenizerOptions, IReadChunkOptions, IRandomAccessFileInfo, IRandomAccessTokenizer } from './types.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export declare class BufferTokenizer extends AbstractTokenizer implements IRandomAccessTokenizer { + private uint8Array; + fileInfo: IRandomAccessFileInfo; + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(uint8Array: Uint8Array, options?: ITokenizerOptions); + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; + supportsRandomAccess(): boolean; + setPosition(position: number): void; +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.js b/node_modules/strtok3/lib/BufferTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..eec03746e02fd7af5e1ba7789be59dda25f46e68 --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.js @@ -0,0 +1,52 @@ +import { EndOfStreamError } from './stream/index.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export class BufferTokenizer extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(uint8Array, options) { + super(options); + this.uint8Array = uint8Array; + this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: uint8Array.length } }; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options?.position) { + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length); + if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read)); + return bytes2read; + } + close() { + return super.close(); + } + supportsRandomAccess() { + return true; + } + setPosition(position) { + this.position = position; + } +} diff --git a/node_modules/strtok3/lib/FileTokenizer.d.ts b/node_modules/strtok3/lib/FileTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..98229ffd5674d0eb23ec3082879d357dbfaf0c7d --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.d.ts @@ -0,0 +1,37 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import type { IRandomAccessTokenizer, IRandomAccessFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js'; +import { type FileHandle } from 'node:fs/promises'; +interface IFileTokenizerOptions extends ITokenizerOptions { + /** + * Pass additional file information to the tokenizer + */ + fileInfo: IRandomAccessFileInfo; +} +export declare class FileTokenizer extends AbstractTokenizer implements IRandomAccessTokenizer { + private fileHandle; + fileInfo: IRandomAccessFileInfo; + /** + * Create tokenizer from provided file path + * @param sourceFilePath File path + */ + static fromFile(sourceFilePath: string): Promise; + protected constructor(fileHandle: FileHandle, options: IFileTokenizerOptions); + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; + setPosition(position: number): void; + supportsRandomAccess(): boolean; +} +export {}; diff --git a/node_modules/strtok3/lib/FileTokenizer.js b/node_modules/strtok3/lib/FileTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..1d5e7655da541ec0662665f926b2c737dfdbb4fa --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.js @@ -0,0 +1,61 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { EndOfStreamError } from './stream/index.js'; +import { open as fsOpen } from 'node:fs/promises'; +export class FileTokenizer extends AbstractTokenizer { + /** + * Create tokenizer from provided file path + * @param sourceFilePath File path + */ + static async fromFile(sourceFilePath) { + const fileHandle = await fsOpen(sourceFilePath, 'r'); + const stat = await fileHandle.stat(); + return new FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat.size } }); + } + constructor(fileHandle, options) { + super(options); + this.fileHandle = fileHandle; + this.fileInfo = options.fileInfo; + } + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + this.position = normOptions.position; + if (normOptions.length === 0) + return 0; + const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position); + this.position += res.bytesRead; + if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position); + if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + async close() { + await this.fileHandle.close(); + return super.close(); + } + setPosition(position) { + this.position = position; + } + supportsRandomAccess() { + return true; + } +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e78a83e1fe361b3a7864e007416a61ef35dc51fd --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts @@ -0,0 +1,34 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { type IStreamReader } from './stream/index.js'; +import type { IFileInfo, IReadChunkOptions, ITokenizerOptions } from './types.js'; +export declare class ReadStreamTokenizer extends AbstractTokenizer { + private streamReader; + fileInfo: IFileInfo; + /** + * Constructor + * @param streamReader stream-reader to read from + * @param options Tokenizer options + */ + constructor(streamReader: IStreamReader, options?: ITokenizerOptions); + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * @param length Number of bytes to ignore. Must be ≥ 0. + */ + ignore(length: number): Promise; + abort(): Promise; + close(): Promise; + supportsRandomAccess(): boolean; +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.js b/node_modules/strtok3/lib/ReadStreamTokenizer.js new file mode 100644 index 0000000000000000000000000000000000000000..7b0cf4a929136fc80fe0d8900086333859ce73ae --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.js @@ -0,0 +1,107 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { EndOfStreamError } from './stream/index.js'; +const maxBufferSize = 256000; +export class ReadStreamTokenizer extends AbstractTokenizer { + /** + * Constructor + * @param streamReader stream-reader to read from + * @param options Tokenizer options + */ + constructor(streamReader, options) { + super(options); + this.streamReader = streamReader; + this.fileInfo = options?.fileInfo ?? {}; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + await this.ignore(skipBytes); + return this.readBuffer(uint8Array, options); + } + if (skipBytes < 0) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + if (normOptions.length === 0) { + return 0; + } + const bytesRead = await this.streamReader.read(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess); + this.position += bytesRead; + if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + let bytesRead = 0; + if (normOptions.position) { + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + const skipBuffer = new Uint8Array(normOptions.length + skipBytes); + bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess }); + uint8Array.set(skipBuffer.subarray(skipBytes)); + return bytesRead - skipBytes; + } + if (skipBytes < 0) { + throw new Error('Cannot peek from a negative offset in a stream'); + } + } + if (normOptions.length > 0) { + try { + bytesRead = await this.streamReader.peek(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess); + } + catch (err) { + if (options?.mayBeLess && err instanceof EndOfStreamError) { + return 0; + } + throw err; + } + if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + } + return bytesRead; + } + /** + * @param length Number of bytes to ignore. Must be ≥ 0. + */ + async ignore(length) { + if (length < 0) { + throw new RangeError('ignore length must be ≥ 0 bytes'); + } + const bufSize = Math.min(maxBufferSize, length); + const buf = new Uint8Array(bufSize); + let totBytesRead = 0; + while (totBytesRead < length) { + const remaining = length - totBytesRead; + const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) }); + if (bytesRead < 0) { + return bytesRead; + } + totBytesRead += bytesRead; + } + return totBytesRead; + } + abort() { + return this.streamReader.abort(); + } + async close() { + return this.streamReader.close(); + } + supportsRandomAccess() { + return false; + } +} diff --git a/node_modules/strtok3/lib/core.d.ts b/node_modules/strtok3/lib/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fb2f7d5f88302bedff48584c15e390cbeaa2b5f --- /dev/null +++ b/node_modules/strtok3/lib/core.d.ts @@ -0,0 +1,40 @@ +import type { Readable } from 'node:stream'; +import { type AnyWebByteStream } from './stream/index.js'; +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { BufferTokenizer } from './BufferTokenizer.js'; +import type { ITokenizerOptions } from './types.js'; +import { BlobTokenizer } from './BlobTokenizer.js'; +export { EndOfStreamError, AbortError, type AnyWebByteStream } from './stream/index.js'; +export type { ITokenizer, IRandomAccessTokenizer, IFileInfo, IRandomAccessFileInfo, ITokenizerOptions, IReadChunkOptions, OnClose } from './types.js'; +export type { IToken, IGetToken } from '@tokenizer/token'; +export { AbstractTokenizer } from './AbstractTokenizer.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export declare function fromStream(stream: Readable, options?: ITokenizerOptions): ReadStreamTokenizer; +/** + * Construct ReadStreamTokenizer from given ReadableStream (WebStream API). + * Will set fileSize, if provided given Stream has set the .path property/ + * @param webStream - Read from Node.js Stream.Readable (must be a byte stream) + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export declare function fromWebStream(webStream: AnyWebByteStream, options?: ITokenizerOptions): ReadStreamTokenizer; +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export declare function fromBuffer(uint8Array: Uint8Array, options?: ITokenizerOptions): BufferTokenizer; +/** + * Construct ReadStreamTokenizer from given Blob. + * @param blob - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export declare function fromBlob(blob: Blob, options?: ITokenizerOptions): BlobTokenizer; diff --git a/node_modules/strtok3/lib/core.js b/node_modules/strtok3/lib/core.js new file mode 100644 index 0000000000000000000000000000000000000000..22f41cf82ecfd45d5b438203ef8797e82c88306c --- /dev/null +++ b/node_modules/strtok3/lib/core.js @@ -0,0 +1,62 @@ +import { StreamReader, makeWebStreamReader } from './stream/index.js'; +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { BufferTokenizer } from './BufferTokenizer.js'; +import { BlobTokenizer } from './BlobTokenizer.js'; +export { EndOfStreamError, AbortError } from './stream/index.js'; +export { AbstractTokenizer } from './AbstractTokenizer.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export function fromStream(stream, options) { + const streamReader = new StreamReader(stream); + const _options = options ?? {}; + const chainedClose = _options.onClose; + _options.onClose = async () => { + await streamReader.close(); + if (chainedClose) { + return chainedClose(); + } + }; + return new ReadStreamTokenizer(streamReader, _options); +} +/** + * Construct ReadStreamTokenizer from given ReadableStream (WebStream API). + * Will set fileSize, if provided given Stream has set the .path property/ + * @param webStream - Read from Node.js Stream.Readable (must be a byte stream) + * @param options - Tokenizer options + * @returns ReadStreamTokenizer + */ +export function fromWebStream(webStream, options) { + const webStreamReader = makeWebStreamReader(webStream); + const _options = options ?? {}; + const chainedClose = _options.onClose; + _options.onClose = async () => { + await webStreamReader.close(); + if (chainedClose) { + return chainedClose(); + } + }; + return new ReadStreamTokenizer(webStreamReader, _options); +} +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export function fromBuffer(uint8Array, options) { + return new BufferTokenizer(uint8Array, options); +} +/** + * Construct ReadStreamTokenizer from given Blob. + * @param blob - Uint8Array to tokenize + * @param options - Tokenizer options + * @returns BufferTokenizer + */ +export function fromBlob(blob, options) { + return new BlobTokenizer(blob, options); +} diff --git a/node_modules/strtok3/lib/index.d.ts b/node_modules/strtok3/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6b34d82f906d5470041715619857d520da3d109 --- /dev/null +++ b/node_modules/strtok3/lib/index.d.ts @@ -0,0 +1,16 @@ +import type { Readable } from 'node:stream'; +import type { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { type ITokenizerOptions } from './core.js'; +import { FileTokenizer } from "./FileTokenizer.js"; +export { FileTokenizer } from './FileTokenizer.js'; +export * from './core.js'; +export type { IToken, IGetToken } from '@tokenizer/token'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param options - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export declare function fromStream(stream: Readable, options?: ITokenizerOptions): Promise; +export declare const fromFile: typeof FileTokenizer.fromFile; diff --git a/node_modules/strtok3/lib/index.js b/node_modules/strtok3/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..aef7d6d538ee99456de2cccab9834d4b2b74834a --- /dev/null +++ b/node_modules/strtok3/lib/index.js @@ -0,0 +1,22 @@ +import { stat as fsStat } from 'node:fs/promises'; +import { fromStream as coreFromStream } from './core.js'; +import { FileTokenizer } from "./FileTokenizer.js"; +export { FileTokenizer } from './FileTokenizer.js'; +export * from './core.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param options - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export async function fromStream(stream, options) { + const rst = coreFromStream(stream, options); + if (stream.path) { + const stat = await fsStat(stream.path); + rst.fileInfo.path = stream.path; + rst.fileInfo.size = stat.size; + } + return rst; +} +export const fromFile = FileTokenizer.fromFile; diff --git a/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts b/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..55f69a2e7b90c6561b6a22932bf038d8a979d3fd --- /dev/null +++ b/node_modules/strtok3/lib/stream/AbstractStreamReader.d.ts @@ -0,0 +1,54 @@ +export interface IStreamReader { + /** + * Peak ahead (peek) from stream. Subsequent read or peeks will return the same data. + * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - Allow the read to complete, without the buffer being fully filled (length may be smaller) + * @returns Number of bytes peeked. If `maybeLess` is set, this shall be the `uint8Array.length`. + */ + peek(uint8Array: Uint8Array, mayBeLess?: boolean): Promise; + /** + * Read from stream the stream. + * @param uint8Array - Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - Allow the read to complete, without the buffer being fully filled (length may be smaller) + * @returns Number of actually bytes read. If `maybeLess` is set, this shall be the `uint8Array.length`. + */ + read(uint8Array: Uint8Array, mayBeLess?: boolean): Promise; + close(): Promise; + /** + * Abort any active asynchronous operation are active, abort those before they may have completed. + */ + abort(): Promise; +} +export declare abstract class AbstractStreamReader implements IStreamReader { + protected endOfStream: boolean; + protected interrupted: boolean; + /** + * Store peeked data + * @type {Array} + */ + protected peekQueue: Uint8Array[]; + peek(uint8Array: Uint8Array, mayBeLess?: boolean): Promise; + read(buffer: Uint8Array, mayBeLess?: boolean): Promise; + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @returns Number of bytes read + */ + protected readFromPeekBuffer(buffer: Uint8Array): number; + readRemainderFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected abstract readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + /** + * abort synchronous operations + */ + abstract close(): Promise; + /** + * Abort any active asynchronous operation are active, abort those before they may have completed. + */ + abstract abort(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/AbstractStreamReader.js b/node_modules/strtok3/lib/stream/AbstractStreamReader.js new file mode 100644 index 0000000000000000000000000000000000000000..dd77385fdabda16f7686357f26cb33ca4f9c2194 --- /dev/null +++ b/node_modules/strtok3/lib/stream/AbstractStreamReader.js @@ -0,0 +1,71 @@ +import { EndOfStreamError, AbortError } from "./Errors.js"; +export class AbstractStreamReader { + constructor() { + this.endOfStream = false; + this.interrupted = false; + /** + * Store peeked data + * @type {Array} + */ + this.peekQueue = []; + } + async peek(uint8Array, mayBeLess = false) { + const bytesRead = await this.read(uint8Array, mayBeLess); + this.peekQueue.push(uint8Array.subarray(0, bytesRead)); // Put read data back to peek buffer + return bytesRead; + } + async read(buffer, mayBeLess = false) { + if (buffer.length === 0) { + return 0; + } + let bytesRead = this.readFromPeekBuffer(buffer); + if (!this.endOfStream) { + bytesRead += await this.readRemainderFromStream(buffer.subarray(bytesRead), mayBeLess); + } + if (bytesRead === 0 && !mayBeLess) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @returns Number of bytes read + */ + readFromPeekBuffer(buffer) { + let remaining = buffer.length; + let bytesRead = 0; + // consume peeked data first + while (this.peekQueue.length > 0 && remaining > 0) { + const peekData = this.peekQueue.pop(); // Front of queue + if (!peekData) + throw new Error('peekData should be defined'); + const lenCopy = Math.min(peekData.length, remaining); + buffer.set(peekData.subarray(0, lenCopy), bytesRead); + bytesRead += lenCopy; + remaining -= lenCopy; + if (lenCopy < peekData.length) { + // remainder back to queue + this.peekQueue.push(peekData.subarray(lenCopy)); + } + } + return bytesRead; + } + async readRemainderFromStream(buffer, mayBeLess) { + let bytesRead = 0; + // Continue reading from stream if required + while (bytesRead < buffer.length && !this.endOfStream) { + if (this.interrupted) { + throw new AbortError(); + } + const chunkLen = await this.readFromStream(buffer.subarray(bytesRead), mayBeLess); + if (chunkLen === 0) + break; + bytesRead += chunkLen; + } + if (!mayBeLess && bytesRead < buffer.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } +} diff --git a/node_modules/strtok3/lib/stream/Deferred.d.ts b/node_modules/strtok3/lib/stream/Deferred.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..03d2dbbb68d7ff117c5626dbfb40946f71882351 --- /dev/null +++ b/node_modules/strtok3/lib/stream/Deferred.d.ts @@ -0,0 +1,6 @@ +export declare class Deferred { + promise: Promise; + resolve: (value: T) => void; + reject: (reason: Error) => void; + constructor(); +} diff --git a/node_modules/strtok3/lib/stream/Deferred.js b/node_modules/strtok3/lib/stream/Deferred.js new file mode 100644 index 0000000000000000000000000000000000000000..c7e42a62ad978a173bcc6df7501a00ef7dfa5160 --- /dev/null +++ b/node_modules/strtok3/lib/stream/Deferred.js @@ -0,0 +1,10 @@ +export class Deferred { + constructor() { + this.resolve = () => null; + this.reject = () => null; + this.promise = new Promise((resolve, reject) => { + this.reject = reject; + this.resolve = resolve; + }); + } +} diff --git a/node_modules/strtok3/lib/stream/Errors.d.ts b/node_modules/strtok3/lib/stream/Errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0d2a8d78209dbd2e85918ecbc51be16c7f36e3e --- /dev/null +++ b/node_modules/strtok3/lib/stream/Errors.d.ts @@ -0,0 +1,10 @@ +export declare const defaultMessages = "End-Of-Stream"; +/** + * Thrown on read operation of the end of file or stream has been reached + */ +export declare class EndOfStreamError extends Error { + constructor(); +} +export declare class AbortError extends Error { + constructor(message?: string); +} diff --git a/node_modules/strtok3/lib/stream/Errors.js b/node_modules/strtok3/lib/stream/Errors.js new file mode 100644 index 0000000000000000000000000000000000000000..7fa17793c79f706b1423beef74ab13cab1735ede --- /dev/null +++ b/node_modules/strtok3/lib/stream/Errors.js @@ -0,0 +1,16 @@ +export const defaultMessages = 'End-Of-Stream'; +/** + * Thrown on read operation of the end of file or stream has been reached + */ +export class EndOfStreamError extends Error { + constructor() { + super(defaultMessages); + this.name = "EndOfStreamError"; + } +} +export class AbortError extends Error { + constructor(message = "The operation was aborted") { + super(message); + this.name = "AbortError"; + } +} diff --git a/node_modules/strtok3/lib/stream/StreamReader.d.ts b/node_modules/strtok3/lib/stream/StreamReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd163f90cfb7770d8c16ce06092a0c5687dcbd02 --- /dev/null +++ b/node_modules/strtok3/lib/stream/StreamReader.d.ts @@ -0,0 +1,29 @@ +import type { Readable } from 'node:stream'; +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +/** + * Node.js Readable Stream Reader + * Ref: https://nodejs.org/api/stream.html#readable-streams + */ +export declare class StreamReader extends AbstractStreamReader { + private s; + /** + * Deferred used for postponed read request (as not data is yet available to read) + */ + private deferred; + constructor(s: Readable); + /** + * Read chunk from stream + * @param buffer Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @returns Number of bytes read + */ + protected readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + /** + * Process deferred read request + * @param request Deferred read request + */ + private readDeferred; + private reject; + abort(): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/StreamReader.js b/node_modules/strtok3/lib/stream/StreamReader.js new file mode 100644 index 0000000000000000000000000000000000000000..44c161656e4055c3e67c1883d5b3faa1b0a2e1af --- /dev/null +++ b/node_modules/strtok3/lib/stream/StreamReader.js @@ -0,0 +1,83 @@ +import { AbortError, } from './Errors.js'; +import { Deferred } from './Deferred.js'; +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +/** + * Node.js Readable Stream Reader + * Ref: https://nodejs.org/api/stream.html#readable-streams + */ +export class StreamReader extends AbstractStreamReader { + constructor(s) { + super(); + this.s = s; + /** + * Deferred used for postponed read request (as not data is yet available to read) + */ + this.deferred = null; + if (!s.read || !s.once) { + throw new Error('Expected an instance of stream.Readable'); + } + this.s.once('end', () => { + this.endOfStream = true; + if (this.deferred) { + this.deferred.resolve(0); + } + }); + this.s.once('error', err => this.reject(err)); + this.s.once('close', () => this.abort()); + } + /** + * Read chunk from stream + * @param buffer Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @returns Number of bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + const readBuffer = this.s.read(buffer.length); + if (readBuffer) { + buffer.set(readBuffer); + return readBuffer.length; + } + const request = { + buffer, + mayBeLess, + deferred: new Deferred() + }; + this.deferred = request.deferred; + this.s.once('readable', () => { + this.readDeferred(request); + }); + return request.deferred.promise; + } + /** + * Process deferred read request + * @param request Deferred read request + */ + readDeferred(request) { + const readBuffer = this.s.read(request.buffer.length); + if (readBuffer) { + request.buffer.set(readBuffer); + request.deferred.resolve(readBuffer.length); + this.deferred = null; + } + else { + this.s.once('readable', () => { + this.readDeferred(request); + }); + } + } + reject(err) { + this.interrupted = true; + if (this.deferred) { + this.deferred.reject(err); + this.deferred = null; + } + } + async abort() { + this.reject(new AbortError()); + } + async close() { + return this.abort(); + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts b/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..71bec4f3516b5358f58981fbe441bad823101dcf --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamByobReader.d.ts @@ -0,0 +1,14 @@ +import { WebStreamReader } from './WebStreamReader.js'; +/** + * Read from a WebStream using a BYOB reader + * Reference: https://nodejs.org/api/webstreams.html#class-readablestreambyobreader + */ +export declare class WebStreamByobReader extends WebStreamReader { + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; +} diff --git a/node_modules/strtok3/lib/stream/WebStreamByobReader.js b/node_modules/strtok3/lib/stream/WebStreamByobReader.js new file mode 100644 index 0000000000000000000000000000000000000000..6c8d253fcd103deafcfb1df6b81d84daeb085f41 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamByobReader.js @@ -0,0 +1,27 @@ +import { WebStreamReader } from './WebStreamReader.js'; +/** + * Read from a WebStream using a BYOB reader + * Reference: https://nodejs.org/api/webstreams.html#class-readablestreambyobreader + */ +export class WebStreamByobReader extends WebStreamReader { + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + // @ts-expect-error + const result = await this.reader.read(new Uint8Array(buffer.length), { min: mayBeLess ? undefined : buffer.length }); + if (result.done) { + this.endOfStream = result.done; + } + if (result.value) { + buffer.set(result.value); + return result.value.length; + } + return 0; + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9c469f15d07fcf1850bd406717964d444fb67d1 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.d.ts @@ -0,0 +1,19 @@ +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export declare class WebStreamDefaultReader extends AbstractStreamReader { + private reader; + private buffer; + constructor(reader: ReadableStreamDefaultReader); + /** + * Copy chunk to target, and store the remainder in this.buffer + */ + private writeChunk; + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + abort(): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js new file mode 100644 index 0000000000000000000000000000000000000000..76fe36822079fadd69d73646c1868b1001fdd385 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js @@ -0,0 +1,62 @@ +import { EndOfStreamError } from './Errors.js'; +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export class WebStreamDefaultReader extends AbstractStreamReader { + constructor(reader) { + super(); + this.reader = reader; + this.buffer = null; // Internal buffer to store excess data + } + /** + * Copy chunk to target, and store the remainder in this.buffer + */ + writeChunk(target, chunk) { + const written = Math.min(chunk.length, target.length); + target.set(chunk.subarray(0, written)); + // Adjust the remainder of the buffer + if (written < chunk.length) { + this.buffer = chunk.subarray(written); + } + else { + this.buffer = null; + } + return written; + } + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + let totalBytesRead = 0; + // Serve from the internal buffer first + if (this.buffer) { + totalBytesRead += this.writeChunk(buffer, this.buffer); + } + // Continue reading from the stream if more data is needed + while (totalBytesRead < buffer.length && !this.endOfStream) { + const result = await this.reader.read(); + if (result.done) { + this.endOfStream = true; + break; + } + if (result.value) { + totalBytesRead += this.writeChunk(buffer.subarray(totalBytesRead), result.value); + } + } + if (!mayBeLess && totalBytesRead === 0 && this.endOfStream) { + throw new EndOfStreamError(); + } + return totalBytesRead; + } + abort() { + this.interrupted = true; + return this.reader.cancel(); + } + async close() { + await this.abort(); + this.reader.releaseLock(); + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamReader.d.ts b/node_modules/strtok3/lib/stream/WebStreamReader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc46e3d34b4254079f79ef35ec0df2920ce813e4 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReader.d.ts @@ -0,0 +1,14 @@ +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export declare abstract class WebStreamReader extends AbstractStreamReader { + protected reader: ReadableStreamDefaultReader | ReadableStreamBYOBReader; + constructor(reader: ReadableStreamDefaultReader | ReadableStreamBYOBReader); + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + protected abstract readFromStream(buffer: Uint8Array, mayBeLess: boolean): Promise; + abort(): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/stream/WebStreamReader.js b/node_modules/strtok3/lib/stream/WebStreamReader.js new file mode 100644 index 0000000000000000000000000000000000000000..048074e684d0c9c19c710356fab81b0b2808106e --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReader.js @@ -0,0 +1,13 @@ +import { AbstractStreamReader } from "./AbstractStreamReader.js"; +export class WebStreamReader extends AbstractStreamReader { + constructor(reader) { + super(); + this.reader = reader; + } + async abort() { + return this.close(); + } + async close() { + this.reader.releaseLock(); + } +} diff --git a/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..565563d7cf4d5bcb944d34cc6b2f8b5a913e261b --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.d.ts @@ -0,0 +1,5 @@ +import type { ReadableStream as NodeReadableStream } from 'node:stream/web'; +import { WebStreamByobReader } from './WebStreamByobReader.js'; +import { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export type AnyWebByteStream = NodeReadableStream | ReadableStream; +export declare function makeWebStreamReader(stream: AnyWebByteStream): WebStreamByobReader | WebStreamDefaultReader; diff --git a/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..e6767840317369a9cfbe2b3280df56d936f81480 --- /dev/null +++ b/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js @@ -0,0 +1,19 @@ +import { WebStreamByobReader } from './WebStreamByobReader.js'; +import { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export function makeWebStreamReader(stream) { + try { + const reader = stream.getReader({ mode: "byob" }); + if (reader instanceof ReadableStreamDefaultReader) { + // Fallback to default reader in case `mode: byob` is ignored + return new WebStreamDefaultReader(reader); + } + return new WebStreamByobReader(reader); + } + catch (error) { + if (error instanceof TypeError) { + // Fallback to default reader in case `mode: byob` rejected by a `TypeError` + return new WebStreamDefaultReader(stream.getReader()); + } + throw error; + } +} diff --git a/node_modules/strtok3/lib/stream/index.d.ts b/node_modules/strtok3/lib/stream/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b973ea79dd23ff6ae84581ddf0f64ad2d83ec69 --- /dev/null +++ b/node_modules/strtok3/lib/stream/index.d.ts @@ -0,0 +1,6 @@ +export { AbortError, EndOfStreamError } from './Errors.js'; +export { StreamReader } from './StreamReader.js'; +export { WebStreamByobReader } from './WebStreamByobReader.js'; +export { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export type { IStreamReader } from './AbstractStreamReader.js'; +export { type AnyWebByteStream, makeWebStreamReader } from './WebStreamReaderFactory.js'; diff --git a/node_modules/strtok3/lib/stream/index.js b/node_modules/strtok3/lib/stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6df5a2ce9a67342d6788df2c79590fd690091dbf --- /dev/null +++ b/node_modules/strtok3/lib/stream/index.js @@ -0,0 +1,5 @@ +export { AbortError, EndOfStreamError } from './Errors.js'; +export { StreamReader } from './StreamReader.js'; +export { WebStreamByobReader } from './WebStreamByobReader.js'; +export { WebStreamDefaultReader } from './WebStreamDefaultReader.js'; +export { makeWebStreamReader } from './WebStreamReaderFactory.js'; diff --git a/node_modules/strtok3/lib/types.d.ts b/node_modules/strtok3/lib/types.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..295608e5977046b650e395ce18c9f445b587efeb --- /dev/null +++ b/node_modules/strtok3/lib/types.d.ts @@ -0,0 +1,139 @@ +import type { IGetToken } from '@tokenizer/token'; +export interface IFileInfo { + /** + * File size in bytes + */ + size?: number; + /** + * MIME-type of file + */ + mimeType?: string; + /** + * File path + */ + path?: string; + /** + * File URL + */ + url?: string; +} +export interface IRandomAccessFileInfo extends IFileInfo { + /** + * File size in bytes + */ + size: number; +} +export interface IReadChunkOptions { + /** + * Number of bytes to read. + */ + length?: number; + /** + * Position where to begin reading from the file. + * Default it is `tokenizer.position`. + * Position may not be less than `tokenizer.position`, unless `supportsRandomAccess()` returns `true`. + */ + position?: number; + /** + * If set, will not throw an EOF error if not all off the requested data could be read + */ + mayBeLess?: boolean; +} +export interface IRandomAccessTokenizer extends ITokenizer { + /** + * Provide access to information of the underlying information stream or file. + */ + fileInfo: IRandomAccessFileInfo; + /** + * Change the position (offset) of the tokenizer + * @param position New position + */ + setPosition(position: number): void; +} +/** + * The tokenizer allows us to read or peek from the tokenizer-stream. + * The tokenizer-stream is an abstraction of a stream, file or Buffer. + */ +export interface ITokenizer { + /** + * Provide access to information of the underlying information stream or file. + */ + readonly fileInfo: IFileInfo; + /** + * Offset in bytes (= number of bytes read) since beginning of file or stream + */ + readonly position: number; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peek from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + peekBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peeked from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @param maybeless - If set, will not throw an EOF error if the less then the requested length could be read. + */ + peekToken(token: IGetToken, position?: number | null, maybeless?: boolean): Promise; + /** + * Read a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IGetToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IGetToken): Promise; + /** + * Ignore given number of bytes + * @param length - Number of bytes ignored + */ + ignore(length: number): Promise; + /** + * Clean up resources. + * It does not close the stream for StreamReader, but is does close the file-descriptor. + */ + close(): Promise; + /** + * Abort pending asynchronous operations + */ + abort(): Promise; + /** + * Returns true when the underlying file supports random access + */ + supportsRandomAccess(): boolean; +} +export type OnClose = () => Promise; +export interface ITokenizerOptions { + /** + * Pass additional file information to the tokenizer + */ + fileInfo?: IFileInfo; + /** + * On tokenizer close handler + */ + onClose?: OnClose; + /** + * Pass `AbortSignal` which can stop active async operations + * Ref: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal + */ + abortSignal?: AbortSignal; +} diff --git a/node_modules/strtok3/lib/types.js b/node_modules/strtok3/lib/types.js new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/strtok3/lib/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/strtok3/package.json b/node_modules/strtok3/package.json new file mode 100644 index 0000000000000000000000000000000000000000..42b2265c47f2db503dd0f2b06a6748bf090033f4 --- /dev/null +++ b/node_modules/strtok3/package.json @@ -0,0 +1,94 @@ +{ + "name": "strtok3", + "version": "10.3.5", + "description": "A promise based streaming tokenizer", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli 'lib/**/*.js' 'lib/**/*.js.map' 'lib/**/*.d.ts' 'test/**/*.js' 'test/**/*.js.map'", + "compile-src": "tsc -p lib --sourceMap false", + "compile-test": "tsc -p test", + "compile": "yarn run compile-src && yarn run compile-test", + "build": "yarn run clean && yarn run compile", + "prepublishOnly": "yarn run build", + "eslint": "eslint lib test", + "lint:md": "remark -u preset-lint-recommended .", + "lint:ts": "biome check", + "lint": "yarn run lint:md && yarn run lint:ts", + "fix": "yarn run biome lint --write", + "test": "mocha", + "bun:test": "bun run --bun test", + "test-coverage": "c8 yarn run test", + "send-codacy": "c8 report --reporter=text-lcov | codacy-coverage", + "start": "yarn run compile && yarn run lint && yarn run cover-test", + "update-biome": "yarn add -D --exact @biomejs/biome && npx @biomejs/biome migrate --write" + }, + "engines": { + "node": ">=18" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Borewit/strtok3.git" + }, + "license": "MIT", + "type": "module", + "exports": { + ".": { + "node": "./lib/index.js", + "default": "./lib/core.js" + }, + "./core": "./lib/core.js" + }, + "types": "lib/index.d.ts", + "files": [ + "lib/**/*.js", + "lib/**/*.d.ts" + ], + "bugs": { + "url": "https://github.com/Borewit/strtok3/issues" + }, + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "devDependencies": { + "@biomejs/biome": "2.4.8", + "@types/chai": "^5.2.2", + "@types/chai-as-promised": "^8.0.2", + "@types/debug": "^4.1.12", + "@types/mocha": "^10.0.10", + "@types/node": "^24.1.0", + "c8": "^11.0.0", + "chai": "^5.2.1", + "chai-as-promised": "^8.0.2", + "del-cli": "^7.0.0", + "mocha": "^11.7.5", + "node-readable-to-web-readable-stream": "^0.4.2", + "remark-cli": "^12.0.1", + "remark-preset-lint-recommended": "^7.0.1", + "token-types": "^6.1.2", + "ts-node": "^10.9.2", + "typescript": "^5.8.3", + "uint8array-extras": "^1.4.0" + }, + "keywords": [ + "tokenizer", + "reader", + "token", + "async", + "promise", + "parser", + "decoder", + "binary", + "endian", + "uint", + "stream", + "streaming" + ], + "packageManager": "yarn@4.9.2" +} diff --git a/node_modules/superagent/LICENSE b/node_modules/superagent/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1b188ba5d80295b22b4c607ecfc27abc3afceb4b --- /dev/null +++ b/node_modules/superagent/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/superagent/README.md b/node_modules/superagent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ce4234d223922085247b7ff6ca6eb979c7b8f3b --- /dev/null +++ b/node_modules/superagent/README.md @@ -0,0 +1,273 @@ +# superagent + +[![build status](https://github.com/forwardemail/superagent/actions/workflows/ci.yml/badge.svg)](https://github.com/forwardemail/superagent/actions/workflows/ci.yml) +[![code coverage](https://img.shields.io/codecov/c/github/ladjs/superagent.svg)](https://codecov.io/gh/ladjs/superagent) +[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) +[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org) +[![license](https://img.shields.io/github/license/ladjs/superagent.svg)](LICENSE) + +> Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features. Maintained for [Forward Email](https://github.com/forwardemail) and [Lad](https://github.com/ladjs). + + +## Table of Contents + +* [Install](#install) +* [Usage](#usage) + * [Node](#node) + * [Browser](#browser) +* [Supported Platforms](#supported-platforms) + * [Required Browser Features](#required-browser-features) +* [Plugins](#plugins) +* [Upgrading from previous versions](#upgrading-from-previous-versions) +* [Contributors](#contributors) +* [License](#license) + + +## Install + +[npm][]: + +```sh +npm install superagent +``` + +[yarn][]: + +```sh +yarn add superagent +``` + + +## Usage + +### Node + +```js +const superagent = require('superagent'); + +// callback +superagent + .post('/api/pet') + .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body + .set('X-API-Key', 'foobar') + .set('accept', 'json') + .end((err, res) => { + // Calling the end function will send the request + }); + +// promise with then/catch +superagent.post('/api/pet').then(console.log).catch(console.error); + +// promise with async/await +(async () => { + try { + const res = await superagent.post('/api/pet'); + console.log(res); + } catch (err) { + console.error(err); + } +})(); +``` + +### Browser + +**The browser-ready, minified version of `superagent` is only 50 KB (minified and gzipped).** + +Browser-ready versions of this module are available via [jsdelivr][], [unpkg][], and also in the `node_modules/superagent/dist` folder in downloads of the `superagent` package. + +> Note that we also provide unminified versions with `.js` instead of `.min.js` file extensions. + +#### VanillaJS + +This is the solution for you if you're just using ` + + + + +``` + +#### Bundler + +If you are using [browserify][], [webpack][], [rollup][], or another bundler, then you can follow the same usage as [Node](#node) above. + + +## Supported Platforms + +* Node: v14.18.0+ +* Browsers (see [.browserslistrc](.browserslistrc)): + + ```sh + npx browserslist + ``` + + ```sh + and_chr 102 + and_ff 101 + and_qq 10.4 + and_uc 12.12 + android 101 + chrome 103 + chrome 102 + chrome 101 + chrome 100 + edge 103 + edge 102 + edge 101 + firefox 101 + firefox 100 + firefox 91 + ios_saf 15.5 + ios_saf 15.4 + ios_saf 15.2-15.3 + ios_saf 15.0-15.1 + ios_saf 14.5-14.8 + ios_saf 14.0-14.4 + ios_saf 12.2-12.5 + kaios 2.5 + op_mini all + op_mob 64 + opera 86 + opera 85 + safari 15.5 + safari 15.4 + samsung 17.0 + samsung 16.0 + ``` + +### Required Browser Features + +We recommend using (specifically with the bundle mentioned in [VanillaJS](#vanillajs) above): + +```html + +``` + +* WeakRef is not supported in Opera 85, iOS Safari 12.2-12.5 +* BigInt is not supported in iOS Safari 12.2-12.5 + + +## Plugins + +SuperAgent is easily extended via plugins. + +```js +const nocache = require('superagent-no-cache'); +const superagent = require('superagent'); +const prefix = require('superagent-prefix')('/static'); + +superagent + .get('/some-url') + .query({ action: 'edit', city: 'London' }) // query string + .use(prefix) // Prefixes *only* this request + .use(nocache) // Prevents caching of *only* this request + .end((err, res) => { + // Do something + }); +``` + +Existing plugins: + +* [superagent-no-cache](https://github.com/johntron/superagent-no-cache) - prevents caching by including Cache-Control header +* [superagent-prefix](https://github.com/johntron/superagent-prefix) - prefixes absolute URLs (useful in test environment) +* [superagent-suffix](https://github.com/timneutkens1/superagent-suffix) - suffix URLs with a given path +* [superagent-mock](https://github.com/M6Web/superagent-mock) - simulate HTTP calls by returning data fixtures based on the requested URL +* [superagent-mocker](https://github.com/shuvalov-anton/superagent-mocker) — simulate REST API +* [superagent-cache](https://github.com/jpodwys/superagent-cache) - A global SuperAgent patch with built-in, flexible caching +* [superagent-cache-plugin](https://github.com/jpodwys/superagent-cache-plugin) - A SuperAgent plugin with built-in, flexible caching +* [superagent-jsonapify](https://github.com/alex94puchades/superagent-jsonapify) - A lightweight [json-api](http://jsonapi.org/format/) client addon for superagent +* [superagent-serializer](https://github.com/zzarcon/superagent-serializer) - Converts server payload into different cases +* [superagent-httpbackend](https://www.npmjs.com/package/superagent-httpbackend) - stub out requests using AngularJS' $httpBackend syntax +* [superagent-throttle](https://github.com/leviwheatcroft/superagent-throttle) - queues and intelligently throttles requests +* [superagent-charset](https://github.com/magicdawn/superagent-charset) - add charset support for node's SuperAgent +* [superagent-verbose-errors](https://github.com/jcoreio/superagent-verbose-errors) - include response body in error messages for failed requests +* [superagent-declare](https://github.com/damoclark/superagent-declare) - A simple [declarative](https://en.wikipedia.org/wiki/Declarative_programming) API for SuperAgent +* [superagent-node-http-timings](https://github.com/webuniverseio/superagent-node-http-timings) - measure http timings in node.js +* [superagent-cheerio](https://github.com/mmmmmrob/superagent-cheerio) - add [cheerio](https://www.npmjs.com/package/cheerio) to your response content automatically. Adds `res.$` for HTML and XML response bodies. +* [@certible/superagent-aws-sign](https://github.com/certible/superagent-aws-sign) - Sign AWS endpoint requests, it uses the aws4 to authenticate the SuperAgent requests + +Please prefix your plugin with `superagent-*` so that it can easily be found by others. + +For SuperAgent extensions such as couchdb and oauth visit the [wiki](https://github.com/ladjs/superagent/wiki). + + +## Upgrading from previous versions + +Please see [GitHub releases page](https://github.com/ladjs/superagent/releases) for the current changelog. + +Our breaking changes are mostly in rarely used functionality and from stricter error handling. + +* [6.0 to 6.1](https://github.com/ladjs/superagent/releases/tag/v6.1.0) + * Browser behaviour changed to match Node when serializing `application/x-www-form-urlencoded`, using `arrayFormat: 'indices'` semantics of `qs` library. (See: ) +* [5.x to 6.x](https://github.com/ladjs/superagent/releases/tag/v6.0.0): + * Retry behavior is still opt-in, however we now have a more fine-grained list of status codes and error codes that we retry against (see updated docs) + * A specific issue with Content-Type matching not being case-insensitive is fixed + * Set is now required for IE 9, see [Required Browser Features](#required-browser-features) for more insight +* [4.x to 5.x](https://github.com/ladjs/superagent/releases/tag/v5.0.0): + * We've implemented the build setup of [Lass](https://lass.js.org) to simplify our stack and linting + * Unminified browserified build size has been reduced from 48KB to 20KB (via `tinyify` and the latest version of Babel using `@babel/preset-env` and `.browserslistrc`) + * Linting support has been added using `caniuse-lite` and `eslint-plugin-compat` + * We can now target what versions of Node we wish to support more easily using `.babelrc` +* [3.x to 4.x](https://github.com/ladjs/superagent/releases/tag/v4.0.0-alpha.1): + * Ensure you're running Node 6 or later. We've dropped support for Node 4. + * We've started using ES6 and for compatibility with Internet Explorer you may need to use Babel. + * We suggest migrating from `.end()` callbacks to `.then()` or `await`. +* [2.x to 3.x](https://github.com/ladjs/superagent/releases/tag/v3.0.0): + * Ensure you're running Node 4 or later. We've dropped support for Node 0.x. + * Test code that calls `.send()` multiple times. Invalid calls to `.send()` will now throw instead of sending garbage. +* [1.x to 2.x](https://github.com/ladjs/superagent/releases/tag/v2.0.0): + * If you use `.parse()` in the *browser* version, rename it to `.serialize()`. + * If you rely on `undefined` in query-string values being sent literally as the text "undefined", switch to checking for missing value instead. `?key=undefined` is now `?key` (without a value). + * If you use `.then()` in Internet Explorer, ensure that you have a polyfill that adds a global `Promise` object. +* 0.x to 1.x: + * Instead of 1-argument callback `.end(function(res){})` use `.then(res => {})`. + + +## Contributors + +| Name | +| ------------------- | +| **Kornel Lesiński** | +| **Peter Lyons** | +| **Hunter Loftis** | +| **Nick Baugh** | + + +## License + +[MIT](LICENSE) © TJ Holowaychuk + + +## + +[npm]: https://www.npmjs.com/ + +[yarn]: https://yarnpkg.com/ + +[jsdelivr]: https://www.jsdelivr.com/ + +[unpkg]: https://unpkg.com/ + +[browserify]: https://github.com/browserify/browserify + +[webpack]: https://github.com/webpack/webpack + +[rollup]: https://github.com/rollup/rollup diff --git a/node_modules/superagent/lib/agent-base.js b/node_modules/superagent/lib/agent-base.js new file mode 100644 index 0000000000000000000000000000000000000000..b1a5e44efcbc6e884c399d31af511b5455a4ace7 --- /dev/null +++ b/node_modules/superagent/lib/agent-base.js @@ -0,0 +1,25 @@ +"use strict"; + +const defaults = ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts']; +class Agent { + constructor() { + this._defaults = []; + } + _setDefaults(request) { + for (const def of this._defaults) { + request[def.fn](...def.args); + } + } +} +for (const fn of defaults) { + // Default setting for all requests from this agent + Agent.prototype[fn] = function (...args) { + this._defaults.push({ + fn, + args + }); + return this; + }; +} +module.exports = Agent; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJkZWZhdWx0cyIsIkFnZW50IiwiY29uc3RydWN0b3IiLCJfZGVmYXVsdHMiLCJfc2V0RG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QUFPLEdBQUdYLEtBQUsiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/client.js b/node_modules/superagent/lib/client.js new file mode 100644 index 0000000000000000000000000000000000000000..aafb5eb10a92d5e27ad69a7e6cda40361b0338c1 --- /dev/null +++ b/node_modules/superagent/lib/client.js @@ -0,0 +1,957 @@ +"use strict"; + +/** + * Root reference for iframes. + */ + +let root; +if (typeof window !== 'undefined') { + // Browser window + root = window; +} else if (typeof self === 'undefined') { + // Other environments + console.warn('Using browser-only version of superagent in non-browser environment'); + root = void 0; +} else { + // Web Worker + root = self; +} +const Emitter = require('component-emitter'); +const safeStringify = require('fast-safe-stringify'); +const qs = require('qs'); +const RequestBase = require('./request-base'); +const { + isObject, + mixin, + hasOwn +} = require('./utils'); +const ResponseBase = require('./response-base'); +const Agent = require('./agent-base'); + +/** + * Noop. + */ + +function noop() {} + +/** + * Expose `request`. + */ + +module.exports = function (method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } + + // url first + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + return new exports.Request(method, url); +}; +exports = module.exports; +const request = exports; +exports.Request = Request; + +/** + * Determine XHR. + */ + +request.getXHR = () => { + if (root.XMLHttpRequest) { + return new root.XMLHttpRequest(); + } + throw new Error('Browser-only version of superagent could not find XHR'); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +const trim = ''.trim ? s => s.trim() : s => s.replace(/(^\s*|\s*$)/g, ''); + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(object) { + if (!isObject(object)) return object; + const pairs = []; + for (const key in object) { + if (hasOwn(object, key)) pushEncodedKeyValuePair(pairs, key, object[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, value) { + if (value === undefined) return; + if (value === null) { + pairs.push(encodeURI(key)); + return; + } + if (Array.isArray(value)) { + for (const v of value) { + pushEncodedKeyValuePair(pairs, key, v); + } + } else if (isObject(value)) { + for (const subkey in value) { + if (hasOwn(value, subkey)) pushEncodedKeyValuePair(pairs, `${key}[${subkey}]`, value[subkey]); + } + } else { + pairs.push(encodeURI(key) + '=' + encodeURIComponent(value)); + } +} + +/** + * Expose serialization method. + */ + +request.serializeObject = serialize; + +/** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(string_) { + const object = {}; + const pairs = string_.split('&'); + let pair; + let pos; + for (let i = 0, length_ = pairs.length; i < length_; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos === -1) { + object[decodeURIComponent(pair)] = ''; + } else { + object[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); + } + } + return object; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'text/xml', + urlencoded: 'application/x-www-form-urlencoded', + form: 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +request.serialize = { + 'application/x-www-form-urlencoded': obj => { + return qs.stringify(obj, { + indices: false, + strictNullHandling: true + }); + }, + 'application/json': safeStringify +}; + +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(string_) { + const lines = string_.split(/\r?\n/); + const fields = {}; + let index; + let line; + let field; + let value; + for (let i = 0, length_ = lines.length; i < length_; ++i) { + line = lines[i]; + index = line.indexOf(':'); + if (index === -1) { + // could be empty line, just skip it + continue; + } + field = line.slice(0, index).toLowerCase(); + value = trim(line.slice(index + 1)); + fields[field] = value; + } + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/i.test(mime); +} + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(request_) { + this.req = request_; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; + this.statusText = this.req.xhr.statusText; + let { + status + } = this.xhr; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + this._setStatusProperties(status); + this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + this.header = this.headers; + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + if (this.text === null && request_._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); + } +} +mixin(Response.prototype, ResponseBase.prototype); + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function (string_) { + let parse = request.parse[this.type]; + if (this.req._parser) { + return this.req._parser(this, string_); + } + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && string_ && (string_.length > 0 || string_ instanceof Object) ? parse(string_) : null; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function () { + const { + req + } = this; + const { + method + } = req; + const { + url + } = req; + const message = `cannot ${method} ${url} (${this.status})`; + const error = new Error(message); + error.status = this.status; + error.method = method; + error.url = url; + return error; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + const self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', () => { + let error = null; + let res = null; + try { + res = new Response(self); + } catch (err) { + error = new Error('Parser is unable to parse the response'); + error.parse = true; + error.original = err; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + error.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + error.status = self.xhr.status ? self.xhr.status : null; + error.statusCode = error.status; // backwards-compat only + } else { + error.rawResponse = null; + error.status = null; + } + return self.callback(error); + } + self.emit('response', res); + let new_error; + try { + if (!self._isResponseOK(res)) { + new_error = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); + } + } catch (err) { + new_error = err; // ok() callback can throw + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_error) { + new_error.original = error; + new_error.response = res; + new_error.status = new_error.status || res.status; + self.callback(new_error, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +// eslint-disable-next-line new-cap +Emitter(Request.prototype); +mixin(Request.prototype, RequestBase.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function (type) { + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function (type) { + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + if (typeof pass === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + if (!options) { + options = { + type: typeof btoa === 'function' ? 'basic' : 'auto' + }; + } + const encoder = options.encoder ? options.encoder : string => { + if (typeof btoa === 'function') { + return btoa(string); + } + throw new Error('Cannot use basic auth, btoa is not a function'); + }; + return this._auth(user, pass, options, encoder); +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function (value) { + if (typeof value !== 'string') value = serialize(value); + if (value) this._query.push(value); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + this._getFormData().append(field, file, options || file.name); + } + return this; +}; +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function (error, res) { + if (this._shouldRetry(error, res)) { + return this._retry(); + } + const fn = this._callback; + this.clearTimeout(); + if (error) { + if (this._maxRetries) error.retries = this._retries - 1; + this.emit('error', error); + } + fn(error, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function () { + const error = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + error.crossDomain = true; + error.status = this.status; + error.method = this.method; + error.url = this.url; + this.callback(error); +}; + +// This only warns, because the request is still likely to work +Request.prototype.agent = function () { + console.warn('This is not supported in browser version of superagent'); + return this; +}; +Request.prototype.ca = Request.prototype.agent; +Request.prototype.buffer = Request.prototype.ca; + +// This throws, because it can't send/receive data as expected +Request.prototype.write = () => { + throw new Error('Streaming is not supported in browser version of superagent'); +}; +Request.prototype.pipe = Request.prototype.write; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ +Request.prototype._isHost = function (object) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return object && typeof object === 'object' && !Array.isArray(object) && Object.prototype.toString.call(object) !== '[object Object]'; +}; + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function (fn) { + if (this._endCalled) { + console.warn('Warning: .end() was called twice. This is not supported in superagent'); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + + // querystring + this._finalizeQueryString(); + this._end(); +}; +Request.prototype._setUploadTimeout = function () { + const self = this; + + // upload timeout it's wokrs only if deadline timeout is off + if (this._uploadTimeout && !this._uploadTimeoutTimer) { + this._uploadTimeoutTimer = setTimeout(() => { + self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); + }, this._uploadTimeout); + } +}; + +// eslint-disable-next-line complexity +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + const self = this; + this.xhr = request.getXHR(); + const { + xhr + } = this; + let data = this._formData || this._data; + this._setTimeouts(); + + // state change + xhr.addEventListener('readystatechange', () => { + const { + readyState + } = xhr; + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + if (readyState !== 4) { + return; + } + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + let status; + try { + status = xhr.status; + } catch (err) { + status = 0; + } + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }); + + // progress + const handleProgress = (direction, e) => { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + if (e.percent === 100) { + clearTimeout(self._uploadTimeoutTimer); + } + } + e.direction = direction; + self.emit('progress', e); + }; + if (this.hasListeners('progress')) { + try { + xhr.addEventListener('progress', handleProgress.bind(null, 'download')); + if (xhr.upload) { + xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); + } + } catch (err) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + if (xhr.upload) { + this._setUploadTimeout(); + } + + // initiate request + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { + // serialize stuff + const contentType = this._header['content-type']; + let serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // set header fields + for (const field in this.header) { + if (this.header[field] === null) continue; + if (hasOwn(this.header, field)) xhr.setRequestHeader(field, this.header[field]); + } + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data === 'undefined' ? null : data); +}; + +// create a Proxy that can instantiate a new Agent without using `new` keyword +// (for backward compatibility and chaining) +const proxyAgent = new Proxy(Agent, { + apply(target, thisArg, argumentsList) { + return new target(...argumentsList); + } +}); +request.agent = proxyAgent; +for (const method of ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE']) { + Agent.prototype[method.toLowerCase()] = function (url, fn) { + const request_ = new request.Request(method, url); + this._setDefaults(request_); + if (fn) { + request_.end(fn); + } + return request_; + }; +} +Agent.prototype.del = Agent.prototype.delete; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = (url, data, fn) => { + const request_ = request('GET', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = (url, data, fn) => { + const request_ = request('HEAD', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.query(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = (url, data, fn) => { + const request_ = request('OPTIONS', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, data, fn) { + const request_ = request('DELETE', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +} +request.del = del; +request.delete = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = (url, data, fn) => { + const request_ = request('PATCH', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = (url, data, fn) => { + const request_ = request('POST', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = (url, data, fn) => { + const request_ = request('PUT', url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) request_.send(data); + if (fn) request_.end(fn); + return request_; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6Wy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sR0FBRyxDQUFDcUgsRUFBRSxDQUFDO0VBQ3hCLE9BQU8xRCxRQUFRO0FBQ2pCLENBQUMiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/agent.js b/node_modules/superagent/lib/node/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..d03ccf883d2338da89d0532892a01f755d56233d --- /dev/null +++ b/node_modules/superagent/lib/node/agent.js @@ -0,0 +1,101 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const { + CookieJar +} = require('cookiejar'); +const { + CookieAccessInfo +} = require('cookiejar'); +const methods = require('methods'); +const request = require('../..'); +const AgentBase = require('../agent-base'); + +/** + * Initialize a new `Agent`. + * + * @api public + */ + +class Agent extends AgentBase { + constructor(options) { + super(); + this.jar = new CookieJar(); + if (options) { + if (options.ca) { + this.ca(options.ca); + } + if (options.key) { + this.key(options.key); + } + if (options.pfx) { + this.pfx(options.pfx); + } + if (options.cert) { + this.cert(options.cert); + } + if (options.rejectUnauthorized === false) { + this.disableTLSCerts(); + } + } + } + + /** + * Save the cookies in the given `res` to + * the agent's cookie jar for persistence. + * + * @param {Response} res + * @api private + */ + _saveCookies(res) { + const cookies = res.headers['set-cookie']; + if (cookies) { + var _res$request; + const url = new URL(((_res$request = res.request) === null || _res$request === void 0 ? void 0 : _res$request.url) || ''); + this.jar.setCookies(cookies, url.hostname, url.pathname); + } + } + + /** + * Attach cookies when available to the given `req`. + * + * @param {Request} req + * @api private + */ + _attachCookies(request_) { + const url = new URL(request_.url); + const access = new CookieAccessInfo(url.hostname, url.pathname, url.protocol === 'https:'); + const cookies = this.jar.getCookies(access).toValueString(); + request_.cookies = cookies; + } +} +for (const name of methods) { + const method = name.toUpperCase(); + if (method === "QUERY") continue; + Agent.prototype[name] = function (url, fn) { + const request_ = new request.Request(method, url); + request_.on('response', this._saveCookies.bind(this)); + request_.on('redirect', this._saveCookies.bind(this)); + request_.on('redirect', this._attachCookies.bind(this, request_)); + this._setDefaults(request_); + this._attachCookies(request_); + if (fn) { + request_.end(fn); + } + return request_; + }; +} +Agent.prototype.del = Agent.prototype.delete; + +// create a Proxy that can instantiate a new Agent without using `new` keyword +// (for backward compatibility and chaining) +const proxyAgent = new Proxy(Agent, { + apply(target, thisArg, argumentsList) { + return new target(...argumentsList); + } +}); +module.exports = proxyAgent; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJDb29raWVKYXIiLCJyZXF1aXJlIiwiQ29va2llQWNjZXNzSW5mbyIsIm1ldGhvZHMiLCJyZXF1ZXN0IiwiQWdlbnRCYXNlIiwiQWdlbnQiLCJjb25zdHJ1Y3RvciIsIm9wdGlvbnMiLCJqYXIiLCJjYSIsImtleSIsInBmeCIsImNlcnQiLCJyZWplY3RVbmF1dGhvcml6ZWQiLCJkaXNhYmxlVExTQ2VydHMiLCJfc2F2ZUNvb2tpZXMiLCJyZXMiLCJjb29raWVzIiwiaGVhZGVycyIsIl9yZXMkcmVxdWVzdCIsInVybCIsIlVSTCIsInNldENvb2tpZXMiLCJob3N0bmFtZSIsInBhdGhuYW1lIiwiX2F0dGFjaENvb2tpZXMiLCJyZXF1ZXN0XyIsImFjY2VzcyIsInByb3RvY29sIiwiZ2V0Q29va2llcyIsInRvVmFsdWVTdHJpbmciLCJuYW1lIiwibWV0aG9kIiwidG9VcHBlckNhc2UiLCJwcm90b3R5cGUiLCJmbiIsIlJlcXVlc3QiLCJvbiIsImJpbmQiLCJfc2V0RGVmYXVsdHMiLCJlbmQiLCJkZWwiLCJkZWxldGUiLCJwcm94eUFnZW50IiwiUHJveHkiLCJhcHBseSIsInRhcmdldCIsInRoaXNBcmciLCJhcmd1bWVudHNMaXN0IiwibW9kdWxlIiwiZXhwb3J0cyJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL2FnZW50LmpzIl0sInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogTW9kdWxlIGRlcGVuZGVuY2llc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xDQUFDO0lBQ2xCO0lBRUEsT0FBT1QsUUFBUTtFQUNqQixDQUFDO0FBQ0g7QUFFQXJCLEtBQUssQ0FBQzZCLFNBQVMsQ0FBQ08sR0FBRyxHQUFHcEMsS0FBSyxDQUFDNkIsU0FBUyxDQUFDUSxNQUFNOztBQUU1QztBQUNBO0FBQ0EsTUFBTUMsVUFBVSxHQUFHLElBQUlDLEtBQUssQ0FBQ3ZDLEtBQUssRUFBRTtFQUNsQ3dDLEtBQUtBLENBQUVDLE1BQU0sRUFBRUMsT0FBTyxFQUFFQyxhQUFhLEVBQUU7SUFDckMsT0FBTyxJQUFJRixNQUFNLENBQUMsR0FBR0UsYUFBYSxDQUFDO0VBQ3JDO0FBQ0YsQ0FBQyxDQUFDO0FBRUZDLE1BQU0sQ0FBQ0MsT0FBTyxHQUFHUCxVQUFVIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/decompress.js b/node_modules/superagent/lib/node/decompress.js new file mode 100644 index 0000000000000000000000000000000000000000..befe06c48dee494d788403aef2ca05b459ba4155 --- /dev/null +++ b/node_modules/superagent/lib/node/decompress.js @@ -0,0 +1,20 @@ +"use strict"; + +const zlib = require('zlib'); +const utils = require('../utils'); +const { + isGzipOrDeflateEncoding, + isBrotliEncoding +} = utils; +exports.chooseDecompresser = res => { + let decompresser; + if (isGzipOrDeflateEncoding(res)) { + decompresser = zlib.createUnzip(); + } else if (isBrotliEncoding(res)) { + decompresser = zlib.createBrotliDecompress(); + } else { + throw new Error('unknown content-encoding'); + } + return decompresser; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ6bGliIiwicmVxdWlyZSIsInV0aWxzIiwiaXNHemlwT3JEZWZsYXRlRW5jb2RpbmciLCJpc0Jyb3RsaUVuY29kaW5nIiwiZXhwb3J0cyIsImNob29zZURlY29tcHJlc3NlciIsInJlcyIsImRlY29tcHJlc3NlciIsImNyZWF0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QUNoQ0MsWUFBWSxHQUFHUixJQUFJLENBQUNTLFdBQVcsQ0FBQyxDQUFDO0VBQ25DLENBQUMsTUFBTSxJQUFJTCxnQkFBZ0IsQ0FBQ0csR0FBRyxDQUFDLEVBQUU7SUFDaENDLFlBQVksR0FBR1IsSUFBSSxDQUFDVSxzQkFBc0IsQ0FBQyxDQUFDO0VBQzlDLENBQUMsTUFBTTtJQUNMLE1BQU0sSUFBSUMsS0FBSyxDQUFDLDBCQUEwQixDQUFDO0VBQzdDO0VBQ0EsT0FBT0gsWUFBWTtBQUNyQixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/http2wrapper.js b/node_modules/superagent/lib/node/http2wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..9ba0955b25ec7da2c6dbaef2db13373843f91153 --- /dev/null +++ b/node_modules/superagent/lib/node/http2wrapper.js @@ -0,0 +1,158 @@ +"use strict"; + +const http2 = require('http2'); +const Stream = require('stream'); +const net = require('net'); +const tls = require('tls'); +const { + HTTP2_HEADER_PATH, + HTTP2_HEADER_STATUS, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_HOST, + HTTP2_HEADER_SET_COOKIE, + NGHTTP2_CANCEL +} = http2.constants; +function setProtocol(protocol) { + return { + request(options) { + return new Request(protocol, options); + } + }; +} +function normalizeIpv6Host(host) { + return net.isIP(host) === 6 ? `[${host}]` : host; +} +class Request extends Stream { + constructor(protocol, options) { + super(); + const defaultPort = protocol === 'https:' ? 443 : 80; + const defaultHost = 'localhost'; + const port = options.port || defaultPort; + const host = options.host || defaultHost; + delete options.port; + delete options.host; + this.method = options.method; + this.path = options.path; + this.protocol = protocol; + this.host = host; + delete options.method; + delete options.path; + const sessionOptions = { + ...options + }; + if (options.socketPath) { + sessionOptions.socketPath = options.socketPath; + sessionOptions.createConnection = this.createUnixConnection.bind(this); + } + this._headers = {}; + const normalizedHost = normalizeIpv6Host(host); + const session = http2.connect(`${protocol}//${normalizedHost}:${port}`, sessionOptions); + this.setHeader('host', `${normalizedHost}:${port}`); + session.on('error', error => this.emit('error', error)); + this.session = session; + } + createUnixConnection(authority, options) { + switch (this.protocol) { + case 'http:': + return net.connect(options.socketPath); + case 'https:': + options.ALPNProtocols = ['h2']; + options.servername = this.host; + options.allowHalfOpen = true; + return tls.connect(options.socketPath, options); + default: + throw new Error('Unsupported protocol', this.protocol); + } + } + setNoDelay(bool) { + // We can not use setNoDelay with HTTP/2. + // Node 10 limits http2session.socket methods to ones safe to use with HTTP/2. + // See also https://nodejs.org/api/http2.html#http2_http2session_socket + } + getFrame() { + if (this.frame) { + return this.frame; + } + const method = { + [HTTP2_HEADER_PATH]: this.path, + [HTTP2_HEADER_METHOD]: this.method + }; + let headers = this.mapToHttp2Header(this._headers); + headers = Object.assign(headers, method); + const frame = this.session.request(headers); + frame.once('response', (headers, flags) => { + headers = this.mapToHttpHeader(headers); + frame.headers = headers; + frame.statusCode = headers[HTTP2_HEADER_STATUS]; + frame.status = frame.statusCode; + this.emit('response', frame); + }); + this._headerSent = true; + frame.once('drain', () => this.emit('drain')); + frame.on('error', error => this.emit('error', error)); + frame.on('close', () => this.session.close()); + this.frame = frame; + return frame; + } + mapToHttpHeader(headers) { + const keys = Object.keys(headers); + const http2Headers = {}; + for (let key of keys) { + let value = headers[key]; + key = key.toLowerCase(); + switch (key) { + case HTTP2_HEADER_SET_COOKIE: + value = Array.isArray(value) ? value : [value]; + break; + default: + break; + } + http2Headers[key] = value; + } + return http2Headers; + } + mapToHttp2Header(headers) { + const keys = Object.keys(headers); + const http2Headers = {}; + for (let key of keys) { + let value = headers[key]; + key = key.toLowerCase(); + switch (key) { + case HTTP2_HEADER_HOST: + key = HTTP2_HEADER_AUTHORITY; + value = /^http:\/\/|^https:\/\//.test(value) ? new URL(value).host : value; + break; + default: + break; + } + http2Headers[key] = value; + } + return http2Headers; + } + setHeader(name, value) { + this._headers[name.toLowerCase()] = value; + } + getHeader(name) { + return this._headers[name.toLowerCase()]; + } + write(data, encoding) { + const frame = this.getFrame(); + return frame.write(data, encoding); + } + pipe(stream, options) { + const frame = this.getFrame(); + return frame.pipe(stream, options); + } + end(data) { + const frame = this.getFrame(); + frame.end(data); + } + abort(data) { + const frame = this.getFrame(); + frame.close(NGHTTP2_CANCEL); + this.session.destroy(); + } +} +exports.setProtocol = setProtocol; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJodHRwMiIsInJlcXVpcmUiLCJTdHJlYW0iLCJuZXQiLCJ0bHMiLCJIVFRQMl9IRUFERVJfUEFUSCIsIkhUVFAyX0hFQURFUl9TVEFUVVMiLCJIVFRQMl9IRUFERVJfTUVUSE9EIiwiSFRUUDJfSEVBREVSX0FVVEhPUklUWSIsIkhUVFAyX0hFQURFUl9IT1NUIiwiSFRUUDJfSEVBREVSX1NFVF9DT09LSUUiLCJOR0hUVFAyX0NBTkNFTCIsImNvbnN0YW50cyIsInNldFByb3RvY29sIiwicHJvdG9jb2wiLCJyZXF1ZXN0Iiwib3B0aW9ucyIsIlJlcXVlc3QiLCJub3JtYWxpemVJcHY2SG9zdCIsImhvc3QiLCJpc0lQIiwiY29uc3RydWN0b3IiLCJkZWZhdWx0UG9ydCIsImRlZmF1bHRIb3N0IiwicG9ydCIsIm1ldGhvZCIsInBhdGgiLCJzZXNzaW9uT3B0aW9ucyIsInNvY2tldFBhdGgiLCJjcmVhdGVDb25uZWN0aW9uIiwiY3JlYXRlVW5peENvbm5lY3Rpb24iLCJiaW5kIiwiX2hlYWRlcnMiLCJub3JtYWxpemVkSG9zdCIsInNlc3Npb24iLCJjb25uZWN0Iiwic2V0SGVhZGVyIiwib24iLCJlcnJvciIsImVtaXQiLCJhdXRob3JpdHkiLCJBTFBOUHJvdG9jb2xzIiwic2VydmVybmFtZSIsImFsbG93SGFsZk9wZW4iLCJFcnJvciIsInNldE5vRGVsYXkiLCJib29sIiwiZ2V0RnJhb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UFDcUMsSUFBSSxDQUFDTCxXQUFXLENBQUMsQ0FBQyxDQUFDO0VBQzFDO0VBRUFPLEtBQUtBLENBQUNDLElBQUksRUFBRUMsUUFBUSxFQUFFO0lBQ3BCLE1BQU16QixLQUFLLEdBQUcsSUFBSSxDQUFDRCxRQUFRLENBQUMsQ0FBQztJQUM3QixPQUFPQyxLQUFLLENBQUN1QixLQUFLLENBQUNDLElBQUksRUFBRUMsUUFBUSxDQUFDO0VBQ3BDO0VBRUFDLElBQUlBLENBQUNDLE1BQU0sRUFBRTNELE9BQU8sRUFBRTtJQUNwQixNQUFNZ0MsS0FBSyxHQUFHLElBQUksQ0FBQ0QsUUFBUSxDQUFDLENBQUM7SUFDN0IsT0FBT0MsS0FBSyxDQUFDMEIsSUFBSSxDQUFDQyxNQUFNLEVBQUUzRCxPQUFPLENBQUM7RUFDcEM7RUFFQTRELEdBQUdBLENBQUNKLElBQUksRUFBRTtJQUNSLE1BQU14QixLQUFLLEdBQUcsSUFBSSxDQUFDRCxRQUFRLENBQUMsQ0FBQztJQUM3QkMsS0FBSyxDQUFDNEIsR0FBRyxDQUFDSixJQUFJLENBQUM7RUFDakI7RUFFQUssS0FBS0EsQ0FBQ0wsSUFBSSxFQUFFO0lBQ1YsTUFBTXhCLEtBQUssR0FBRyxJQUFJLENBQUNELFFBQVEsQ0FBQyxDQUFDO0lBQzdCQyxLQUFLLENBQUNXLEtBQUssQ0FBQ2hELGNBQWMsQ0FBQztJQUMzQixJQUFJLENBQUN1QixPQUFPLENBQUM0QyxPQUFPLENBQUMsQ0FBQztFQUN4QjtBQUNGO0FBRUFDLE9BQU8sQ0FBQ2xFLFdBQVcsR0FBR0EsV0FBVyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/index.js b/node_modules/superagent/lib/node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f12ccfd387f7373bbbc8ebe487cdb1e8a73db42c --- /dev/null +++ b/node_modules/superagent/lib/node/index.js @@ -0,0 +1,1332 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const { + format +} = require('url'); +const Stream = require('stream'); +const https = require('https'); +const http = require('http'); +const fs = require('fs'); +const zlib = require('zlib'); +const util = require('util'); +const qs = require('qs'); +const mime = require('mime'); +let methods = require('methods'); +const FormData = require('form-data'); +const formidable = require('formidable'); +const debug = require('debug')('superagent'); +const CookieJar = require('cookiejar'); +const safeStringify = require('fast-safe-stringify'); +const utils = require('../utils'); +const RequestBase = require('../request-base'); +const http2 = require('./http2wrapper'); +const { + decompress +} = require('./unzip'); +const Response = require('./response'); +const { + mixin, + hasOwn, + isBrotliEncoding, + isGzipOrDeflateEncoding +} = utils; +const { + chooseDecompresser +} = require('./decompress'); +function request(method, url) { + // callback + if (typeof url === 'function') { + return new exports.Request('GET', method).end(url); + } + + // url first + if (arguments.length === 1) { + return new exports.Request('GET', method); + } + return new exports.Request(method, url); +} +module.exports = request; +exports = module.exports; + +/** + * Expose `Request`. + */ + +exports.Request = Request; + +/** + * Expose the agent function + */ + +exports.agent = require('./agent'); + +/** + * Noop. + */ + +function noop() {} + +/** + * Expose `Response`. + */ + +exports.Response = Response; + +/** + * Define "form" mime type. + */ + +mime.define({ + 'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data'] +}, true); + +/** + * Protocol map. + */ + +exports.protocols = { + 'http:': http, + 'https:': https, + 'http2:': http2 +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + +exports.serialize = { + 'application/x-www-form-urlencoded': obj => { + return qs.stringify(obj, { + indices: false, + strictNullHandling: true + }); + }, + 'application/json': safeStringify +}; + +/** + * Default parsers. + * + * superagent.parse['application/xml'] = function(res, fn){ + * fn(null, res); + * }; + * + */ + +exports.parse = require('./parsers'); + +/** + * Default buffering map. Can be used to set certain + * response types to buffer/not buffer. + * + * superagent.buffer['application/xml'] = true; + */ +exports.buffer = {}; + +/** + * Initialize internal header tracking properties on a request instance. + * + * @param {Object} req the instance + * @api private + */ +function _initHeaders(request_) { + request_._header = { + // coerces header names to lowercase + }; + request_.header = { + // preserves header name case + }; +} + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String|Object} url + * @api public + */ + +function Request(method, url) { + Stream.call(this); + if (typeof url !== 'string') url = format(url); + this._enableHttp2 = Boolean(process.env.HTTP2_TEST); // internal only + this._agent = false; + this._formData = null; + this.method = method; + this.url = url; + _initHeaders(this); + this.writable = true; + this._redirects = 0; + this.redirects(method === 'HEAD' ? 0 : 5); + this.cookies = ''; + this.qs = {}; + this._query = []; + this.qsRaw = this._query; // Unused, for backwards compatibility only + this._redirectList = []; + this._streamRequest = false; + this._lookup = undefined; + this.once('end', this.clearTimeout.bind(this)); +} + +/** + * Inherit from `Stream` (which inherits from `EventEmitter`). + * Mixin `RequestBase`. + */ +util.inherits(Request, Stream); +mixin(Request.prototype, RequestBase.prototype); + +/** + * Enable or Disable http2. + * + * Enable http2. + * + * ``` js + * request.get('http://localhost/') + * .http2() + * .end(callback); + * + * request.get('http://localhost/') + * .http2(true) + * .end(callback); + * ``` + * + * Disable http2. + * + * ``` js + * request = request.http2(); + * request.get('http://localhost/') + * .http2(false) + * .end(callback); + * ``` + * + * @param {Boolean} enable + * @return {Request} for chaining + * @api public + */ + +Request.prototype.http2 = function (bool) { + if (exports.protocols['http2:'] === undefined) { + throw new Error('superagent: this version of Node.js does not support http2'); + } + this._enableHttp2 = bool === undefined ? true : bool; + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('http://localhost/upload') + * .attach('field', Buffer.from('Hello world'), 'hello.html') + * .end(callback); + * ``` + * + * A filename may also be used: + * + * ``` js + * request.post('http://localhost/upload') + * .attach('files', 'image.jpg') + * .end(callback); + * ``` + * + * @param {String} field + * @param {String|fs.ReadStream|Buffer} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function (field, file, options) { + if (file) { + if (this._data) { + throw new Error("superagent can't mix .send() and .attach()"); + } + let o = options || {}; + if (typeof options === 'string') { + o = { + filename: options + }; + } + if (typeof file === 'string') { + if (!o.filename) o.filename = file; + debug('creating `fs.ReadStream` instance for file: %s', file); + file = fs.createReadStream(file); + file.on('error', error => { + const formData = this._getFormData(); + formData.emit('error', error); + }); + } else if (!o.filename && file.path) { + o.filename = file.path; + } + this._getFormData().append(field, file, o); + } + return this; +}; +Request.prototype._getFormData = function () { + if (!this._formData) { + this._formData = new FormData(); + this._formData.on('error', error => { + debug('FormData error', error); + if (this.called) { + // The request has already finished and the callback was called. + // Silently ignore the error. + return; + } + this.callback(error); + this.abort(); + }); + } + return this._formData; +}; + +/** + * Gets/sets the `Agent` to use for this HTTP request. The default (if this + * function is not called) is to opt out of connection pooling (`agent: false`). + * + * @param {http.Agent} agent + * @return {http.Agent} + * @api public + */ + +Request.prototype.agent = function (agent) { + if (arguments.length === 0) return this._agent; + this._agent = agent; + return this; +}; + +/** + * Gets/sets the `lookup` function to use custom DNS resolver. + * + * @param {Function} lookup + * @return {Function} + * @api public + */ + +Request.prototype.lookup = function (lookup) { + if (arguments.length === 0) return this._lookup; + this._lookup = lookup; + return this; +}; + +/** + * Set _Content-Type_ response header passed through `mime.getType()`. + * + * Examples: + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('json') + * .send(jsonstring) + * .end(callback); + * + * request.post('/') + * .type('application/json') + * .send(jsonstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function (type) { + return this.set('Content-Type', type.includes('/') ? type : mime.getType(type)); +}; + +/** + * Set _Accept_ response header passed through `mime.getType()`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function (type) { + return this.set('Accept', type.includes('/') ? type : mime.getType(type)); +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function (value) { + if (typeof value === 'string') { + this._query.push(value); + } else { + Object.assign(this.qs, value); + } + return this; +}; + +/** + * Write raw `data` / `encoding` to the socket. + * + * @param {Buffer|String} data + * @param {String} encoding + * @return {Boolean} + * @api public + */ + +Request.prototype.write = function (data, encoding) { + const request_ = this.request(); + if (!this._streamRequest) { + this._streamRequest = true; + } + return request_.write(data, encoding); +}; + +/** + * Pipe the request body to `stream`. + * + * @param {Stream} stream + * @param {Object} options + * @return {Stream} + * @api public + */ + +Request.prototype.pipe = function (stream, options) { + this.piped = true; // HACK... + this.buffer(false); + this.end(); + return this._pipeContinue(stream, options); +}; +Request.prototype._pipeContinue = function (stream, options) { + this.req.once('response', res => { + // redirect + if (isRedirect(res.statusCode) && this._redirects++ !== this._maxRedirects) { + return this._redirect(res) === this ? this._pipeContinue(stream, options) : undefined; + } + this.res = res; + this._emitResponse(); + if (this._aborted) return; + if (this._shouldDecompress(res)) { + let decompresser = chooseDecompresser(res); + decompresser.on('error', error => { + if (error && error.code === 'Z_BUF_ERROR') { + // unexpected end of file is ignored by browsers and curl + stream.emit('end'); + return; + } + stream.emit('error', error); + }); + res.pipe(decompresser).pipe(stream, options); + // don't emit 'end' until decompresser has completed writing all its data. + decompresser.once('end', () => this.emit('end')); + } else { + res.pipe(stream, options); + res.once('end', () => this.emit('end')); + } + }); + return stream; +}; + +/** + * Enable / disable buffering. + * + * @return {Boolean} [val] + * @return {Request} for chaining + * @api public + */ + +Request.prototype.buffer = function (value) { + this._buffer = value !== false; + return this; +}; + +/** + * Redirect to `url + * + * @param {IncomingMessage} res + * @return {Request} for chaining + * @api private + */ + +Request.prototype._redirect = function (res) { + let url = res.headers.location; + if (!url) { + return this.callback(new Error('No location header for redirect'), res); + } + debug('redirect %s -> %s', this.url, url); + + // location + url = new URL(url, this.url).href; + + // ensure the response is being consumed + // this is required for Node v0.10+ + res.resume(); + let headers = this.req.getHeaders ? this.req.getHeaders() : this.req._headers; + const changesOrigin = new URL(url).host !== new URL(this.url).host; + + // implementation of 302 following defacto standard + if (res.statusCode === 301 || res.statusCode === 302) { + // strip Content-* related fields + // in case of POST etc + headers = utils.cleanHeader(headers, changesOrigin); + + // force GET + this.method = this.method === 'HEAD' ? 'HEAD' : 'GET'; + + // clear data + this._data = null; + } + + // 303 is always GET + if (res.statusCode === 303) { + // strip Content-* related fields + // in case of POST etc + headers = utils.cleanHeader(headers, changesOrigin); + + // force method + this.method = 'GET'; + + // clear data + this._data = null; + } + + // 307 preserves method + // 308 preserves method + delete headers.host; + delete this.req; + delete this._formData; + + // remove all add header except User-Agent + _initHeaders(this); + + // redirect + this.res = res; + this._endCalled = false; + this.url = url; + this.qs = {}; + this._query.length = 0; + this.set(headers); + this._emitRedirect(); + this._redirectList.push(this.url); + this.end(this._callback); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * Examples: + * + * .auth('tobi', 'learnboost') + * .auth('tobi:learnboost') + * .auth('tobi') + * .auth(accessToken, { type: 'bearer' }) + * + * @param {String} user + * @param {String} [pass] + * @param {Object} [options] options with authorization type 'basic' or 'bearer' ('basic' is default) + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function (user, pass, options) { + if (arguments.length === 1) pass = ''; + if (typeof pass === 'object' && pass !== null) { + // pass is optional and can be replaced with options + options = pass; + pass = ''; + } + if (!options) { + options = { + type: 'basic' + }; + } + const encoder = string => Buffer.from(string).toString('base64'); + return this._auth(user, pass, options, encoder); +}; + +/** + * Set the certificate authority option for https request. + * + * @param {Buffer | Array} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.ca = function (cert) { + this._ca = cert; + return this; +}; + +/** + * Set the client certificate key option for https request. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.key = function (cert) { + this._key = cert; + return this; +}; + +/** + * Set the key, certificate, and CA certs of the client in PFX or PKCS12 format. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.pfx = function (cert) { + if (typeof cert === 'object' && !Buffer.isBuffer(cert)) { + this._pfx = cert.pfx; + this._passphrase = cert.passphrase; + } else { + this._pfx = cert; + } + return this; +}; + +/** + * Set the client certificate option for https request. + * + * @param {Buffer | String} cert + * @return {Request} for chaining + * @api public + */ + +Request.prototype.cert = function (cert) { + this._cert = cert; + return this; +}; + +/** + * Do not reject expired or invalid TLS certs. + * sets `rejectUnauthorized=true`. Be warned that this allows MITM attacks. + * + * @return {Request} for chaining + * @api public + */ + +Request.prototype.disableTLSCerts = function () { + this._disableTLSCerts = true; + return this; +}; + +/** + * Return an http[s] request. + * + * @return {OutgoingMessage} + * @api private + */ + +// eslint-disable-next-line complexity +Request.prototype.request = function () { + if (this.req) return this.req; + const options = {}; + try { + const query = qs.stringify(this.qs, { + indices: false, + strictNullHandling: true + }); + if (query) { + this.qs = {}; + this._query.push(query); + } + this._finalizeQueryString(); + } catch (err) { + return this.emit('error', err); + } + let { + url: urlString + } = this; + const retries = this._retries; + + // default to http:// + if (urlString.indexOf('http') !== 0) urlString = `http://${urlString}`; + const url = new URL(urlString); + let { + protocol + } = url; + let path = `${url.pathname}${url.search}`; + + // support unix sockets + if (/^https?\+unix:/.test(protocol) === true) { + // get the protocol + protocol = `${protocol.split('+')[0]}:`; + + // get the socket path + options.socketPath = url.hostname.replace(/%2F/g, '/'); + url.host = ''; + url.hostname = ''; + } + + // Override IP address of a hostname + if (this._connectOverride) { + const { + hostname + } = url; + const match = hostname in this._connectOverride ? this._connectOverride[hostname] : this._connectOverride['*']; + if (match) { + // backup the real host + if (!this._header.host) { + this.set('host', url.host); + } + let newHost; + let newPort; + if (typeof match === 'object') { + newHost = match.host; + newPort = match.port; + } else { + newHost = match; + newPort = url.port; + } + + // wrap [ipv6] + url.host = /:/.test(newHost) ? `[${newHost}]` : newHost; + if (newPort) { + url.host += `:${newPort}`; + url.port = newPort; + } + url.hostname = newHost; + } + } + + // options + options.method = this.method; + options.port = url.port; + options.path = path; + options.host = utils.normalizeHostname(url.hostname); // ex: [::1] -> ::1 + options.ca = this._ca; + options.key = this._key; + options.pfx = this._pfx; + options.cert = this._cert; + options.passphrase = this._passphrase; + options.agent = this._agent; + options.lookup = this._lookup; + options.rejectUnauthorized = typeof this._disableTLSCerts === 'boolean' ? !this._disableTLSCerts : process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; + + // Allows request.get('https://1.2.3.4/').set('Host', 'example.com') + if (this._header.host) { + options.servername = this._header.host.replace(/:\d+$/, ''); + } + if (this._trustLocalhost && /^(?:localhost|127\.0\.0\.\d+|(0*:)+:0*1)$/.test(url.hostname)) { + options.rejectUnauthorized = false; + } + + // initiate request + const module_ = this._enableHttp2 ? exports.protocols['http2:'].setProtocol(protocol) : exports.protocols[protocol]; + + // request + this.req = module_.request(options); + const { + req + } = this; + + // set tcp no delay + req.setNoDelay(true); + if (options.method !== 'HEAD') { + req.setHeader('Accept-Encoding', 'gzip, deflate'); + } + this.protocol = protocol; + this.host = url.host; + + // expose events + req.once('drain', () => { + this.emit('drain'); + }); + req.on('error', error => { + // flag abortion here for out timeouts + // because node will emit a faux-error "socket hang up" + // when request is aborted before a connection is made + if (this._aborted) return; + // if not the same, we are in the **old** (cancelled) request, + // so need to continue (same as for above) + if (this._retries !== retries) return; + // if we've received a response then we don't want to let + // an error in the request blow up the response + if (this.response) return; + this.callback(error); + }); + + // auth + if (url.username || url.password) { + this.auth(url.username, url.password); + } + if (this.username && this.password) { + this.auth(this.username, this.password); + } + for (const key in this.header) { + if (hasOwn(this.header, key)) req.setHeader(key, this.header[key]); + } + + // add cookies + if (this.cookies) { + if (hasOwn(this._header, 'cookie')) { + // merge + const temporaryJar = new CookieJar.CookieJar(); + temporaryJar.setCookies(this._header.cookie.split('; ')); + temporaryJar.setCookies(this.cookies.split('; ')); + req.setHeader('Cookie', temporaryJar.getCookies(CookieJar.CookieAccessInfo.All).toValueString()); + } else { + req.setHeader('Cookie', this.cookies); + } + } + return req; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function (error, res) { + if (this._shouldRetry(error, res)) { + return this._retry(); + } + + // Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime. + const fn = this._callback || noop; + this.clearTimeout(); + if (this.called) return console.warn('superagent: double callback bug'); + this.called = true; + if (!error) { + try { + if (!this._isResponseOK(res)) { + let message = 'Unsuccessful HTTP response'; + if (res) { + message = http.STATUS_CODES[res.status] || message; + } + error = new Error(message); + error.status = res ? res.status : undefined; + } + } catch (err) { + error = err; + error.status = error.status || (res ? res.status : undefined); + } + } + + // It's important that the callback is called outside try/catch + // to avoid double callback + if (!error) { + return fn(null, res); + } + error.response = res; + if (this._maxRetries) error.retries = this._retries - 1; + + // only emit error event if there is a listener + // otherwise we assume the callback to `.end()` will get the error + if (error && this.listeners('error').length > 0) { + this.emit('error', error); + } + fn(error, res); +}; + +/** + * Check if `obj` is a host object, + * + * @param {Object} obj host object + * @return {Boolean} is a host object + * @api private + */ +Request.prototype._isHost = function (object) { + return Buffer.isBuffer(object) || object instanceof Stream || object instanceof FormData; +}; + +/** + * Initiate request, invoking callback `fn(err, res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype._emitResponse = function (body, files) { + const response = new Response(this); + this.response = response; + response.redirects = this._redirectList; + if (undefined !== body) { + response.body = body; + } + response.files = files; + if (this._endCalled) { + response.pipe = function () { + throw new Error("end() has already been called, so it's too late to start piping"); + }; + } + this.emit('response', response); + return response; +}; + +/** + * Emit `redirect` event, passing an instanceof `Response`. + * + * @api private + */ + +Request.prototype._emitRedirect = function () { + const response = new Response(this); + response.redirects = this._redirectList; + this.emit('redirect', response); +}; +Request.prototype.end = function (fn) { + this.request(); + debug('%s %s', this.method, this.url); + if (this._endCalled) { + throw new Error('.end() was called twice. This is not supported in superagent'); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + this._end(); +}; +Request.prototype._end = function () { + if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); + let data = this._data; + const { + req + } = this; + const { + method + } = this; + this._setTimeouts(); + + // body + if (method !== 'HEAD' && !req._headerSent) { + // serialize stuff + if (typeof data !== 'string') { + let contentType = req.getHeader('Content-Type'); + // Parse out just the content type from the header (ignore the charset) + if (contentType) contentType = contentType.split(';')[0]; + let serialize = this._serializer || exports.serialize[contentType]; + if (!serialize && isJSON(contentType)) { + serialize = exports.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // content-length + if (data && !req.getHeader('Content-Length')) { + req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)); + } + } + + // response + // eslint-disable-next-line complexity + req.once('response', res => { + debug('%s %s -> %s', this.method, this.url, res.statusCode); + if (this._responseTimeoutTimer) { + clearTimeout(this._responseTimeoutTimer); + } + if (this.piped) { + return; + } + const max = this._maxRedirects; + const mime = utils.type(res.headers['content-type'] || '') || 'text/plain'; + let type = mime.split('/')[0]; + if (type) type = type.toLowerCase().trim(); + const multipart = type === 'multipart'; + const redirect = isRedirect(res.statusCode); + const responseType = this._responseType; + this.res = res; + + // redirect + if (redirect && this._redirects++ !== max) { + return this._redirect(res); + } + if (this.method === 'HEAD') { + this.emit('end'); + this.callback(null, this._emitResponse()); + return; + } + + // zlib support + if (this._shouldDecompress(res)) { + decompress(req, res); + } + let buffer = this._buffer; + if (buffer === undefined && mime in exports.buffer) { + buffer = Boolean(exports.buffer[mime]); + } + let parser = this._parser; + if (undefined === buffer && parser) { + console.warn("A custom superagent parser has been set, but buffering strategy for the parser hasn't been configured. Call `req.buffer(true or false)` or set `superagent.buffer[mime] = true or false`"); + buffer = true; + } + if (!parser) { + if (responseType) { + parser = exports.parse.image; // It's actually a generic Buffer + buffer = true; + } else if (multipart) { + const form = formidable.formidable(); + parser = (res, callback) => { + // Create a PassThrough stream that acts as a proper HTTP request + const bridgeStream = new Stream.PassThrough(); + + // Add HTTP request properties from the current request context + bridgeStream.method = this.method || 'POST'; + bridgeStream.url = this.url || '/'; + bridgeStream.httpVersion = res.httpVersion || '1.1'; + bridgeStream.headers = res.headers || {}; + bridgeStream.socket = res.socket || { + readable: true + }; + + // Pipe the response data through the bridge stream + res.pipe(bridgeStream); + form.parse(bridgeStream, (err, fields, files) => { + if (err) return callback(err); + + // Formidable v3 always returns arrays, but SuperAgent expects single values + // Flatten single-item arrays to maintain backward compatibility + const flattenedFields = {}; + if (fields) { + for (const key in fields) { + const value = fields[key]; + flattenedFields[key] = Array.isArray(value) && value.length === 1 ? value[0] : value; + } + } + const flattenedFiles = {}; + if (files) { + for (const key in files) { + const value = files[key]; + flattenedFiles[key] = Array.isArray(value) && value.length === 1 ? value[0] : value; + } + } + + // Return flattened fields as the object parameter to match SuperAgent's expected format + callback(null, flattenedFields, flattenedFiles); + }); + }; + buffer = true; + } else if (isBinary(mime)) { + parser = exports.parse.image; + buffer = true; // For backwards-compatibility buffering default is ad-hoc MIME-dependent + } else if (exports.parse[mime]) { + parser = exports.parse[mime]; + } else if (type === 'text') { + parser = exports.parse.text; + buffer = buffer !== false; + // everyone wants their own white-labeled json + } else if (isJSON(mime)) { + parser = exports.parse['application/json']; + buffer = buffer !== false; + } else if (buffer) { + parser = exports.parse.text; + } else if (undefined === buffer) { + parser = exports.parse.image; // It's actually a generic Buffer + buffer = true; + } + } + + // by default only buffer text/*, json and messed up thing from hell + if (undefined === buffer && isText(mime) || isJSON(mime)) { + buffer = true; + } + this._resBuffered = buffer; + let parserHandlesEnd = false; + if (buffer) { + // Protectiona against zip bombs and other nuisance + let responseBytesLeft = this._maxResponseSize || 200000000; + res.on('data', buf => { + responseBytesLeft -= buf.byteLength || buf.length > 0 ? buf.length : 0; + if (responseBytesLeft < 0) { + // This will propagate through error event + const error = new Error('Maximum response size reached'); + error.code = 'ETOOLARGE'; + // Parsers aren't required to observe error event, + // so would incorrectly report success + parserHandlesEnd = false; + // Will not emit error event + res.destroy(error); + // so we do callback now + this.callback(error, null); + } + }); + } + if (parser) { + try { + // Unbuffered parsers are supposed to emit response early, + // which is weird BTW, because response.body won't be there. + parserHandlesEnd = buffer; + parser(res, (error, object, files) => { + if (this.timedout) { + // Timeout has already handled all callbacks + return; + } + + // Intentional (non-timeout) abort is supposed to preserve partial response, + // even if it doesn't parse. + if (error && !this._aborted) { + return this.callback(error); + } + if (parserHandlesEnd) { + this.emit('end'); + this.callback(null, this._emitResponse(object, files)); + } + }); + } catch (err) { + this.callback(err); + return; + } + } + this.res = res; + + // unbuffered + if (!buffer) { + debug('unbuffered %s %s', this.method, this.url); + this.callback(null, this._emitResponse()); + if (multipart) return; // allow multipart to handle end event + res.once('end', () => { + debug('end %s %s', this.method, this.url); + this.emit('end'); + }); + return; + } + + // terminating events + res.once('error', error => { + parserHandlesEnd = false; + this.callback(error, null); + }); + if (!parserHandlesEnd) res.once('end', () => { + debug('end %s %s', this.method, this.url); + // TODO: unless buffering emit earlier to stream + this.emit('end'); + this.callback(null, this._emitResponse()); + }); + }); + this.emit('request', this); + const getProgressMonitor = () => { + const lengthComputable = true; + const total = req.getHeader('Content-Length'); + let loaded = 0; + const progress = new Stream.Transform(); + progress._transform = (chunk, encoding, callback) => { + loaded += chunk.length; + this.emit('progress', { + direction: 'upload', + lengthComputable, + loaded, + total + }); + callback(null, chunk); + }; + return progress; + }; + const bufferToChunks = buffer => { + const chunkSize = 16 * 1024; // default highWaterMark value + const chunking = new Stream.Readable(); + const totalLength = buffer.length; + const remainder = totalLength % chunkSize; + const cutoff = totalLength - remainder; + for (let i = 0; i < cutoff; i += chunkSize) { + const chunk = buffer.slice(i, i + chunkSize); + chunking.push(chunk); + } + if (remainder > 0) { + const remainderBuffer = buffer.slice(-remainder); + chunking.push(remainderBuffer); + } + chunking.push(null); // no more data + + return chunking; + }; + + // if a FormData instance got created, then we send that as the request body + const formData = this._formData; + if (formData) { + // set headers + const headers = formData.getHeaders(); + for (const i in headers) { + if (hasOwn(headers, i)) { + debug('setting FormData header: "%s: %s"', i, headers[i]); + req.setHeader(i, headers[i]); + } + } + + // attempt to get "Content-Length" header + formData.getLength((error, length) => { + // TODO: Add chunked encoding when no length (if err) + if (error) debug('formData.getLength had error', error, length); + debug('got FormData Content-Length: %s', length); + if (typeof length === 'number') { + req.setHeader('Content-Length', length); + } + formData.pipe(getProgressMonitor()).pipe(req); + }); + } else if (Buffer.isBuffer(data)) { + bufferToChunks(data).pipe(getProgressMonitor()).pipe(req); + } else { + req.end(data); + } +}; + +// Check whether response has a non-0-sized gzip-encoded body +Request.prototype._shouldDecompress = res => { + return hasNonEmptyResponseContent(res) && (isGzipOrDeflateEncoding(res) || isBrotliEncoding(res)); +}; + +/** + * Overrides DNS for selected hostnames. Takes object mapping hostnames to IP addresses. + * + * When making a request to a URL with a hostname exactly matching a key in the object, + * use the given IP address to connect, instead of using DNS to resolve the hostname. + * + * A special host `*` matches every hostname (keep redirects in mind!) + * + * request.connect({ + * 'test.example.com': '127.0.0.1', + * 'ipv6.example.com': '::1', + * }) + */ +Request.prototype.connect = function (connectOverride) { + if (typeof connectOverride === 'string') { + this._connectOverride = { + '*': connectOverride + }; + } else if (typeof connectOverride === 'object') { + this._connectOverride = connectOverride; + } else { + this._connectOverride = undefined; + } + return this; +}; +Request.prototype.trustLocalhost = function (toggle) { + this._trustLocalhost = toggle === undefined ? true : toggle; + return this; +}; + +// generate HTTP verb methods +if (!methods.includes('del')) { + // create a copy so we don't cause conflicts with + // other packages using the methods package and + // npm 3.x + methods = [...methods]; + methods.push('del'); +} +for (let method of methods) { + const name = method; + method = method === 'del' ? 'delete' : method; + method = method.toUpperCase(); + request[name] = (url, data, fn) => { + const request_ = request(method, url); + if (typeof data === 'function') { + fn = data; + data = null; + } + if (data) { + if (method === 'GET' || method === 'HEAD') { + request_.query(data); + } else { + request_.send(data); + } + } + if (fn) request_.end(fn); + return request_; + }; +} + +/** + * Check if `mime` is text and should be buffered. + * + * @param {String} mime + * @return {Boolean} + * @api public + */ + +function isText(mime) { + const parts = mime.split('/'); + let type = parts[0]; + if (type) type = type.toLowerCase().trim(); + let subtype = parts[1]; + if (subtype) subtype = subtype.toLowerCase().trim(); + return type === 'text' || subtype === 'x-www-form-urlencoded'; +} + +// This is not a catchall, but a start. It might be useful +// in the long run to have file that includes all binary +// content types from https://www.iana.org/assignments/media-types/media-types.xhtml +function isBinary(mime) { + let [registry, name] = mime.split('/'); + if (registry) registry = registry.toLowerCase().trim(); + if (name) name = name.toLowerCase().trim(); + return ['audio', 'font', 'image', 'video'].includes(registry) || ['gz', 'gzip'].includes(name); +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + // should match /json or +json + // but not /json-seq + return /[/+]json($|[^-\w])/i.test(mime); +} + +/** + * Check if we should follow the redirect `code`. + * + * @param {Number} code + * @return {Boolean} + * @api private + */ + +function isRedirect(code) { + return [301, 302, 303, 305, 307, 308].includes(code); +} +function hasNonEmptyResponseContent(res) { + if (res.statusCode === 204 || res.statusCode === 304) { + // These aren't supposed to have any body + return false; + } + + // header content is a string, and distinction between 0 and no information is crucial + if (res.headers['content-length'] === '0') { + // We know that the body is empty (unfortunately, this check does not cover chunked encoding) + return false; + } + return true; +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJmb3JtYXQiLCJyZXF1aXJlIiwiU3RyZWFtIiwiaHR0cHMiLCJodHRwIiwiZnMiLCJ6bGliIiwidXRpbCIsInFzIiwibWltZSIsIm1ldGhvZHMiLCJGb3JtRGF0YSIsImZvcm1pZGFibGUiLCJkZWJ1ZyIsIkNvb2tpZUphciIsInNhZmVTdHJpbmdpZnkiLCJ1dGlscyIsIlJlcXVlc3RCYXNlIiwiaHR0cDIiLCJkZWNvbXByZX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mlkZ2VTdHJlYW0sIChlcnIsIGZpZWxkcywgZmlsZXMpID0+IHtcbiAgICAgICAgICAgIGlmIChlcnIpIHJldHVybiBjYWxsYmFjayhlcnIpO1xuXG4gICAgICAgICAgICAvLyBGb3JtaWRhYmxlIHYzIGFsd2F5cyByZXR1cm5zIGFycmF5cywgYnV0IFN1cGVyQWdlbnQgZXhwZWN0cyBzaW5nbGUgdmFsdWVzXG4gICAgICAgICAgICAvLyBGbGF0dGVuIHNpbmdsZS1pdGVtIGFycmF5cyB0byBtYWludGFpbiBiYWNrd2FyZCBjb21wYXRpYmlsaXR5XG4gICAgICAgICAgICBjb25zdCBmbGF0dGVuZWRGaWVsZHMgPSB7fTtcbiAgICAgICAgICAgIGlmIChmaWVsZHMpIHtcbiAgICAgICAgICAgICAgZm9yIChjb25zdCBrZXkgaW4gZmllbGRzKSB7XG4gICAgICAgICAgICAgICAgY29uc3QgdmFsdWUgPSBmaWVsZHNba2V5XTtcbiAgICAgICAgICAgICAgICBmbGF0dGVuZWRGaWVsZHNba2V5XSA9IEFycmF5LmlzQXJyYXkodmFsdWUpICYmIHZhbHVlLmxlbmd0aCA9PT0gMSA/IHZhbHVlWzBdIDogdmFsdWU7XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgY29uc3QgZmxhdHRlbmVkRmlsZXMgPSB7fTtcbiAgICAgICAgICAgIGlmIChmaWxlcykge1xuICAgICAgICAgICAgICBmb3IgKGNvbnN0IGtleSBpbiBmaWxlcykge1xuICAgICAgICAgICAgICAgIGNvbnN0IHZhbHVlID0gZmlsZXNba2V5XTtcbiAgICAgICAgICAgICAgICBmbGF0dGVuZWRGaWxlc1trZXldID0gQXJyYXkuaXNBcnJheSh2YWx1ZSkgJiYgdmFsdWUubGVuZ3RoID09PSAxID8gdmFsdWVbMF0gOiB2YWx1ZTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICAvLyBSZXR1cm4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lBQ3BEO0lBQ0EsT0FBTyxLQUFLO0VBQ2Q7O0VBRUE7RUFDQSxJQUFJRixHQUFHLENBQUNXLE9BQU8sQ0FBQyxnQkFBZ0IsQ0FBQyxLQUFLLEdBQUcsRUFBRTtJQUN6QztJQUNBLE9BQU8sS0FBSztFQUNkO0VBRUEsT0FBTyxJQUFJO0FBQ2IiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/image.js b/node_modules/superagent/lib/node/parsers/image.js new file mode 100644 index 0000000000000000000000000000000000000000..c77432de92f635f835fac3ade18c09e564bc1864 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/image.js @@ -0,0 +1,13 @@ +"use strict"; + +module.exports = (res, fn) => { + const data = []; // Binary data needs binary storage + + res.on('data', chunk => { + data.push(chunk); + }); + res.on('end', () => { + fn(null, Buffer.concat(data)); + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJkYXRhIiwib24iLCJjaHVuayIsInB1c2giLCJCdWZmZXIiLCJjb25jYXQiXSwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvbm9kZS9wYXJzZXJzL2ltYWdlLmpzIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gKHJlcywgZm4pID0+IHtcbiAgY29uc3QgZGF0YSA9IFtdOyAvLyBCaW5hcnkgZGF0YSBuZWVkcyBiaW5hcnkgc3RvcmFnZVxuXG4gIHJlcy5vbignZGF0YScsIChjaHVuaykgPT4ge1xuICAgIGRhdGEucHVzaChjaHVuayk7XG4gIH0pO1xuICByZXMub24oJ2VuZCcsICgpID0+IHtcbiAgICBmbihudWxsLCBCdWZmZXIuY29uY2F0KGRhdGEpKTtcbiAgfSk7XG59O1xuIl0sIm1hcHBpbmdzIjoiOztBQUFBQSxNQUFNLENBQUNDLE9BQU8sR0FBRyxDQUFDQyxHQUFHLEVBQUVDLEVBQUUsS0FBSztFQUM1QixNQUFNQyxJQUFJLEdBQUcsRUFBRSxDQUFDLENBQUM7O0VBRWpCRixHQUFHLENBQUNHLEVBQUUsQ0FBQyxNQUFNLEVBQUdDLEtBQUssSUFBSztJQUN4QkYsSUFBSSxDQUFDRyxJQUFJLENBQUNELEtBQUssQ0FBQztFQUNsQixDQUFDLENBQUM7RUFDRkosR0FBRyxDQUFDRyxFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU07SUFDbEJGLEVBQUUsQ0FBQyxJQUFJLEVBQUVLLE1BQU0sQ0FBQ0MsTUFBTSxDQUFDTCxJQUFJLENBQUMsQ0FBQztFQUMvQixDQUFDLENBQUM7QUFDSixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/index.js b/node_modules/superagent/lib/node/parsers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..06052a5e0fc92be78c12f4fd4354a3eb1c64a710 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/index.js @@ -0,0 +1,11 @@ +"use strict"; + +exports['application/x-www-form-urlencoded'] = require('./urlencoded'); +exports['application/json'] = require('./json'); +exports.text = require('./text'); +exports['application/json-seq'] = exports.text; +const binary = require('./image'); +exports['application/octet-stream'] = binary; +exports['application/pdf'] = binary; +exports.image = binary; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJleHBvcnRzIiwicmVxdWlyZSIsInRleHQiLCJiaW5hcnkiLCJpbWFnZSJdLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9ub2RlL3BhcnNlcnMvaW5kZXguanMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0c1snYXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkJ10gPSByZXF1aXJlKCcuL3VybGVuY29kZWQnKTtcbmV4cG9ydHNbJ2FwcGxpY2F0aW9uL2pzb24nXSA9IHJlcXVpcmUoJy4vanNvbicpO1xuZXhwb3J0cy50ZXh0ID0gcmVxdWlyZSgnLi90ZXh0Jyk7XG5cbmV4cG9ydHNbJ2FwcGxpY2F0aW9uL2pzb24tc2VxJ10gPSBleHBvcnRzLnRleHQ7XG5cbmNvbnN0IGJpbmFyeSA9IHJlcXVpcmUoJy4vaW1hZ2UnKTtcblxuZXhwb3J0c1snYXBwbGljYXRpb24vb2N0ZXQtc3RyZWFtJ10gPSBiaW5hcnk7XG5leHBvcnRzWydhcHBsaWNhdGlvbi9wZGYnXSA9IGJpbmFyeTtcbmV4cG9ydHMuaW1hZ2UgPSBiaW5hcnk7XG4iXSwibWFwcGluZ3MiOiI7O0FBQUFBLE9BQU8sQ0FBQyxtQ0FBbUMsQ0FBQyxHQUFHQyxPQUFPLENBQUMsY0FBYyxDQUFDO0FBQ3RFRCxPQUFPLENBQUMsa0JBQWtCLENBQUMsR0FBR0MsT0FBTyxDQUFDLFFBQVEsQ0FBQztBQUMvQ0QsT0FBTyxDQUFDRSxJQUFJLEdBQUdELE9BQU8sQ0FBQyxRQUFRLENBQUM7QUFFaENELE9BQU8sQ0FBQyxzQkFBc0IsQ0FBQyxHQUFHQSxPQUFPLENBQUNFLElBQUk7QUFFOUMsTUFBTUMsTUFBTSxHQUFHRixPQUFPLENBQUMsU0FBUyxDQUFDO0FBRWpDRCxPQUFPLENBQUMsMEJBQTBCLENBQUMsR0FBR0csTUFBTTtBQUM1Q0gsT0FBTyxDQUFDLGlCQUFpQixDQUFDLEdBQUdHLE1BQU07QUFDbkNILE9BQU8sQ0FBQ0ksS0FBSyxHQUFHRCxNQUFNIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/json.js b/node_modules/superagent/lib/node/parsers/json.js new file mode 100644 index 0000000000000000000000000000000000000000..bce03c99d9cdc30be60ed39a05fc0f4d75f1a182 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/json.js @@ -0,0 +1,25 @@ +"use strict"; + +module.exports = function (res, fn) { + res.text = ''; + res.setEncoding('utf8'); + res.on('data', chunk => { + res.text += chunk; + }); + res.on('end', () => { + let body; + let error; + try { + body = res.text && JSON.parse(res.text); + } catch (err) { + error = err; + // issue #675: return the raw response if the response parsing fails + error.rawResponse = res.text || null; + // issue #876: return the http status code if the response parsing fails + error.statusCode = res.statusCode; + } finally { + fn(error, body); + } + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIiwiYm9keSIsImVycm9yIiwiSlNPTiIsInBhcnNlIiwiZXJyIiwicmF3UmVzcG9uc2UiLCJzdGF0dXNDb2RlIl0sInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL25vZGUvcGFyc2Vycy9qc29uLmpzIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gZnVuY3Rpb24gKHJlcywgZm4pIHtcbiAgcmVzLnRleHQgPSAnJztcbiAgcmVzLnNldEVuY29kaW5nKCd1dGY4Jyk7XG4gIHJlcy5vbignZGF0YScsIChjaHVuaykgPT4ge1xuICAgIHJlcy50ZXh0ICs9IGNodW5rO1xuICB9KTtcbiAgcmVzLm9uKCdlbmQnLCAoKSA9PiB7XG4gICAgbGV0IGJvZHk7XG4gICAgbGV0IGVycm9yO1xuICAgIHRyeSB7XG4gICAgICBib2R5ID0gcmVzLnRleHQgJiYgSlNPTi5wYXJzZShyZXMudGV4dCk7XG4gICAgfSBjYXRjaCAoZXJyKSB7XG4gICAgICBlcnJvciA9IGVycjtcbiAgICAgIC8vIGlzc3VlICM2NzU6IHJldHVybiB0aGUgcmF3IHJlc3BvbnNlIGlmIHRoZSByZXNwb25zZSBwYXJzaW5nIGZhaWxzXG4gICAgICBlcnJvci5yYXd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BQ1JYLEVBQUUsQ0FBQ00sS0FBSyxFQUFFRCxJQUFJLENBQUM7SUFDakI7RUFDRixDQUFDLENBQUM7QUFDSixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/text.js b/node_modules/superagent/lib/node/parsers/text.js new file mode 100644 index 0000000000000000000000000000000000000000..2304042a77cedef4391c07b57e7f9d809af67429 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/text.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = (res, fn) => { + res.text = ''; + res.setEncoding('utf8'); + res.on('data', chunk => { + res.text += chunk; + }); + res.on('end', fn); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIl0sInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL25vZGUvcGFyc2Vycy90ZXh0LmpzIl0sInNvdXJjZXNDb250ZW50IjpbIm1vZHVsZS5leHBvcnRzID0gKHJlcywgZm4pID0+IHtcbiAgcmVzLnRleHQgPSAnJztcbiAgcmVzLnNldEVuY29kaW5nKCd1dGY4Jyk7XG4gIHJlcy5vbignZGF0YScsIChjaHVuaykgPT4ge1xuICAgIHJlcy50ZXh0ICs9IGNodW5rO1xuICB9KTtcbiAgcmVzLm9uKCdlbmQnLCBmbik7XG59O1xuIl0sIm1hcHBpbmdzIjoiOztBQUFBQSxNQUFNLENBQUNDLE9BQU8sR0FBRyxDQUFDQyxHQUFHLEVBQUVDLEVBQUUsS0FBSztFQUM1QkQsR0FBRyxDQUFDRSxJQUFJLEdBQUcsRUFBRTtFQUNiRixHQUFHLENBQUNHLFdBQVcsQ0FBQyxNQUFNLENBQUM7RUFDdkJILEdBQUcsQ0FBQ0ksRUFBRSxDQUFDLE1BQU0sRUFBR0MsS0FBSyxJQUFLO0lBQ3hCTCxHQUFHLENBQUNFLElBQUksSUFBSUcsS0FBSztFQUNuQixDQUFDLENBQUM7RUFDRkwsR0FBRyxDQUFDSSxFQUFFLENBQUMsS0FBSyxFQUFFSCxFQUFFLENBQUM7QUFDbkIsQ0FBQyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/parsers/urlencoded.js b/node_modules/superagent/lib/node/parsers/urlencoded.js new file mode 100644 index 0000000000000000000000000000000000000000..ea58bfa5b8a1729f2ee9499a2da88cb60fd79605 --- /dev/null +++ b/node_modules/superagent/lib/node/parsers/urlencoded.js @@ -0,0 +1,22 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const qs = require('qs'); +module.exports = (res, fn) => { + res.text = ''; + res.setEncoding('ascii'); + res.on('data', chunk => { + res.text += chunk; + }); + res.on('end', () => { + try { + fn(null, qs.parse(res.text)); + } catch (err) { + fn(err); + } + }); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJxcyIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwicmVzIiwiZm4iLCJ0ZXh0Iiwic2V0RW5jb2RpbmciLCJvbiIsImNodW5rIiwicGFyc2UiLCJlcnIiXSwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvbm9kZS9wYXJzZXJzL3VybGVuY29kZWQuanMiXSwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4gKiBNb2R1bGUgZGVwZW5kZW5jaWVzLlxuICovXG5cbmNvbnN0IHFzID0gcmVxdWlyZSgncXMnKTtcblxubW9kdWxlLmV4cG9ydHMgPSAocmVzLCBmbikgPT4ge1xuICByZXMudGV4dCA9ICcnO1xuICByZXMuc2V0RW5jb2RpbmcoJ2FzY2lpJyk7XG4gIHJlcy5vbignZGF0YScsIChjaHVuaykgPT4ge1xuICAgIHJlcy50ZXh0ICs9IGNodW5rO1xuICB9KTtcbiAgcmVzLm9uKCdlbmQnLCAoKSA9PiB7XG4gICAgdHJ5IHtcbiAgICAgIGZuKG51bGwsIHFzLnBhcnNlKHJlcy50ZXh0KSk7XG4gICAgfSBjYXRjaCAoZXJyKSB7XG4gICAgICBmbihlcnIpO1xuICAgIH1cbiAgfSk7XG59O1xuIl0sIm1hcHBpbmdzIjoiOztBQUFBO0FBQ0E7QUFDQTs7QUFFQSxNQUFNQSxFQUFFLEdBQUdDLE9BQU8sQ0FBQyxJQUFJLENBQUM7QUFFeEJDLE1BQU0sQ0FBQ0MsT0FBTyxHQUFHLENBQUNDLEdBQUcsRUFBRUMsRUFBRSxLQUFLO0VBQzVCRCxHQUFHLENBQUNFLElBQUksR0FBRyxFQUFFO0VBQ2JGLEdBQUcsQ0FBQ0csV0FBVyxDQUFDLE9BQU8sQ0FBQztFQUN4QkgsR0FBRyxDQUFDSSxFQUFFLENBQUMsTUFBTSxFQUFHQyxLQUFLLElBQUs7SUFDeEJMLEdBQUcsQ0FBQ0UsSUFBSSxJQUFJRyxLQUFLO0VBQ25CLENBQUMsQ0FBQztFQUNGTCxHQUFHLENBQUNJLEVBQUUsQ0FBQyxLQUFLLEVBQUUsTUFBTTtJQUNsQixJQUFJO01BQ0ZILEVBQUUsQ0FBQyxJQUFJLEVBQUVMLEVBQUUsQ0FBQ1UsS0FBSyxDQUFDTixHQUFHLENBQUNFLElBQUksQ0FBQyxDQUFDO0lBQzlCLENBQUMsQ0FBQyxPQUFPSyxHQUFHLEVBQUU7TUFDWk4sRUFBRSxDQUFDTSxHQUFHLENBQUM7SUFDVDtFQUNGLENBQUMsQ0FBQztBQUNKLENBQUMiLCJpZ25vcmVMaXN0IjpbXX0= \ No newline at end of file diff --git a/node_modules/superagent/lib/node/response.js b/node_modules/superagent/lib/node/response.js new file mode 100644 index 0000000000000000000000000000000000000000..3514fc7d5c373cc0ed0b762d73ac166c782cc1c5 --- /dev/null +++ b/node_modules/superagent/lib/node/response.js @@ -0,0 +1,143 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const util = require('util'); +const Stream = require('stream'); +const ResponseBase = require('../response-base'); +const { + mixin +} = require('../utils'); + +/** + * Expose `Response`. + */ + +module.exports = Response; + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * @param {Request} req + * @param {Object} options + * @constructor + * @extends {Stream} + * @implements {ReadableStream} + * @api private + */ + +function Response(request) { + Stream.call(this); + this.res = request.res; + const { + res + } = this; + this.request = request; + this.req = request.req; + this.text = res.text; + this.files = res.files || {}; + this.buffered = request._resBuffered; + this.headers = res.headers; + this.header = this.headers; + this._setStatusProperties(res.statusCode); + this._setHeaderProperties(this.header); + this.setEncoding = res.setEncoding.bind(res); + res.on('data', this.emit.bind(this, 'data')); + res.on('end', this.emit.bind(this, 'end')); + res.on('close', this.emit.bind(this, 'close')); + res.on('error', this.emit.bind(this, 'error')); +} + +// Lazy access res.body. +// https://github.com/nodejs/node/pull/39520#issuecomment-889697136 +Object.defineProperty(Response.prototype, 'body', { + get() { + return this._body !== undefined ? this._body : this.res.body !== undefined ? this.res.body : {}; + }, + set(value) { + this._body = value; + } +}); + +/** + * Inherit from `Stream`. + */ + +util.inherits(Response, Stream); +mixin(Response.prototype, ResponseBase.prototype); + +/** + * Implements methods of a `ReadableStream` + */ + +Response.prototype.destroy = function (error) { + this.res.destroy(error); +}; + +/** + * Pause. + */ + +Response.prototype.pause = function () { + this.res.pause(); +}; + +/** + * Resume. + */ + +Response.prototype.resume = function () { + this.res.resume(); +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function () { + const { + req + } = this; + const { + method + } = req; + const { + path + } = req; + const message = `cannot ${method} ${path} (${this.status})`; + const error = new Error(message); + error.status = this.status; + error.text = this.text; + error.method = method; + error.path = path; + return error; +}; +Response.prototype.setStatusProperties = function (status) { + console.warn('In superagent 2.x setStatusProperties is a private method'); + return this._setStatusProperties(status); +}; + +/** + * To json. + * + * @return {Object} + * @api public + */ + +Response.prototype.toJSON = function () { + return { + req: this.request.toJSON(), + header: this.header, + status: this.status, + text: this.text + }; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1dGlsIiwicmVxdWlyZSIsIlN0cmVhbSIsIlJlc3BvbnNlQmFzZSIsIm1peGluIiwibW9kdWxlIiwiZXhwb3J0cyIsIlJlc3BvbnNlIiwicmVxdWVzdCIsImNhbGwiLCJyZXMiLCJyZXEiLCJ0ZXh0IiwiZmlsZXMiLCJidWZmZXJlZCIsIl9yZXNCdWZmZXJlZCIsImhlYWRlcnMiLCJoZWFkZXIiLCJfc2V0U3RhdHVzUHJvcGVydGllcyIsInN0YXR1c0NvZGUiLCJfc2V0SGVhZGVyUHJvcGVydGllcyIsInNldEVuY29kaW5nIiwiYmluZCIsIm9uIiwiZW1pdCIsIk9iamVjdCIsImRlZmluZVByb3BlcnR5IiwicHJvdG90eXBlIiwiZ2V0IiwiX2JvZHkiLCJ1bmRlZmluZWQiLCJib2R5Iiwic2V0IiwidmFsdWUiLCJpbmhlcml0cyIsImRlc3Ryb3kiLCJlcnJvciIsInBhdXNlIiwicmVzdW1lIiwidG9FcnJvciIsIm1ldGhvZCIsInBhdGgiLCJtZXNzYWdlIiwic3RhdHVzIiwiRXJyb3IiLCJzZXRTdGF0dXNQcm9wZXJ0aWVzIiwiY29uc29sZSIsIndhcm4iLCJ0b0pTT04iXSwic291cmNlcyI6WyIuLi8uLi9zcmMvbm9kZS9yZXNwb25zZS5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIE1vZHVsZSBkZXBlbmRlbmNpZXMuXG4gKi9cblxuY29uc3QgdXRpbCA9IHJlcXVpcmUoJ3V0aWwnKTtcbmNvbnN0IFN0cmVhbSA9IHJlcXVpcmUoJ3N0cmVhbScpO1xuY29uc3QgUmVzcG9uc2VCYXNlID0gcmVxdWlyZSgnLi4vcmVzcG9uc2UtYmFzZScpO1xuY29uc3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0Isb0JBQW9CLENBQUN5QixNQUFNLENBQUM7QUFDMUMsQ0FBQzs7QUFFRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUFwQyxRQUFRLENBQUNvQixTQUFTLENBQUNxQixNQUFNLEdBQUcsWUFBWTtFQUN0QyxPQUFPO0lBQ0xyQyxHQUFHLEVBQUUsSUFBSSxDQUFDSCxPQUFPLENBQUN3QyxNQUFNLENBQUMsQ0FBQztJQUMxQi9CLE1BQU0sRUFBRSxJQUFJLENBQUNBLE1BQU07SUFDbkIwQixNQUFNLEVBQUUsSUFBSSxDQUFDQSxNQUFNO0lBQ25CL0IsSUFBSSxFQUFFLElBQUksQ0FBQ0E7RUFDYixDQUFDO0FBQ0gsQ0FBQyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/lib/node/unzip.js b/node_modules/superagent/lib/node/unzip.js new file mode 100644 index 0000000000000000000000000000000000000000..b473d16b3882ee22d809bc18e4008741024b5536 --- /dev/null +++ b/node_modules/superagent/lib/node/unzip.js @@ -0,0 +1,74 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const { + StringDecoder +} = require('string_decoder'); +const Stream = require('stream'); +const { + chooseDecompresser +} = require('./decompress'); + +/** + * Buffers response data events and re-emits when they're decompressed. + * + * @param {Request} req + * @param {Response} res + * @api private + */ + +exports.decompress = (request, res) => { + let decompresser = chooseDecompresser(res); + const stream = new Stream(); + let decoder; + + // make node responseOnEnd() happy + stream.req = request; + decompresser.on('error', error => { + if (error && error.code === 'Z_BUF_ERROR') { + // unexpected end of file is ignored by browsers and curl + stream.emit('end'); + return; + } + stream.emit('error', error); + }); + + // pipe to unzip + res.pipe(decompresser); + + // override `setEncoding` to capture encoding + res.setEncoding = type => { + decoder = new StringDecoder(type); + }; + + // decode upon decompressing with captured encoding + decompresser.on('data', buf => { + if (decoder) { + const string_ = decoder.write(buf); + if (string_.length > 0) stream.emit('data', string_); + } else { + stream.emit('data', buf); + } + }); + decompresser.on('end', () => { + stream.emit('end'); + }); + + // override `on` to capture data listeners + const _on = res.on; + res.on = function (type, fn) { + if (type === 'data' || type === 'end') { + stream.on(type, fn.bind(res)); + } else if (type === 'error') { + stream.on(type, fn.bind(res)); + _on.call(res, type, fn); + } else { + _on.call(res, type, fn); + } + return this; + }; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJTdHJpbmdEZWNvZGVyIiwicmVxdWlyZSIsIlN0cmVhbSIsImNob29zZURlY29tcHJlc3NlciIsImV4cG9ydHMiLCJkZWNvbXByZXNzIiwicmVxdWVzdCIsInJlcyIsImRlY29tcHJlc3NlciIsInN0cmVhbSIsImRlY29kZXIiLCJyZXEiLCJvbiIsImVycm9yIiwiY29kZSIsImVtaXQiLCJwaXBlIiwic2V0RW5jb2RpbmciLCJ0eXBlIiwiYnVmIiwic3RyaW5nXyIsIndyaXRlIiwibGVuZ3RoIiwiX29uIiwiZm4iLCJiaW5kIiwiY2FsbCJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ub2RlL3VuemlwLmpzIl0sInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogTW9kdWxlIGRlcGVuZGVuY2llcy5cbiAqL1xuXG5jb25zdCB7IFN0cmluZ0RlY29kZXIgfSA9IHJlcXVpcmUoJ3N0cmluZ19kZWNvZGVyJyk7XG5jb25zdCBTdHJlYW0gPSByZXF1aXJlKCdzdHJlYW0nKTtcbmNvbnN0IHsgY2hvb3NlRGVjb21wcmVzc2VyIH0gPSByZXF1aXJlKCcuL2RlY29tcHJlc3MnKTtcblxuLyoqXG4gKiBCdWZmZXJzIHJlc3BvbnNlIGRhdGEgZXZlbnRzIGFuZCByZS1lbWl0cyB3aGVuIHRoZXkncmUgZGVjb21wcmVzc2VkLlxuICpcbiAqIEBwYXJhbSB7UmVxdWVzdH0gcmVxXG4gKiBAcGFyYW0ge1Jlc3BvbnNlfSByZXNcbiAqIEBhc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BTSxDQUFDTSxJQUFJLENBQUMsTUFBTSxFQUFFSSxHQUFHLENBQUM7SUFDMUI7RUFDRixDQUFDLENBQUM7RUFFRlgsWUFBWSxDQUFDSSxFQUFFLENBQUMsS0FBSyxFQUFFLE1BQU07SUFDM0JILE1BQU0sQ0FBQ00sSUFBSSxDQUFDLEtBQUssQ0FBQztFQUNwQixDQUFDLENBQUM7O0VBRUY7RUFDQSxNQUFNUSxHQUFHLEdBQUdoQixHQUFHLENBQUNLLEVBQUU7RUFDbEJMLEdBQUcsQ0FBQ0ssRUFBRSxHQUFHLFVBQVVNLElBQUksRUFBRU0sRUFBRSxFQUFFO0lBQzNCLElBQUlOLElBQUksS0FBSyxNQUFNLElBQUlBLElBQUksS0FBSyxLQUFLLEVBQUU7TUFDckNULE1BQU0sQ0FBQ0csRUFBRSxDQUFDTSxJQUFJLEVBQUVNLEVBQUUsQ0FBQ0MsSUFBSSxDQUFDbEIsR0FBRyxDQUFDLENBQUM7SUFDL0IsQ0FBQyxNQUFNLElBQUlXLElBQUksS0FBSyxPQUFPLEVBQUU7TUFDM0JULE1BQU0sQ0FBQ0csRUFBRSxDQUFDTSxJQUFJLEVBQUVNLEVBQUUsQ0FBQ0MsSUFBSSxDQUFDbEIsR0FBRyxDQUFDLENBQUM7TUFDN0JnQixHQUFHLENBQUNHLElBQUksQ0FBQ25CLEdBQUcsRUFBRVcsSUFBSSxFQUFFTSxFQUFFLENBQUM7SUFDekIsQ0FBQyxNQUFNO01BQ0xELEdBQUcsQ0FBQ0csSUFBSSxDQUFDbkIsR0FBRyxFQUFFVyxJQUFJLEVBQUVNLEVBQUUsQ0FBQztJQUN6QjtJQUVBLE9BQU8sSUFBSTtFQUNiLENBQUM7QUFDSCxDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/request-base.js b/node_modules/superagent/lib/request-base.js new file mode 100644 index 0000000000000000000000000000000000000000..19fbbd28c5c9a6aa6cd01186264fc5ba4deb3a42 --- /dev/null +++ b/node_modules/superagent/lib/request-base.js @@ -0,0 +1,720 @@ +"use strict"; + +/** + * Module of mixed-in functions shared between node and client code + */ +const { + isObject, + hasOwn +} = require('./utils'); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase() {} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function () { + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + clearTimeout(this._uploadTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + delete this._uploadTimeoutTimer; + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function (fn) { + this._parser = fn; + return this; +}; + +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.responseType = function (value) { + this._responseType = value; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function (fn) { + this._serializer = fn; + return this; +}; + +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, deadline} + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function (options) { + if (!options || typeof options !== 'object') { + this._timeout = options; + this._responseTimeout = 0; + this._uploadTimeout = 0; + return this; + } + for (const option in options) { + if (hasOwn(options, option)) { + switch (option) { + case 'deadline': + this._timeout = options.deadline; + break; + case 'response': + this._responseTimeout = options.response; + break; + case 'upload': + this._uploadTimeout = options.upload; + break; + default: + console.warn('Unknown timeout option', option); + } + } + } + return this; +}; + +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @param {Function} [fn] + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.retry = function (count, fn) { + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + this._retryCallback = fn; + return this; +}; + +// +// NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package +// +// +// NOTE: we do not include EADDRINFO because it was removed from libuv in 2014 +// +// +// +// +// TODO: expose these as configurable defaults +// +const ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); +const STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); + +// TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) +// const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']); + +/** + * Determine if a request should be retried. + * (Inspired by https://github.com/sindresorhus/got#retry) + * + * @param {Error} err an error + * @param {Response} [res] response + * @returns {Boolean} if segment should be retried + */ +RequestBase.prototype._shouldRetry = function (error, res) { + if (!this._maxRetries || this._retries++ >= this._maxRetries) { + return false; + } + if (this._retryCallback) { + try { + const override = this._retryCallback(error, res); + if (override === true) return true; + if (override === false) return false; + // undefined falls back to defaults + } catch (err) { + console.error(err); + } + } + + // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) + /* + if ( + this.req && + this.req.method && + !METHODS.has(this.req.method.toUpperCase()) + ) + return false; + */ + if (res && res.status && STATUS_CODES.has(res.status)) return true; + if (error) { + if (error.code && ERROR_CODES.has(error.code)) return true; + // Superagent timeout + if (error.timeout && error.code === 'ECONNABORTED') return true; + if (error.crossDomain) return true; + } + return false; +}; + +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + +RequestBase.prototype._retry = function () { + this.clearTimeout(); + + // node + if (this.req) { + this.req = null; + this.req = this.request(); + } + this._aborted = false; + this.timedout = false; + this.timedoutError = null; + return this._end(); +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + +RequestBase.prototype.then = function (resolve, reject) { + if (!this._fullfilledPromise) { + const self = this; + if (this._endCalled) { + console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); + } + this._fullfilledPromise = new Promise((resolve, reject) => { + self.on('abort', () => { + if (this._maxRetries && this._maxRetries > this._retries) { + return; + } + if (this.timedout && this.timedoutError) { + reject(this.timedoutError); + return; + } + const error = new Error('Aborted'); + error.code = 'ABORTED'; + error.status = this.status; + error.method = this.method; + error.url = this.url; + reject(error); + }); + self.end((error, res) => { + if (error) reject(error);else resolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +}; +RequestBase.prototype.catch = function (callback) { + return this.then(undefined, callback); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function (fn) { + fn(this); + return this; +}; +RequestBase.prototype.ok = function (callback) { + if (typeof callback !== 'function') throw new Error('Callback required'); + this._okCallback = callback; + return this; +}; +RequestBase.prototype._isResponseOK = function (res) { + if (!res) { + return false; + } + if (this._okCallback) { + return this._okCallback(res); + } + return res.status >= 200 && res.status < 300; +}; + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function (field) { + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function (field, value) { + if (isObject(field)) { + for (const key in field) { + if (hasOwn(field, key)) this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = value; + this.header[field] = value; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field field name + */ +RequestBase.prototype.unset = function (field) { + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name name of field + * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field + * @param {String} options extra options, e.g. 'blob' + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function (name, value, options) { + // name should be either a string or an object. + if (name === null || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + if (this._data) { + throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + if (isObject(name)) { + for (const key in name) { + if (hasOwn(name, key)) this.field(key, name[key]); + } + return this; + } + if (Array.isArray(value)) { + for (const i in value) { + if (hasOwn(value, i)) this.field(name, value[i]); + } + return this; + } + + // val should be defined now + if (value === null || undefined === value) { + throw new Error('.field(name, val) val can not be empty'); + } + if (typeof value === 'boolean') { + value = String(value); + } + + // fix https://github.com/ladjs/superagent/issues/1680 + if (options) this._getFormData().append(name, value, options);else this._getFormData().append(name, value); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} request + * @api public + */ +RequestBase.prototype.abort = function () { + if (this._aborted) { + return this; + } + this._aborted = true; + if (this.xhr) this.xhr.abort(); // browser + if (this.req) { + this.req.abort(); // node + } + this.clearTimeout(); + this.emit('abort'); + return this; +}; +RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { + switch (options.type) { + case 'basic': + this.set('Authorization', `Basic ${base64Encoder(`${user}:${pass}`)}`); + break; + case 'auto': + this.username = user; + this.password = pass; + break; + case 'bearer': + // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', `Bearer ${user}`); + break; + default: + break; + } + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * @param {Boolean} [on=true] - Set 'withCredentials' state + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.withCredentials = function (on) { + // This is browser-only functionality. Node side is no-op. + if (on === undefined) on = true; + this._withCredentials = on; + return this; +}; + +/** + * Set the max redirects to `n`. Does nothing in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function (n) { + this._maxRedirects = n; + return this; +}; + +/** + * Maximum size of buffered response body, in bytes. Counts uncompressed size. + * Default 200MB. + * + * @param {Number} n number of bytes + * @return {Request} for chaining + */ +RequestBase.prototype.maxResponseSize = function (n) { + if (typeof n !== 'number') { + throw new TypeError('Invalid argument'); + } + this._maxResponseSize = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function () { + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +// eslint-disable-next-line complexity +RequestBase.prototype.send = function (data) { + const isObject_ = isObject(data); + let type = this._header['content-type']; + if (this._formData) { + throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + if (isObject_ && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw new Error("Can't merge these send calls"); + } + + // merge + if (isObject_ && isObject(this._data)) { + for (const key in data) { + if (typeof data[key] == 'bigint' && !data[key].toJSON) throw new Error('Cannot serialize BigInt value to json'); + if (hasOwn(data, key)) this._data[key] = data[key]; + } + } else if (typeof data === 'bigint') throw new Error("Cannot send value of type BigInt");else if (typeof data === 'string') { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if (type) type = type.toLowerCase().trim(); + if (type === 'application/x-www-form-urlencoded') { + this._data = this._data ? `${this._data}&${data}` : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + if (!isObject_ || this._isHost(data)) { + return this; + } + + // default to json + if (!type) this.type('json'); + return this; +}; + +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.sortQuery = function (sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ +RequestBase.prototype._finalizeQueryString = function () { + const query = this._query.join('&'); + if (query) { + this.url += (this.url.includes('?') ? '&' : '?') + query; + } + this._query.length = 0; // Makes the call idempotent + + if (this._sort) { + const index = this.url.indexOf('?'); + if (index >= 0) { + const queryArray = this.url.slice(index + 1).split('&'); + if (typeof this._sort === 'function') { + queryArray.sort(this._sort); + } else { + queryArray.sort(); + } + this.url = this.url.slice(0, index) + '?' + queryArray.join('&'); + } + } +}; + +// For backwards compat only +RequestBase.prototype._appendQueryString = () => { + console.warn('Unsupported'); +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +RequestBase.prototype._timeoutError = function (reason, timeout, errno) { + if (this._aborted) { + return; + } + const error = new Error(`${reason + timeout}ms exceeded`); + error.timeout = timeout; + error.code = 'ECONNABORTED'; + error.errno = errno; + this.timedout = true; + this.timedoutError = error; + this.abort(); + this.callback(error); +}; +RequestBase.prototype._setTimeouts = function () { + const self = this; + + // deadline + if (this._timeout && !this._timer) { + this._timer = setTimeout(() => { + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } + + // response timeout + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(() => { + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJpc09iamVjdCIsImhhc093biIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwiUmVxdWVzdEJhc2UiLCJwcm90b3R5cGUiLCJjbGVhclRpbWVvdXQiLCJfdGltZXIiLCJfcmVzcG9uc2VUaW1lb3V0VGltZXIiLCJfdXBsb2FkVGltZW91dFRpbWVyIiwicGFyc2UiLCJmbiIsIl9wYXJzZXIiLCJ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XMuX3JldHJpZXMpIHtcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cblxuICAgICAgICBpZiAodGhpcy50aW1lZG91dCAmJiB0aGlzLnRpbWVkb3V0RXJyb3IpIHtcbiAgICAgICAgICByZWplY3QodGhpcy50aW1lZG91dEVycm9yKTtcbiAgICAgICAgICByZXR1cm47XG4gICAgICAgIH1cblxuICAgICAgICBjb25zdCBlcnJvciA9IG5ldyBFcnJvcignQWJvcnRlZCcpO1xuICAgICAgICBlcnJvci5jb2RlID0gJ0FCT1JURUQnO1xuICAgICAgICBlcnJvci5zdGF0dXMgPSB0aGlzLnN0YXR1cztcbiAgICAgICAgZXJyb3IubWV0aG9kID0gdGhpcy5tZXRob2Q7XG4gICAgICAgIGVycm9yLnVybCA9IHRoaXMudXJsO1xuICAgICAgICByZWplY3QoZXJyb3IpO1xuICAgICAgfSk7XG4gICAgICBzZWxmLmVuZCgoZXJyb3IsIHJlcykgPT4ge1xuICAgICAgICBpZiAoZXJyb3IpIHJlamVjdChlcnJvcik7XG4gICAgICAgIGVsc2UgcmVzb2x2ZShyZXMpO1xuICAgICAgfSk7XG4gICAgfSk7XG4gIH1cblxuICByZXR1cm4gdGhpcy5fZnVsbGZpbGxlZFByb21pc2UudGhlbihyZXNvbHZlLCByZWplY3QpO1xufTtcblxuUmVxdWVzdEJhc2UucHJvdG90eXBlLmNhdGNoID0gZnVuY3Rpb24gKGNhbGxiYWNrKSB7XG4gIHJldHVybiB0aGlzLnRoZW4odW5kZWZpbmVkLCBjYWxsYmFjayk7XG59O1xuXG4vKipcbiAqIEFsbG93IGZvciBleHRlbnNpb25cbiAqL1xuXG5SZXF1ZXN0QmFzZS5wcm90b3R5cGUudXNlID0gZnVuY3Rpb24gKGZuKSB7XG4gIGZuKHRoaXMpO1xuICByZXR1cm4gdGhpcztcbn07XG5cblJlcXVlc3RCYXNlLnByb3RvdHlwZS5vayA9IGZ1bmN0aW9uIChjYWxsYmFjaykge1xuICBpZiAodHlwZW9mI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VxdWVzdC5wb3N0KCcvdXNlcicpXG4gKiAgICAgICAgIC50eXBlKCdqc29uJylcbiAqICAgICAgICAgLnNlbmQoJ3tcIm5hbWVcIjpcInRqXCJ9JylcbiAqICAgICAgICAgLmVuZChjYWxsYmFjaylcbiAqXG4gKiAgICAgICAvLyBhdXRvIGpzb25cbiAqICAgICAgIHJlcXVlc3QucG9zdCgnL3VzZXInKVxuICogICAgICAgICAuc2VuZCh7IG5hbWU6ICd0aicgfSlcbiAqICAgICAgICAgLmVuZChjYWxsYmFjaylcbiAqXG4gKiAgICAgICAvLyBtYW51YWwgeC13d3ctZm9ybS11cmxlbmNvZGVkXG4gKiAgICAgICByZXF1ZXN0LnBvc3QoJy91c2VyJylcbiAqICAgICAgICAgLnR5cGUoJ2Zvcm0nKVxuICogICAgICAgICAuc2VuZCgnbmFtZT10aicpXG4gKiAgICAgICAgIC5lbmQoY2FsbGJhY2spXG4gKlxuICogICAgICAgLy8gYXV0byB4LXd3dy1mb3JtLXVybGVuY29kZWRcbiAqICAgICAgIHJlcXVlc3QucG9zdCgnL3VzZXInKVxuICogICAgICAgICAudHlwZSgnZm9ybScpXG4gKiAgICAgICAgIC5zZW5kKHsgbmFtZTogJ3RqJyB9KVxuICogICAgICAgICAuZW5kKGNhbGxiYWNrKVxuICpcbiAqICAgICAgIC8vIGRlZmF1bHRzIHRvIHgtd3d3LWZvcm0tdXJsZW5jb2RlZFxuICogICAgICByZXF1ZXN0LnBvc3QoJy91c2VyJylcbiAqICAgICAgICAuc2VuZCgnbmFtZT10b2JpJylcbiAqICAgICAgICAuc2VuZCgnc3BlY2llcz1mZXJyZXQnKVxuICogICAgICAgIC5lbmQoY2FsbGJhY2spXG4gKlxuICogQHBhcmFtIHtTdHJpbmd8T2JqZWN0fSBkYXRhXG4gKiBAcmV0dXJuIHtSZXF1ZXN0fSBmb3IgY2hhaW5pbmdcbiAqIEBhcGkgcHVibGljXG4gKi9cblxuLy8gZXNsaW50LWRpc2FibGUtbmV4dC1sa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HQSxLQUFLO0VBQ25CLElBQUksQ0FBQ2pGLFFBQVEsR0FBRyxJQUFJO0VBQ3BCLElBQUksQ0FBQ0MsYUFBYSxHQUFHYixLQUFLO0VBQzFCLElBQUksQ0FBQ21ELEtBQUssQ0FBQyxDQUFDO0VBQ1osSUFBSSxDQUFDdkIsUUFBUSxDQUFDNUIsS0FBSyxDQUFDO0FBQ3RCLENBQUM7QUFFRHBDLFdBQVcsQ0FBQ0MsU0FBUyxDQUFDaUksWUFBWSxHQUFHLFlBQVk7RUFDL0MsTUFBTTNFLElBQUksR0FBRyxJQUFJOztFQUVqQjtFQUNBLElBQUksSUFBSSxDQUFDdkMsUUFBUSxJQUFJLENBQUMsSUFBSSxDQUFDYixNQUFNLEVBQUU7SUFDakMsSUFBSSxDQUFDQSxNQUFNLEdBQUdnSSxVQUFVLENBQUMsTUFBTTtNQUM3QjVFLElBQUksQ0FBQ3dFLGFBQWEsQ0FBQyxhQUFhLEVBQUV4RSxJQUFJLENBQUN2QyxRQUFRLEVBQUUsT0FBTyxDQUFDO0lBQzNELENBQUMsRUFBRSxJQUFJLENBQUNBLFFBQVEsQ0FBQztFQUNuQjs7RUFFQTtFQUNBLElBQUksSUFBSSxDQUFDQyxnQkFBZ0IsSUFBSSxDQUFDLElBQUksQ0FBQ2IscUJBQXFCLEVBQUU7SUFDeEQsSUFBSSxDQUFDQSxxQkFBcUIsR0FBRytILFVBQVUsQ0FBQyxNQUFNO01BQzVDNUUsSUFBSSxDQUFDd0UsYUFBYSxDQUNoQixzQkFBc0IsRUFDdEJ4RSxJQUFJLENBQUN0QyxnQkFBZ0IsRUFDckIsV0FDRixDQUFDO0lBQ0gsQ0FBQyxFQUFFLElBQUksQ0FBQ0EsZ0JBQWdCLENBQUM7RUFDM0I7QUFDRixDQUFDIiwiaWdub3JlTGlzdCI6W119 \ No newline at end of file diff --git a/node_modules/superagent/lib/response-base.js b/node_modules/superagent/lib/response-base.js new file mode 100644 index 0000000000000000000000000000000000000000..32157bf70e0e11e923a6de4e7e9450504747c252 --- /dev/null +++ b/node_modules/superagent/lib/response-base.js @@ -0,0 +1,120 @@ +"use strict"; + +/** + * Module dependencies. + */ + +const utils = require('./utils'); + +/** + * Expose `ResponseBase`. + */ + +module.exports = ResponseBase; + +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase() {} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +ResponseBase.prototype.get = function (field) { + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +ResponseBase.prototype._setHeaderProperties = function (header) { + // TODO: moar! + // TODO: make this a util + + // content-type + const ct = header['content-type'] || ''; + this.type = utils.type(ct); + + // params + const parameters = utils.params(ct); + for (const key in parameters) { + if (Object.prototype.hasOwnProperty.call(parameters, key)) this[key] = parameters[key]; + } + this.links = {}; + + // links + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (err) { + // ignore + } +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +ResponseBase.prototype._setStatusProperties = function (status) { + const type = Math.trunc(status / 100); + + // status / class + this.statusCode = status; + this.status = this.statusCode; + this.statusType = type; + + // basics + this.info = type === 1; + this.ok = type === 2; + this.redirect = type === 3; + this.clientError = type === 4; + this.serverError = type === 5; + this.error = type === 4 || type === 5 ? this.toError() : false; + + // sugar + this.created = status === 201; + this.accepted = status === 202; + this.noContent = status === 204; + this.badRequest = status === 400; + this.unauthorized = status === 401; + this.notAcceptable = status === 406; + this.forbidden = status === 403; + this.notFound = status === 404; + this.unprocessableEntity = status === 422; +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1dGlscyIsInJlcXVpcmUiLCJtb2R1bGUiLCJleHBvcnRzIiwiUmVzcG9uc2VCYXNlIiwicHJvdG90eXBlIiwiZ2V0IiwiZmllbGQiLCJoZWFkZXIiLCJ0b0xvd2VyQ2FzZSIsIl9zZXRIZWFkZXJQcm9wZXJ0aWVzIiwiY3QiLCJ0eXBlIiwicGFyYW1ldGVycyIsInBhcmFtcyIsImtleSIsIk9iamVjdCIsImhhc093blByb3BlcnR5IiwiY2FsbCIsImxpbmtzIiwibGluayIsInBhcnNlTGlua3MiLCJlcnIiLCJfc2V0U3RhdHVzUHJvcGVydGllcyIsInN0YXR1cyIsIk1hdGgiLCJ0cnVuYyIsInN0YXR1c0NvZGUiLCJzdGF0dXNUeXBlIiwiaW5mbyIsIm9rIiwicmVkaXJlY3QiLCJjbGllbnRFcnJvciIsInNlcnZlckVycm9yIiwiZXJyb3IiLCJ0b0Vycm9yIiwiY3JlYXRlZCIsImFjY2VwdGVkIiwibm9Db250ZW50IiwiYmFkUmVxdWVzdCIsInVuYXV0aG9yaXplZCIsIm5vdEFjY2VwdGFibGUiLCJmb3JiaWRkZW4iLCJub3RGb3VuZCIsInVucHJvY2Vzc2FibGVFbnRpdHkiXSwic291cmNlcyI6WyIuLi9zcmMvcmVzcG9uc2UtYmFzZS5qcyJdLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIE1vZHVsZSBkZXBlbmRlbmNpZXMuXG4gKi9cblxuY29uc3QgdXRpbHMgPSByZXF1aXJlKCcuL3V0aWxzJyk7XG5cbi8qKlxuICogRXhwb3NlIGBSZXNwb25zZUJhc2VgLlxuICovXG5cbm1vZHVsZS5leHBvcnRzID0gUmVzcG9uc2VCYXNlO1xuXG4vKipcbiAqIEluaXRp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/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..8a1c0bbecbaaa1acc5a56a61bfcd7d7753f79cf5 --- /dev/null +++ b/node_modules/superagent/lib/utils.js @@ -0,0 +1,126 @@ +"use strict"; + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.type = string_ => string_.split(/ *; */).shift(); + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.params = value => { + const object = {}; + for (const string_ of value.split(/ *; */)) { + const parts = string_.split(/ *= */); + const key = parts.shift(); + const value = parts.shift(); + if (key && value) object[key] = value; + } + return object; +}; + +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.parseLinks = value => { + const object = {}; + for (const string_ of value.split(/ *, */)) { + const parts = string_.split(/ *; */); + const url = parts[0].slice(1, -1); + const rel = parts[1].split(/ *= */)[1].slice(1, -1); + object[rel] = url; + } + return object; +}; + +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + +exports.cleanHeader = (header, changesOrigin) => { + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header.host; + // secuirty + if (changesOrigin) { + delete header.authorization; + delete header.cookie; + } + return header; +}; +exports.normalizeHostname = hostname => { + const [, normalized] = hostname.match(/^\[([^\]]+)\]$/) || []; + return normalized || hostname; +}; + +/** + * Check if `obj` is an object. + * + * @param {Object} object + * @return {Boolean} + * @api private + */ +exports.isObject = object => { + return object !== null && typeof object === 'object'; +}; + +/** + * Object.hasOwn fallback/polyfill. + * + * @type {(object: object, property: string) => boolean} object + * @api private + */ +exports.hasOwn = Object.hasOwn || function (object, property) { + if (object == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + return Object.prototype.hasOwnProperty.call(new Object(object), property); +}; +exports.mixin = (target, source) => { + for (const key in source) { + if (exports.hasOwn(source, key)) { + target[key] = source[key]; + } + } +}; + +/** + * Check if the response is compressed using Gzip or Deflate. + * @param {Object} res + * @return {Boolean} + */ + +exports.isGzipOrDeflateEncoding = res => { + return new RegExp(/^\s*(?:deflate|gzip)\s*$/).test(res.headers['content-encoding']); +}; + +/** + * Check if the response is compressed using Brotli. + * @param {Object} res + * @return {Boolean} + */ + +exports.isBrotliEncoding = res => { + return new RegExp(/^\s*(?:br)\s*$/).test(res.headers['content-encoding']); +}; +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJleHBvcnRzIiwidHlwZSIsInN0cmluZ18iLCJzcGxpdCIsInNoaWZ0IiwicGFyYW1zIiwidmFsdWUiLCJvYmplY3QiLCJwYXJ0cyIsImtleSIsInBhcnNlTGlua3MiLCJ1cmwiLCJzbGljZSIsInJlbCIsImNsZWFuSGVhZGVyIiwiaGVhZGVyIiwiY2hhbmdlc09yaWdpbiIsImhvc3QiLCJhdXRob3JpemF0aW9uIiwiY29va2llIiwibm9ybWFsaXplSG9zdG5hbWUiLCJob3N0bmFtZSIsIm5vcm1hbGl6ZWQiLCJtYXRjaCIsImlzT2JqZWN0IiwiaGFzT3duIiwiT2JqZWN0IiwicHJvcGVydHkiLCJUeXBlRXJyb3IiLCJwcm90b3R5cGUiLCJoYXNPd25Qcm9wZXJ0eSIsImNhbGwiLCJtaXhpbiIsInRhcmdldCIsInNvdXJjZSIsImlzR3ppcE9yRGVmbGF0ZUVuY29kaW5nIiwicmVzIiwiUmVnRXhwIiwidGVzdCIsImhlYWRlcnMiLCJpc0Jyb3RsaUVuY29kaW5nIl0sInNvdXJjZXMiOlsiLi4vc3JjL3V0aWxzLmpzIl0sInNvdXJjZXNDb250ZW50IjpbIlxuLyoqXG4gKiBSZXR1cm4gdGhlIG1pbWUgdHlwZSBmb3IgdGhlIGdpdmVuIGBzdHJgLlxuICpcbiAqIEBwYXJhbSB7U3RyaW5nfSBzdHJcbiAqIEByZXR1cm4ge1N0cmluZ31cbiAqIEBhcGkgcHJpdmF0ZVxuICovXG5cbmV4cG9ydHMudHlwZSA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QUs7RUFDbEMsS0FBSyxNQUFNekIsR0FBRyxJQUFJeUIsTUFBTSxFQUFFO0lBQ3hCLElBQUlsQyxPQUFPLENBQUN5QixNQUFNLENBQUNTLE1BQU0sRUFBRXpCLEdBQUcsQ0FBQyxFQUFFO01BQy9Cd0IsTUFBTSxDQUFDeEIsR0FBRyxDQUFDLEdBQUd5QixNQUFNLENBQUN6QixHQUFHLENBQUM7SUFDM0I7RUFDRjtBQUNGLENBQUM7O0FBRUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQVQsT0FBTyxDQUFDbUMsdUJBQXVCLEdBQUlDLEdBQUcsSUFBSztFQUN6QyxPQUFPLElBQUlDLE1BQU0sQ0FBQywwQkFBMEIsQ0FBQyxDQUFDQyxJQUFJLENBQUNGLEdBQUcsQ0FBQ0csT0FBTyxDQUFDLGtCQUFrQixDQUFDLENBQUM7QUFDckYsQ0FBQzs7QUFFRDtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBdkMsT0FBTyxDQUFDd0MsZ0JBQWdCLEdBQUlKLEdBQUcsSUFBSztFQUNsQyxPQUFPLElBQUlDLE1BQU0sQ0FBQyxnQkFBZ0IsQ0FBQyxDQUFDQyxJQUFJLENBQUNGLEdBQUcsQ0FBQ0csT0FBTyxDQUFDLGtCQUFrQixDQUFDLENBQUM7QUFDM0UsQ0FBQyIsImlnbm9yZUxpc3QiOltdfQ== \ No newline at end of file diff --git a/node_modules/superagent/package.json b/node_modules/superagent/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6485ae89d05f4e4098960fd641667e86f931255e --- /dev/null +++ b/node_modules/superagent/package.json @@ -0,0 +1,132 @@ +{ + "name": "superagent", + "description": "elegant & feature rich browser / node HTTP with a fluent API", + "version": "10.3.0", + "author": "TJ Holowaychuk ", + "browser": { + "./src/node/index.js": "./src/client.js", + "./lib/node/index.js": "./lib/client.js", + "./test/support/server.js": "./test/support/blank.js" + }, + "bugs": { + "url": "https://github.com/ladjs/superagent/issues" + }, + "contributors": [ + "Kornel Lesiński ", + "Peter Lyons ", + "Hunter Loftis ", + "Nick Baugh " + ], + "dependencies": { + "component-emitter": "^1.3.1", + "cookiejar": "^2.1.4", + "debug": "^4.3.7", + "fast-safe-stringify": "^2.1.1", + "form-data": "^4.0.5", + "formidable": "^3.5.4", + "methods": "^1.1.2", + "mime": "2.6.0", + "qs": "^6.14.1" + }, + "devDependencies": { + "@babel/cli": "^7.20.7", + "@babel/core": "^7.20.12", + "@babel/plugin-transform-runtime": "^7.19.6", + "@babel/preset-env": "^7.20.2", + "@babel/runtime": "^7.20.13", + "@commitlint/cli": "^19.8.1", + "@commitlint/config-conventional": "^19.8.1", + "babelify": "^10.0.0", + "Base64": "^1.1.0", + "basic-auth-connect": "^1.0.0", + "body-parser": "^1.20.4", + "browserify": "^17.0.0", + "cookie-parser": "^1.4.7", + "cross-env": "^7.0.3", + "eslint": "^8.32.0", + "eslint-config-xo-lass": "2", + "eslint-plugin-compat": "4.0.2", + "eslint-plugin-node": "^11.1.0", + "express": "^4.18.3", + "express-session": "^1.17.3", + "fixpack": "^4.0.0", + "get-port": "4.2.0", + "husky": "^9.1.7", + "lint-staged": "^15.5.2", + "marked": "^4.2.12", + "mocha": "^6.2.3", + "multer": "1.4.5-lts.1", + "nyc": "^15.1.0", + "remark-cli": "^11.0.0", + "remark-preset-github": "4.0.4", + "rimraf": "3", + "should": "^13.2.3", + "should-http": "^0.1.1", + "tinyify": "3.0.0", + "xo": "^0.53.1", + "zuul": "^3.12.0" + }, + "engines": { + "node": ">=14.18.0" + }, + "files": [ + "dist/*.js", + "lib/**/*.js" + ], + "homepage": "https://github.com/ladjs/superagent", + "jsdelivr": "dist/superagent.min.js", + "keywords": [ + "agent", + "ajax", + "ajax", + "api", + "async", + "await", + "axios", + "cancel", + "client", + "frisbee", + "got", + "http", + "http", + "https", + "ky", + "promise", + "promise", + "promises", + "request", + "request", + "requests", + "response", + "rest", + "retry", + "super", + "superagent", + "timeout", + "transform", + "xhr", + "xmlhttprequest" + ], + "license": "MIT", + "main": "lib/node/index.js", + "repository": { + "type": "git", + "url": "git://github.com/ladjs/superagent.git" + }, + "scripts": { + "browserify": "browserify src/node/index.js -o dist/superagent.js -s superagent -g [ babelify --configFile ./.dist.babelrc ]", + "build": "npm run build:clean && npm run build:lib && npm run build:dist", + "build:clean": "rimraf lib dist", + "build:dist": "npm run browserify && npm run minify", + "build:lib": "babel --config-file ./.lib.babelrc src --out-dir lib", + "build:test": "babel --config-file ./.test.babelrc test --out-dir lib/node/test", + "coverage": "nyc report --reporter=text-lcov > coverage.lcov", + "lint": "eslint -c .eslintrc src test && remark . -qfo && eslint -c .lib.eslintrc lib/**/*.js && eslint -c .dist.eslintrc dist/**/*.js", + "minify": "cross-env NODE_ENV=production browserify src/node/index.js -o dist/superagent.min.js -s superagent -g [ babelify --configFile ./.dist.babelrc ] -p tinyify", + "nyc": "cross-env NODE_ENV=test nyc ava", + "test": "npm run build && npm run lint && make test", + "test-http2": "npm run build && npm run lint && make test-node-http2", + "prepare": "husky" + }, + "unpkg": "dist/superagent.min.js" +} diff --git a/node_modules/supertest/LICENSE b/node_modules/supertest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..020b1fac6cf419811a3590a693f0a983c5f2890c --- /dev/null +++ b/node_modules/supertest/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk and other +contributors. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supertest/README.md b/node_modules/supertest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..73e175f2b378097f027e2e75f7ac124b39598825 --- /dev/null +++ b/node_modules/supertest/README.md @@ -0,0 +1,471 @@ +# [supertest](https://forwardemail.github.io/superagent/) + +[![build status](https://github.com/forwardemail/supertest/actions/workflows/ci.yml/badge.svg)](https://github.com/forwardemail/supertest/actions/workflows/ci.yml) +[![code coverage](https://img.shields.io/codecov/c/github/ladjs/supertest.svg)](https://codecov.io/gh/ladjs/supertest) +[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) +[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier) +[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org) +[![license](https://img.shields.io/github/license/ladjs/supertest.svg)](LICENSE) + +> HTTP assertions made easy via [superagent](http://github.com/ladjs/superagent). Maintained for [Forward Email](https://github.com/forwardemail) and [Lad](https://github.com/ladjs). + +## About + +The motivation with this module is to provide a high-level abstraction for testing +HTTP, while still allowing you to drop down to the [lower-level API](https://forwardemail.github.io/superagent/) provided by superagent. + +## Getting Started + +Install supertest as an npm module and save it to your package.json file as a development dependency: + +```bash +npm install supertest --save-dev +``` + + Once installed it can now be referenced by simply calling ```require('supertest');``` + +## Example + +You may pass an `http.Server`, or a `Function` to `request()` - if the server is not +already listening for connections then it is bound to an ephemeral port for you so +there is no need to keep track of ports. + +supertest works with any test framework, here is an example without using any +test framework at all: + +```js +const request = require('supertest'); +const express = require('express'); + +const app = express(); + +app.get('/user', function(req, res) { + res.status(200).json({ name: 'john' }); +}); + +request(app) + .get('/user') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + .end(function(err, res) { + if (err) throw err; + }); +``` + +To enable http2 protocol, simply append an options to `request` or `request.agent`: + +```js +const request = require('supertest'); +const express = require('express'); + +const app = express(); + +app.get('/user', function(req, res) { + res.status(200).json({ name: 'john' }); +}); + +request(app, { http2: true }) + .get('/user') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + .end(function(err, res) { + if (err) throw err; + }); + +request.agent(app, { http2: true }) + .get('/user') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + .end(function(err, res) { + if (err) throw err; + }); +``` + +Here's an example with mocha, note how you can pass `done` straight to any of the `.expect()` calls: + +```js +describe('GET /user', function() { + it('responds with json', function(done) { + request(app) + .get('/user') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200, done); + }); +}); +``` + +You can use `auth` method to pass HTTP username and password in the same way as in the [superagent](https://forwardemail.github.io/superagent/#authentication): + +```js +describe('GET /user', function() { + it('responds with json', function(done) { + request(app) + .get('/user') + .auth('username', 'password') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200, done); + }); +}); +``` + +One thing to note with the above statement is that superagent now sends any HTTP +error (anything other than a 2XX response code) to the callback as the first argument if +you do not add a status code expect (i.e. `.expect(302)`). + +If you are using the `.end()` method `.expect()` assertions that fail will +not throw - they will return the assertion as an error to the `.end()` callback. In +order to fail the test case, you will need to rethrow or pass `err` to `done()`, as follows: + +```js +describe('POST /users', function() { + it('responds with json', function(done) { + request(app) + .post('/users') + .send({name: 'john'}) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .end(function(err, res) { + if (err) return done(err); + return done(); + }); + }); +}); +``` + +You can also use promises: + +```js +describe('GET /users', function() { + it('responds with json', function() { + return request(app) + .get('/users') + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(200) + .then(response => { + expect(response.body.email).toEqual('foo@bar.com'); + }) + }); +}); +``` + +Or async/await syntax: + +```js +describe('GET /users', function() { + it('responds with json', async function() { + const response = await request(app) + .get('/users') + .set('Accept', 'application/json') + expect(response.headers["content-type"]).toMatch(/json/); + expect(response.status).toEqual(200); + expect(response.body.email).toEqual('foo@bar.com'); + }); +}); +``` + +Expectations are run in the order of definition. This characteristic can be used +to modify the response body or headers before executing an assertion. + +```js +describe('POST /user', function() { + it('user.name should be an case-insensitive match for "john"', function(done) { + request(app) + .post('/user') + .send('name=john') // x-www-form-urlencoded upload + .set('Accept', 'application/json') + .expect(function(res) { + res.body.id = 'some fixed id'; + res.body.name = res.body.name.toLowerCase(); + }) + .expect(200, { + id: 'some fixed id', + name: 'john' + }, done); + }); +}); +``` + +Anything you can do with superagent, you can do with supertest - for example multipart file uploads! + +```js +request(app) + .post('/') + .field('name', 'my awesome avatar') + .field('complex_object', '{"attribute": "value"}', {contentType: 'application/json'}) + .attach('avatar', 'test/fixtures/avatar.jpg') + ... +``` + +Passing the app or url each time is not necessary, if you're testing +the same host you may simply re-assign the request variable with the +initialization app or url, a new `Test` is created per `request.VERB()` call. + +```js +request = request('http://localhost:5555'); + +request.get('/').expect(200, function(err){ + console.log(err); +}); + +request.get('/').expect('heya', function(err){ + console.log(err); +}); +``` + +Here's an example with mocha that shows how to persist a request and its cookies: + +```js +const request = require('supertest'); +const should = require('should'); +const express = require('express'); +const cookieParser = require('cookie-parser'); + +describe('request.agent(app)', function() { + const app = express(); + app.use(cookieParser()); + + app.get('/', function(req, res) { + res.cookie('cookie', 'hey'); + res.send(); + }); + + app.get('/return', function(req, res) { + if (req.cookies.cookie) res.send(req.cookies.cookie); + else res.send(':(') + }); + + const agent = request.agent(app); + + it('should save cookies', function(done) { + agent + .get('/') + .expect('set-cookie', 'cookie=hey; Path=/', done); + }); + + it('should send cookies', function(done) { + agent + .get('/return') + .expect('hey', done); + }); +}); +``` + +There is another example that is introduced by the file [agency.js](https://github.com/ladjs/superagent/blob/master/test/node/agency.js) + +Here is an example where 2 cookies are set on the request. + +```js +agent(app) + .get('/api/content') + .set('Cookie', ['nameOne=valueOne;nameTwo=valueTwo']) + .send() + .expect(200) + .end((err, res) => { + if (err) { + return done(err); + } + expect(res.text).to.be.equal('hey'); + return done(); + }); +``` + +## API + +You may use any [superagent](http://github.com/ladjs/superagent) methods, +including `.write()`, `.pipe()` etc and perform assertions in the `.end()` callback +for lower-level needs. + +### .expect(status[, fn]) + +Assert response `status` code. + +### .expect(status, body[, fn]) + +Assert response `status` code and `body`. + +### .expect(body[, fn]) + +Assert response `body` text with a string, regular expression, or +parsed body object. + +### .expect(field, value[, fn]) + +Assert header `field` `value` with a string or regular expression. + +### .expect(function(res) {}) + +Pass a custom assertion function. It'll be given the response object to check. If the check fails, throw an error. + +```js +request(app) + .get('/') + .expect(hasPreviousAndNextKeys) + .end(done); + +function hasPreviousAndNextKeys(res) { + if (!('next' in res.body)) throw new Error("missing next key"); + if (!('prev' in res.body)) throw new Error("missing prev key"); +} +``` + +### .end(fn) + +Perform the request and invoke `fn(err, res)`. + +## Cookies + +Here is an example of using the `set` and `not` cookie assertions: + +```js +// setup super-test +const request = require('supertest'); +const express = require('express'); +const cookies = request.cookies; + +// setup express test service +const app = express(); + +app.get('/users', function(req, res) { + res.cookie('alpha', 'one', { domain: 'domain.com', path: '/', httpOnly: true }); + res.send(200, { name: 'tobi' }); +}); + +// test request to service +request(app) + .get('/users') + .expect('Content-Type', /json/) + .expect('Content-Length', '15') + .expect(200) + // assert 'alpha' cookie is set with domain, path, and httpOnly options + .expect(cookies.set({ name: 'alpha', options: ['domain', 'path', 'httponly'] })) + // assert 'bravo' cookie is NOT set + .expect(cookies.not('set', { name: 'bravo' })) + .end(function(err, res) { + if (err) { + throw err; + } + }); +``` + +It is also possible to chain assertions: + +```js +cookies.set({/* ... */}).not('set', {/* ... */}) +``` + +### Cookie assertions + +Functions and methods are chainable. + +#### cookies([secret], [asserts]) + +Get assertion function for [super-test](https://github.com/visionmedia/supertest) `.expect()` method. + +*Arguments* + +- `secret` - String or array of strings. Cookie signature secrets. +- `asserts(req, res)` - Function or array of functions. Failed custom assertions should throw. + +#### .set(expects, [assert]) + +Assert that cookie and options are set. + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `options` - *Optional* array of options. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .reset(expects, [assert]) + +Assert that cookie is set and was already set (in request headers). + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .new(expects, [assert]) + +Assert that cookie is set and was NOT already set (NOT in request headers). + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .renew(expects, [assert]) + +Assert that cookie is set with a strictly greater `expires` or `max-age` than the given value. + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `options` - Object of options. `use one of two options below` + - `options`.`expires` - String UTC expiration for original cookie (in request headers). + - `options`.`max-age` - Integer ttl in seconds for original cookie (in request headers). +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .contain(expects, [assert]) + +Assert that cookie is set with value and contains options. + +Requires `cookies(secret)` initialization if cookie is signed. + +*Arguments* + +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `value` - *Optional* string unsigned value of cookie. + - `options` - *Optional* object of options. + - `options`.`domain` - *Optional* string domain. + - `options`.`path` - *Optional* string path. + - `options`.`expires` - *Optional* string UTC expiration. + - `options`.`max-age` - *Optional* integer ttl, in seconds. + - `options`.`secure` - *Optional* boolean secure flag. + - `options`.`httponly` - *Optional* boolean httpOnly flag. +- `assert` - *Optional* boolean "assert true" modifier. Default: `true`. + +#### .not(method, expects) + +Call any cookies assertion method with "assert true" modifier set to `false`. + +Syntactic sugar. + +*Arguments* + +- `method` - String method name. Arguments of method name apply in `expects`. +- `expects` - Object or array of objects. + - `name` - String name of cookie. + - `value` - *Optional* string unsigned value of cookie. + - `options` - *Optional* object of options. + +## Notes + +Inspired by [api-easy](https://github.com/flatiron/api-easy) minus vows coupling. + +## License + +MIT + +[coverage-badge]: https://img.shields.io/codecov/c/github/ladjs/supertest.svg +[coverage]: https://codecov.io/gh/ladjs/supertest +[travis-badge]: https://travis-ci.org/ladjs/supertest.svg?branch=master +[travis]: https://travis-ci.org/ladjs/supertest +[dependencies-badge]: https://david-dm.org/ladjs/supertest/status.svg +[dependencies]: https://david-dm.org/ladjs/supertest +[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square +[prs]: http://makeapullrequest.com +[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square +[license]: https://github.com/ladjs/supertest/blob/master/LICENSE diff --git a/node_modules/supertest/index.js b/node_modules/supertest/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7575a39d5b50a1f6975bb0db2a1bd803d143ddfd --- /dev/null +++ b/node_modules/supertest/index.js @@ -0,0 +1,67 @@ +'use strict'; + +/** + * Module dependencies. + */ +const methods = require('methods'); +let http2; +try { + http2 = require('http2'); // eslint-disable-line global-require +} catch (_) { + // eslint-disable-line no-empty +} +const Test = require('./lib/test.js'); +const agent = require('./lib/agent.js'); +const cookies = require('./lib/cookies'); + +/** + * Test against the given `app`, + * returning a new `Test`. + * + * @param {Function|Server|String} app + * @return {Test} + * @api public + */ +module.exports = function(app, options = {}) { + const obj = {}; + + if (typeof app === 'function') { + if (options.http2) { + if (!http2) { + throw new Error( + 'supertest: this version of Node.js does not support http2' + ); + } + } + } + + methods.forEach(function(method) { + obj[method] = function(url) { + var test = new Test(app, method, url, options.http2); + if (options.http2) { + test.http2(); + } + return test; + }; + }); + + // Support previous use of del + obj.del = obj.delete; + + return obj; +}; + +/** + * Expose `Test` + */ +module.exports.Test = Test; + +/** + * Expose the agent function + */ +module.exports.agent = agent; + +/** + * Expose cookie assertions + */ +module.exports.cookies = cookies; diff --git a/node_modules/supertest/lib/agent.js b/node_modules/supertest/lib/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..eee7159d3c5e313b93634dd9246b3ae75e530f93 --- /dev/null +++ b/node_modules/supertest/lib/agent.js @@ -0,0 +1,100 @@ +'use strict'; + +/** + * Module dependencies. + */ + +const { agent: Agent } = require('superagent'); +const methods = require('methods'); +const http = require('http'); +let http2; +try { + http2 = require('http2'); // eslint-disable-line global-require +} catch (_) { + // eslint-disable-line no-empty +} +const Test = require('./test.js'); + +/** + * Initialize a new `TestAgent`. + * + * @param {Function|Server} app + * @param {Object} options + * @api public + */ + +function TestAgent(app, options = {}) { + if (!(this instanceof TestAgent)) return new TestAgent(app, options); + + const agent = new Agent(options); + Object.assign(this, agent); + + this._options = options; + + if (typeof app === 'function') { + if (options.http2) { + if (!http2) { + throw new Error( + 'supertest: this version of Node.js does not support http2' + ); + } + app = http2.createServer(app); // eslint-disable-line no-param-reassign + } else { + app = http.createServer(app); // eslint-disable-line no-param-reassign + } + } + this.app = app; +} + +/** + * Inherits from `Agent.prototype`. + */ + +Object.setPrototypeOf(TestAgent.prototype, Agent.prototype); + +// Preserve the original query method before overriding HTTP methods +const originalQuery = Agent.prototype.query; + +// set a host name +TestAgent.prototype.host = function(host) { + this._host = host; + return this; +}; + +// override HTTP verb methods +methods.forEach(function(method) { + // Skip 'query' method to prevent overwriting superagent's query functionality + if (method === 'query') { + return; + } + + TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars + const req = new Test(this.app, method.toUpperCase(), url); + if (this._options.http2) { + req.http2(); + } + + if (this._host) { + req.set('host', this._host); + } + + req.on('response', this._saveCookies.bind(this)); + req.on('redirect', this._saveCookies.bind(this)); + req.on('redirect', this._attachCookies.bind(this, req)); + this._setDefaults(req); + this._attachCookies(req); + + return req; + }; +}); + +// Restore the original query method +TestAgent.prototype.query = originalQuery; + +TestAgent.prototype.del = TestAgent.prototype.delete; + +/** + * Expose `Agent`. + */ + +module.exports = TestAgent; diff --git a/node_modules/supertest/lib/cookies/assertion.js b/node_modules/supertest/lib/cookies/assertion.js new file mode 100644 index 0000000000000000000000000000000000000000..1d5b890d7268ed2380abcdafcfc357d19195c236 --- /dev/null +++ b/node_modules/supertest/lib/cookies/assertion.js @@ -0,0 +1,497 @@ +/** Copyright 2015 Gregory Langlais. See LICENSE.txt. */ + +'use strict'; + +const signature = require('cookie-signature'); + +/** + * Assert that an object has specific properties (supports array of keys or object) + * + * @param {object} obj + * @param {object|array} props + */ +function assertHasProperties(obj, props) { + if (Array.isArray(props)) { + props.forEach(function (key) { + if (!(key in obj)) { + throw new Error('expected object to have property ' + key); + } + }); + } else { + Object.keys(props).forEach(function (key) { + if (!(key in obj)) { + throw new Error('expected object to have property ' + key); + } + }); + } +} + +/** + * Assert that an object does not have specific properties (supports array of keys or object) + * When checking with empty props, throws if object exists (matches should.js behavior) + * + * @param {object} obj + * @param {object|array} props + */ +function assertNotHasProperties(obj, props) { + if (Array.isArray(props)) { + // When empty array is passed, should.js throws 'false negative fail' if object exists + if (props.length === 0) { + throw new Error('expected object to not have properties (false negative fail)'); + } + props.forEach(function (key) { + if (key in obj) { + throw new Error('expected object to not have property ' + key); + } + }); + } else { + // When empty object is passed, should.js throws 'false negative fail' if object exists + let keys = Object.keys(props); + if (keys.length === 0) { + throw new Error('expected object to not have properties (false negative fail)'); + } + keys.forEach(function (key) { + if (key in obj) { + throw new Error('expected object to not have property ' + key); + } + }); + } +} + +/** + * Assert that two values are equal + * + * @param {*} actual + * @param {*} expected + */ +function assertEqual(actual, expected) { + if (actual !== expected) { + throw new Error( + 'expected ' + JSON.stringify(actual) + ' to equal ' + JSON.stringify(expected) + ); + } +} + +/** + * Assert that two values are not equal + * + * @param {*} actual + * @param {*} expected + */ +function assertNotEqual(actual, expected) { + if (actual === expected) { + throw new Error( + 'expected ' + JSON.stringify(actual) + ' to not equal ' + JSON.stringify(expected) + ); + } +} + +/** + * Build Assertion function + * + * {object|object[]} expects cookies + * {string} expects. and value of cookie + * {object} expects.options + * {string} [expects.options.domain] + * {string} [expects.options.path] + * {string} [expects.options.expires] UTC string using date.toUTCString() + * {number} [expects.options.max-age] + * {boolean} [expects.options.secure] + * {boolean} [expects.options.httponly] + * {string|string[]} [expects.secret] + * + * @param {null|string|string[]} [secret] + * @param {function|function[]} [asserts] + * @returns {Assertion} + */ +module.exports = function (secret, asserts) { + let assertions = []; + + if (typeof secret === 'string') secret = [secret]; // eslint-disable-line no-param-reassign + else if (!Array.isArray(secret)) secret = []; // eslint-disable-line no-param-reassign + + if (Array.isArray(asserts)) assertions = asserts; + else if (typeof asserts === 'function') assertions.push(asserts); + + /** + * Assertion function with static chainable methods + * + * @param {object} res + * @returns {undefined|string} + * @constructor + */ + function Assertion(res) { + if (typeof res !== 'object') throw new Error('res argument must be object'); + + // request and response object initialization + let request = { + headers: res.req.getHeaders(), + cookies: [] + }; + + let response = { + headers: res.headers, + cookies: [] + }; + + // build assertions request object + if (request.headers.cookie) { + const cookies = String(request.headers.cookie); + cookies.split(/; */).forEach(function (cookie) { + request.cookies.push(Assertion.parse(cookie)); + }); + } + + // build assertions response object + if ( + Array.isArray(response.headers['set-cookie']) + && response.headers['set-cookie'].length > 0 + ) { + response.headers['set-cookie'].forEach(function (val) { + response.cookies.push(Assertion.parse(val)); + }); + } + + // run assertions + let result; + assertions.every(function (assertion) { + result = assertion(request, response); + return (typeof (result) !== 'string'); + }); + + return result; + } + + /** + * Find cookie in stack/array + * + * @param {string} name + * @param {array} stack + * @returns {object|undefined} cookie + */ + Assertion.find = function (name, stack) { + let cookie; + + stack.every(function (val) { + if (name !== val.name) return true; + cookie = val; + return false; + }); + + return cookie; + }; + + /** + * Parse cookie string + * + * @param {string} str + * @param {object} [options] + * @param {function} [options.decode] uri + * @param {undefined|boolean} [options.request] headers + * @returns {object} + */ + Assertion.parse = function (str, options) { + if (typeof str !== 'string') throw new TypeError('argument str must be a string'); + + if (typeof options !== 'object') options = {}; // eslint-disable-line no-param-reassign + + let decode = options.decode || decodeURIComponent; + + let parts = str.split(/; */); + + let cookie = {}; + + parts.forEach(function (part, i) { + if (i === 1) cookie.options = {}; + + let equalsIndex = part.indexOf('='); + + // things that don't look like key=value get true flag + if (equalsIndex < 0) { + cookie.options[part.trim().toLowerCase()] = true; + return; + } + + const key = part.substr(0, equalsIndex).trim().toLowerCase(); + // only assign once + if (typeof cookie[key] !== 'undefined') return; + + equalsIndex += 1; + let val = part.substr(equalsIndex, part.length).trim(); + // quoted values + if (val[0] === '"') val = val.slice(1, -1); + + let value; + try { + value = decode(val); + } catch (e) { + value = val; + } + + if (i > 0) { + cookie.options[key] = value; + return; + } + + cookie.name = key; + cookie.value = decode(val); + }); + + if (typeof cookie.options === 'undefined') cookie.options = {}; + + return cookie; + }; + + /** + * Iterate expects + * + * @param {object|object[]} expects + * @param {boolean|function} hasValues + * @param {function} [cb] + */ + Assertion.expects = function (expects, hasValues, cb) { + if (!Array.isArray(expects) && typeof expects === 'object') expects = [expects]; // eslint-disable-line no-param-reassign + + let resolvedCb; + let resolvedHasValues; + if (typeof cb === 'undefined' && typeof hasValues === 'function') { + resolvedCb = hasValues; + resolvedHasValues = false; + } else { + resolvedCb = cb; + resolvedHasValues = hasValues; + } + + expects.forEach(function (expect) { + let options = expect.options; + if (typeof options !== 'object' && !Array.isArray(options)) { + options = (resolvedHasValues) ? {} : []; + } + + resolvedCb(Object.assign({}, expect, { options })); + }); + }; + + /** + * Assert cookies and options are set + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.set = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + assertions.push(function (req, res) { + // get expectation cookie + const cookie = Assertion.find(expect.name, res.cookies); + + if (assert && !cookie) throw new Error('expected: ' + expect.name + ' cookie to be set'); + + if (assert) assertHasProperties(cookie.options, expect.options); + else if (cookie) assertNotHasProperties(cookie.options, expect.options); + }); + }); + + return Assertion; + }; + + /** + * Assert cookies has been reset + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.reset = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + assertions.push(function (req, res) { + // get sent cookie + const cookieReq = Assertion.find(expect.name, req.cookies); + // get expectation cookie + const cookieRes = Assertion.find(expect.name, res.cookies); + + if (assert && (!cookieReq || !cookieRes)) { + throw new Error('expected: ' + expect.name + ' cookie to be set'); + } else if (!assert && cookieReq && cookieRes) { + throw new Error('expected: ' + expect.name + ' cookie to be set'); + } + }); + }); + + return Assertion; + }; + + /** + * Assert cookies is set and new + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.new = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + assertions.push(function (req, res) { + // get sent cookie + const cookieReq = Assertion.find(expect.name, req.cookies); + // get expectation cookie + const cookieRes = Assertion.find(expect.name, res.cookies); + + if (assert) { + if (!cookieRes) throw new Error('expected: ' + expect.name + ' cookie to be set'); + if (cookieReq && cookieRes) { + throw new Error('expected: ' + expect.name + ' cookie to NOT already be set'); + } + } else if (!cookieReq || !cookieRes) { + throw new Error('expected: ' + expect.name + ' cookie to be set'); + } + }); + }); + + return Assertion; + }; + + /** + * Assert cookies expires or max-age has increased + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.renew = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, true, function (expect) { + const expectExpires = new Date(expect.options.expires); + const expectMaxAge = parseFloat(expect.options['max-age']); + + let baseMessage = 'expected: ' + expect.name; + if (!expectExpires.getTime() && !expectMaxAge) { + throw new Error(baseMessage + ' expects to have expires or max-age option'); + } + + assertions.push(function (req, res) { + // get sent cookie + const cookieReq = Assertion.find(expect.name, req.cookies); + // get expectation cookie + const cookieRes = Assertion.find(expect.name, res.cookies); + + const cookieMaxAge = (expectMaxAge && cookieRes) + ? parseFloat(cookieRes.options['max-age']) + : undefined; + const cookieExpires = (expectExpires.getTime() && cookieRes) + ? new Date(cookieRes.options.expires) + : undefined; + + if (assert) { + if (!cookieReq || !cookieRes) { + throw new Error(baseMessage + ' cookie to be set'); + } + if (expectMaxAge && (!cookieMaxAge || cookieMaxAge <= expectMaxAge)) { + throw new Error(baseMessage + ' cookie max-age to be greater than existing value'); + } + + if ( + expectExpires.getTime() + && (!cookieExpires.getTime() || cookieExpires <= expectExpires) + ) { + throw new Error(baseMessage + ' cookie expires to be greater than existing value'); + } + } else if (cookieRes) { + if (expectMaxAge && cookieMaxAge > expectMaxAge) { + throw new Error( + baseMessage + ' cookie max-age to be less than or equal to existing value' + ); + } + + if (expectExpires.getTime() && cookieExpires > expectExpires) { + throw new Error( + baseMessage + ' cookie expires to be less than or equal to existing value' + ); + } + } + }); + }); + + return Assertion; + }; + + /** + * Assert cookies contains values + * + * @param {object|object[]} expects cookies + * @param {undefined|boolean} [assert] + * @returns {function} Assertion + */ + Assertion.contain = function (expects, assert) { + if (typeof assert === 'undefined') assert = true; // eslint-disable-line no-param-reassign + + Assertion.expects(expects, function (expect) { + const keys = Object.keys(expect.options); + + assertions.push(function (req, res) { + // get expectation cookie + const cookie = Assertion.find(expect.name, res.cookies); + + if (!cookie) throw new Error('expected: ' + expect.name + ' cookie to be set'); + + // check cookie values are equal + if ('value' in expect) { + try { + if (assert) assertEqual(cookie.value, expect.value); + else assertNotEqual(cookie.value, expect.value); + } catch (e) { + if (secret.length) { + let value; + secret.every(function (sec) { + value = signature.unsign(cookie.value.slice(2), sec); + return !(value && value === expect.value); + }); + + if (assert && !value) { + throw new Error('expected: ' + expect.name + ' value to equal ' + expect.value); + } else if (!assert && value) { + throw new Error('expected: ' + expect.name + ' value to NOT equal ' + expect.value); + } + } else throw e; + } + } + + keys.forEach(function (key) { + const expected = ( + key === 'max-age' + ? expect.options[key].toString() + : expect.options[key] + ); + if (assert) assertEqual(cookie.options[key], expected); + else assertNotEqual(cookie.options[key], expected); + }); + }); + }); + + return Assertion; + }; + + /** + * Assert NOT modifier + * + * @param {function} method + * @param {...*} + */ + Assertion.not = function (method) { + let args = []; + + for (let i = 1; i < arguments.length; i += 1) args.push(arguments[i]); + + args.push(false); + + return Assertion[method].apply(Assertion, args); + }; + + return Assertion; +}; diff --git a/node_modules/supertest/lib/cookies/index.js b/node_modules/supertest/lib/cookies/index.js new file mode 100644 index 0000000000000000000000000000000000000000..889dee0e371297eaba3bfb4ec1290b48f30c23e4 --- /dev/null +++ b/node_modules/supertest/lib/cookies/index.js @@ -0,0 +1,32 @@ +/** Copyright 2015 Gregory Langlais. See LICENSE.txt. */ + +'use strict'; + +const Assertion = require('./assertion'); + +/** + * Construct cookies assertion (function) + * + * @param {null|string|string[]} [secret] + * @param {function(req, res)[]} [asserts] ran within returned assertion function + * @returns {function} assertion + * @constructor + */ +function ExpectCookies(secret, asserts) { + return Assertion(secret, asserts); +} + +// build ExpectCookies proxy methods +const assertion = Assertion(); +const methods = Object.getOwnPropertyNames(assertion); + +methods.forEach(function(method) { + if (typeof assertion[method] === 'function' && typeof Function[method] === 'undefined') { + ExpectCookies[method] = function() { + const newAssertion = Assertion(); + return newAssertion[method].apply(newAssertion, arguments); + }; + } +}); + +module.exports = ExpectCookies; diff --git a/node_modules/supertest/lib/test.js b/node_modules/supertest/lib/test.js new file mode 100644 index 0000000000000000000000000000000000000000..f83008811ab1aee6242d60b8b6fcc09b93e8396c --- /dev/null +++ b/node_modules/supertest/lib/test.js @@ -0,0 +1,403 @@ +'use strict'; + +/** + * Module dependencies. + */ + +const { inspect } = require('util'); +const http = require('http'); +const { STATUS_CODES } = require('http'); +const { Server } = require('tls'); +const { deepStrictEqual } = require('assert'); +const { Request } = require('superagent'); +let http2; +try { + http2 = require('http2'); // eslint-disable-line global-require +} catch (_) { + // eslint-disable-line no-empty +} + +/** @typedef {import('superagent').Response} Response */ + +class Test extends Request { + /** + * Initialize a new `Test` with the given `app`, + * request `method` and `path`. + * + * @param {Server} app + * @param {String} method + * @param {String} path + * @api public + */ + constructor (app, method, path, optHttp2) { + super(method.toUpperCase(), path); + + if (typeof app === 'function') { + if (optHttp2) { + app = http2.createServer(app); // eslint-disable-line no-param-reassign + } else { + app = http.createServer(app); // eslint-disable-line no-param-reassign + } + } + + this.redirects(0); + this.buffer(); + this.app = app; + this._asserts = []; + this.url = typeof app === 'string' + ? app + path + : this.serverAddress(app, path); + } + + /** + * Returns a URL, extracted from a server. + * + * @param {Server} app + * @param {String} path + * @returns {String} URL address + * @api private + */ + serverAddress(app, path) { + const addr = app.address(); + + if (!addr) this._server = app.listen(0); + // } else { + // this._server = app; + // } + const port = app.address().port; + const protocol = app instanceof Server ? 'https' : 'http'; + return protocol + '://127.0.0.1:' + port + path; + } + + /** + * Expectations: + * + * .expect(200) + * .expect(200, fn) + * .expect(200, body) + * .expect('Some body') + * .expect('Some body', fn) + * .expect(['json array body', { key: 'val' }]) + * .expect('Content-Type', 'application/json') + * .expect('Content-Type', 'application/json', fn) + * .expect(fn) + * .expect([200, 404]) + * + * @return {Test} + * @api public + */ + expect(a, b, c) { + // callback + if (typeof a === 'function') { + this._asserts.push(wrapAssertFn(a)); + return this; + } + if (typeof b === 'function') this.end(b); + if (typeof c === 'function') this.end(c); + + // status + if (typeof a === 'number') { + this._asserts.push(wrapAssertFn(this._assertStatus.bind(this, a))); + // body + if (typeof b !== 'function' && arguments.length > 1) { + this._asserts.push(wrapAssertFn(this._assertBody.bind(this, b))); + } + return this; + } + + // multiple statuses + if (Array.isArray(a) && a.length > 0 && a.every(val => typeof val === 'number')) { + this._asserts.push(wrapAssertFn(this._assertStatusArray.bind(this, a))); + return this; + } + + // header field + if (typeof b === 'string' || typeof b === 'number' || b instanceof RegExp) { + this._asserts.push(wrapAssertFn(this._assertHeader.bind(this, { name: '' + a, value: b }))); + return this; + } + + // body + this._asserts.push(wrapAssertFn(this._assertBody.bind(this, a))); + + return this; + } + + /** + * Defer invoking superagent's `.end()` until + * the server is listening. + * + * @param {?Function} fn + * @api public + */ + end(fn) { + const server = this._server; + + super.end((err, res) => { + const localAssert = () => { + this.assert(err, res, fn); + }; + + if (server && server._handle) { + // Handle server closing with error handling for already closed servers + return server.close((closeError) => { + // Ignore ERR_SERVER_NOT_RUNNING errors as the server is already closed + if (closeError && closeError.code === 'ERR_SERVER_NOT_RUNNING') { + return localAssert(); + } + // For other errors, pass them through + if (closeError) { + return localAssert(); + } + localAssert(); + }); + } + + localAssert(); + }); + + return this; + } + + /** + * Perform assertions and invoke `fn(err, res)`. + * + * @param {?Error} resError + * @param {Response} res + * @param {Function} fn + * @api private + */ + assert(resError, res, fn) { + let errorObj; + + // check for unexpected network errors or server not running/reachable errors + // when there is no response and superagent sends back a System Error + // do not check further for other asserts, if any, in such case + // https://nodejs.org/api/errors.html#errors_common_system_errors + const sysErrors = { + ECONNREFUSED: 'Connection refused', + ECONNRESET: 'Connection reset by peer', + EPIPE: 'Broken pipe', + ETIMEDOUT: 'Operation timed out' + }; + + if (!res && resError) { + if (resError instanceof Error && resError.syscall === 'connect' + && Object.getOwnPropertyNames(sysErrors).indexOf(resError.code) >= 0) { + errorObj = new Error(resError.code + ': ' + sysErrors[resError.code]); + } else { + errorObj = resError; + } + } + + // asserts + for (let i = 0; i < this._asserts.length && !errorObj; i += 1) { + errorObj = this._assertFunction(this._asserts[i], res); + } + + // set unexpected superagent error if no other error has occurred. + if (!errorObj && resError instanceof Error && (!res || resError.status !== res.status)) { + errorObj = resError; + } + + if (fn) { + fn.call(this, errorObj || null, res); + } + } + + /* + * Adds a set Authorization Bearer + * + * @param {Bearer} Bearer Token + * Shortcut for .set('Authorization', `Bearer ${token}`) + */ + + bearer(token) { + this.set('Authorization', `Bearer ${token}`); + return this; + } + + /* + * Adds a set Authorization Bearer + * + * @param {Bearer} Bearer Token + * Shortcut for .set('Authorization', `Bearer ${token}`) + */ + + bearer(token) { + this.set('Authorization', `Bearer ${token}`); + return this; + } + + /** + * Perform assertions on a response body and return an Error upon failure. + * + * @param {Mixed} body + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertBody(body, res) { + const isRegexp = body instanceof RegExp; + + // parsed + if (typeof body === 'object' && !isRegexp) { + try { + deepStrictEqual(body, res.body); + } catch (err) { + const a = inspect(body); + const b = inspect(res.body); + return error('expected ' + a + ' response body, got ' + b, body, res.body); + } + } else if (body !== res.text) { + // string + const a = inspect(body); + const b = inspect(res.text); + + // regexp + if (isRegexp) { + if (!body.test(res.text)) { + return error('expected body ' + b + ' to match ' + body, body, res.body); + } + } else { + return error('expected ' + a + ' response body, got ' + b, body, res.body); + } + } + } + + /** + * Perform assertions on a response header and return an Error upon failure. + * + * @param {Object} header + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertHeader(header, res) { + const field = header.name; + const actual = res.header[field.toLowerCase()]; + const fieldExpected = header.value; + + if (typeof actual === 'undefined') return new Error('expected "' + field + '" header field'); + // This check handles header values that may be a String or single element Array + if ((Array.isArray(actual) && actual.toString() === fieldExpected) + || fieldExpected === actual) { + return; + } + if (fieldExpected instanceof RegExp) { + if (!fieldExpected.test(actual)) { + return new Error('expected "' + field + '" matching ' + + fieldExpected + ', got "' + actual + '"'); + } + } else { + return new Error('expected "' + field + '" of "' + fieldExpected + '", got "' + actual + '"'); + } + } + + /** + * Perform assertions on the response status and return an Error upon failure. + * + * @param {Number} status + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertStatus(status, res) { + if (res.status !== status) { + const a = STATUS_CODES[status]; + const b = STATUS_CODES[res.status]; + return new Error('expected ' + status + ' "' + a + '", got ' + res.status + ' "' + b + '"'); + } + } + + /** + * Perform assertions on the response status and return an Error upon failure. + * + * @param {Array} statusArray + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertStatusArray(statusArray, res) { + if (!statusArray.includes(res.status)) { + const b = STATUS_CODES[res.status]; + const expectedList = statusArray.join(', '); + return new Error( + 'expected one of "' + expectedList + '", got ' + res.status + ' "' + b + '"' + ); + } + } + + /** + * Performs an assertion by calling a function and return an Error upon failure. + * + * @param {Function} fn + * @param {Response} res + * @return {?Error} + * @api private + */// eslint-disable-next-line class-methods-use-this + _assertFunction(fn, res) { + let err; + try { + err = fn(res); + } catch (e) { + err = e; + } + if (err instanceof Error) return err; + } +} + +/** + * Wraps an assert function into another. + * The wrapper function edit the stack trace of any assertion error, prepending a more useful stack to it. + * + * @param {Function} assertFn + * @returns {Function} wrapped assert function + */ + +function wrapAssertFn(assertFn) { + const savedStack = new Error().stack.split('\n').slice(3); + + return function(res) { + let badStack; + let err; + try { + err = assertFn(res); + } catch (e) { + err = e; + } + if (err instanceof Error && err.stack) { + badStack = err.stack.replace(err.message, '').split('\n').slice(1); + err.stack = [err.toString()] + .concat(savedStack) + .concat('----') + .concat(badStack) + .join('\n'); + } + return err; + }; +} + +/** + * Return an `Error` with `msg` and results properties. + * + * @param {String} msg + * @param {Mixed} expected + * @param {Mixed} actual + * @return {Error} + * @api private + */ + +function error(msg, expected, actual) { + const err = new Error(msg); + err.expected = expected; + err.actual = actual; + err.showDiff = true; + return err; +} + +/** + * Expose `Test`. + */ + +module.exports = Test; diff --git a/node_modules/supertest/package.json b/node_modules/supertest/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ec8f250facf40c3658e7b05f4490dfbc31aed1ad --- /dev/null +++ b/node_modules/supertest/package.json @@ -0,0 +1,57 @@ +{ + "name": "supertest", + "description": "SuperAgent driven library for testing HTTP servers", + "version": "7.2.2", + "author": "TJ Holowaychuk", + "contributors": [], + "dependencies": { + "methods": "^1.1.2", + "superagent": "^10.3.0", + "cookie-signature": "^1.2.2" + }, + "devDependencies": { + "@commitlint/cli": "17", + "@commitlint/config-conventional": "17", + "body-parser": "^1.20.3", + "cookie-parser": "^1.4.7", + "eslint": "^8.32.0", + "eslint-config-airbnb-base": "^15.0.0", + "eslint-plugin-import": "^2.27.5", + "express": "^4.18.3", + "mocha": "^10.2.0", + "nock": "^13.3.8", + "nyc": "^15.1.0", + "proxyquire": "^2.1.3", + "should": "^13.2.3", + "sinon": "20.0.0" + }, + "engines": { + "node": ">=14.18.0" + }, + "files": [ + "index.js", + "lib" + ], + "keywords": [ + "bdd", + "http", + "request", + "superagent", + "tdd", + "test", + "testing" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/ladjs/supertest.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov > coverage.lcov", + "lint": "eslint lib/**/*.js test/**/*.js index.js", + "lint:fix": "eslint --fix lib/**/*.js test/**/*.js index.js", + "pretest": "npm run lint --if-present", + "test": "nyc --reporter=html --reporter=text mocha --exit --require should --reporter spec --check-leaks" + } +} diff --git a/node_modules/swagger-ui-dist/LICENSE b/node_modules/swagger-ui-dist/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/node_modules/swagger-ui-dist/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/swagger-ui-dist/NOTICE b/node_modules/swagger-ui-dist/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..ab788a27d5bf625faf500f547bd249c6d1873780 --- /dev/null +++ b/node_modules/swagger-ui-dist/NOTICE @@ -0,0 +1,2 @@ +swagger-ui +Copyright 2020-2021 SmartBear Software Inc. diff --git a/node_modules/swagger-ui-dist/README.md b/node_modules/swagger-ui-dist/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6d198eb45428f804fcf0215def2184af743a1940 --- /dev/null +++ b/node_modules/swagger-ui-dist/README.md @@ -0,0 +1,40 @@ +# Swagger UI Dist +[![NPM version](https://badge.fury.io/js/swagger-ui-dist.svg)](http://badge.fury.io/js/swagger-ui-dist) + +## Anonymized analytics + +SwaggerUI Dist uses [Scarf](https://scarf.sh/) to collect [anonymized installation analytics](https://github.com/scarf-sh/scarf-js?tab=readme-ov-file#as-a-user-of-a-package-using-scarf-js-what-information-does-scarf-js-send-about-me). These analytics help support the maintainers of this library and ONLY run during installation. To [opt out](https://github.com/scarf-sh/scarf-js?tab=readme-ov-file#as-a-user-of-a-package-using-scarf-js-how-can-i-opt-out-of-analytics), you can set the `scarfSettings.enabled` field to `false` in your project's `package.json`: + +``` +// package.json +{ + // ... + "scarfSettings": { + "enabled": false + } + // ... +} +``` + +Alternatively, you can set the environment variable `SCARF_ANALYTICS` to `false` as part of the environment that installs your npm packages, e.g., `SCARF_ANALYTICS=false npm install`. + + +# API + +This module, `swagger-ui-dist`, exposes Swagger-UI's entire dist folder as a dependency-free npm module. +Use `swagger-ui` instead, if you'd like to have npm install dependencies for you. + +`SwaggerUIBundle` and `SwaggerUIStandalonePreset` can be imported: +```javascript + import { SwaggerUIBundle, SwaggerUIStandalonePreset } from "swagger-ui-dist" +``` + +To get an absolute path to this directory for static file serving, use the exported `getAbsoluteFSPath` method: + +```javascript +const swaggerUiAssetPath = require("swagger-ui-dist").getAbsoluteFSPath() + +// then instantiate server that serves files from the swaggerUiAssetPath +``` + +For anything else, check the [Swagger-UI](https://github.com/swagger-api/swagger-ui) repository. diff --git a/node_modules/swagger-ui-dist/absolute-path.js b/node_modules/swagger-ui-dist/absolute-path.js new file mode 100644 index 0000000000000000000000000000000000000000..af42bc8f1c5e65db8991187653c4ad40fa5fddb9 --- /dev/null +++ b/node_modules/swagger-ui-dist/absolute-path.js @@ -0,0 +1,14 @@ +/* + * getAbsoluteFSPath + * @return {string} When run in NodeJS env, returns the absolute path to the current directory + * When run outside of NodeJS, will return an error message + */ +const getAbsoluteFSPath = function () { + // detect whether we are running in a browser or nodejs + if (typeof module !== "undefined" && module.exports) { + return require("path").resolve(__dirname) + } + throw new Error('getAbsoluteFSPath can only be called within a Nodejs environment'); +} + +module.exports = getAbsoluteFSPath diff --git a/node_modules/swagger-ui-dist/favicon-16x16.png b/node_modules/swagger-ui-dist/favicon-16x16.png new file mode 100644 index 0000000000000000000000000000000000000000..8b194e617af1c135e6b37939591d24ac3a5efa18 Binary files /dev/null and b/node_modules/swagger-ui-dist/favicon-16x16.png differ diff --git a/node_modules/swagger-ui-dist/favicon-32x32.png b/node_modules/swagger-ui-dist/favicon-32x32.png new file mode 100644 index 0000000000000000000000000000000000000000..249737fe44558e679f0b67134e274461d988fa98 Binary files /dev/null and b/node_modules/swagger-ui-dist/favicon-32x32.png differ diff --git a/node_modules/swagger-ui-dist/index.css b/node_modules/swagger-ui-dist/index.css new file mode 100644 index 0000000000000000000000000000000000000000..f2376fdaa842b12ecf6a191409ff0b0a03c4b0f8 --- /dev/null +++ b/node_modules/swagger-ui-dist/index.css @@ -0,0 +1,16 @@ +html { + box-sizing: border-box; + overflow: -moz-scrollbars-vertical; + overflow-y: scroll; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} + +body { + margin: 0; + background: #fafafa; +} diff --git a/node_modules/swagger-ui-dist/index.html b/node_modules/swagger-ui-dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..84ae62d3dad6004f2ba250cf69b4148eeb7c253d --- /dev/null +++ b/node_modules/swagger-ui-dist/index.html @@ -0,0 +1,19 @@ + + + + + + Swagger UI + + + + + + + +
+ + + + + diff --git a/node_modules/swagger-ui-dist/index.js b/node_modules/swagger-ui-dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c229ec43e12b73e67be0c4bdda555a8831ad933d --- /dev/null +++ b/node_modules/swagger-ui-dist/index.js @@ -0,0 +1,17 @@ +try { + module.exports.SwaggerUIBundle = require("./swagger-ui-bundle.js") + module.exports.SwaggerUIStandalonePreset = require("./swagger-ui-standalone-preset.js") +} catch(e) { + // swallow the error if there's a problem loading the assets. + // allows this module to support providing the assets for browserish contexts, + // without exploding in a Node context. + // + // see https://github.com/swagger-api/swagger-ui/issues/3291#issuecomment-311195388 + // for more information. +} + +// `absolutePath` and `getAbsoluteFSPath` are both here because at one point, +// we documented having one and actually implemented the other. +// They were both retained so we don't break anyone's code. +module.exports.absolutePath = require("./absolute-path.js") +module.exports.getAbsoluteFSPath = require("./absolute-path.js") diff --git a/node_modules/swagger-ui-dist/log.bundle-sizes.swagger-ui.txt b/node_modules/swagger-ui-dist/log.bundle-sizes.swagger-ui.txt new file mode 100644 index 0000000000000000000000000000000000000000..79c0c1fd81b364ef502dd83c42d8ab0371af0f12 --- /dev/null +++ b/node_modules/swagger-ui-dist/log.bundle-sizes.swagger-ui.txt @@ -0,0 +1,114 @@ +ramda: 367.12 KB (5.33%) +lodash: 256.63 KB (3.73%) +ramda-adjunct: 255.04 KB (3.70%) +autolinker: 203.32 KB (2.95%) +@swagger-api/apidom-ns-openapi-3-0: 192.76 KB (2.80%) +swagger-client: 176.74 KB (2.57%) +@swagger-api/apidom-ns-openapi-3-1: 142.98 KB (2.08%) +immutable: 139.22 KB (2.02%) +react-dom: 129.93 KB (1.89%) +remarkable: 125.56 KB (1.82%) +highlight.js: 111.85 KB (1.62%) +dompurify: 105.71 KB (1.54%) +@swagger-api/apidom-reference: 100.62 KB (1.46%) +readable-stream: 96.66 KB (1.40%) +js-yaml: 90.16 KB (1.31%) +core-js-pure: 87.18 KB (1.27%) +minim: 57.35 KB (0.833%) +buffer: 56.99 KB (0.828%) +@swagger-api/apidom-core: 54.17 KB (0.787%) +@swagger-api/apidom-ast: 53.99 KB (0.784%) +@swagger-api/apidom-ns-json-schema-draft-4: 52.01 KB (0.755%) +react-syntax-highlighter: 40.38 KB (0.586%) +apg-lite: 38.54 KB (0.560%) +short-unique-id: 37.48 KB (0.544%) +react-redux: 36.62 KB (0.532%) +@swaggerexpert/cookie: 35.16 KB (0.511%) +@swagger-api/apidom-ns-json-schema-2019-09: 35.04 KB (0.509%) +fast-json-patch: 31.89 KB (0.463%) +@swaggerexpert/json-pointer: 30.48 KB (0.443%) +@swagger-api/apidom-ns-json-schema-draft-7: 23.62 KB (0.343%) +@swagger-api/apidom-ns-json-schema-2020-12: 22.4 KB (0.325%) +@swagger-api/apidom-ns-json-schema-draft-6: 21.63 KB (0.314%) +reselect: 21.47 KB (0.312%) +openapi-path-templating: 20.81 KB (0.302%) +neotraverse: 20.33 KB (0.295%) +sha.js: 18.92 KB (0.275%) +ts-mixer: 17.56 KB (0.255%) +tslib: 17.23 KB (0.250%) +redux: 16.37 KB (0.238%) +url-parse: 16.23 KB (0.236%) +events: 14.54 KB (0.211%) +openapi-server-url-templating: 14.38 KB (0.209%) +get-intrinsic: 14.02 KB (0.204%) +zenscroll: 12.31 KB (0.179%) +react-debounce-input: 11.95 KB (0.174%) +react-immutable-proptypes: 11.82 KB (0.172%) +ret: 10.82 KB (0.157%) +lodash.debounce: 10.53 KB (0.153%) +unraw: 9.9 KB (0.144%) +string_decoder: 9.24 KB (0.134%) +xml: 7.39 KB (0.107%) +react-copy-to-clipboard: 7.33 KB (0.106%) +react: 6.95 KB (0.101%) +randexp: 6.15 KB (0.0893%) +react-immutable-pure-component: 6.01 KB (0.0872%) +redux-immutable: 5.43 KB (0.0789%) +process: 5.29 KB (0.0768%) +drange: 4.8 KB (0.0698%) +lowlight: 4.42 KB (0.0643%) +scheduler: 4.33 KB (0.0629%) +deep-extend: 4.19 KB (0.0609%) +@babel/runtime: 3.99 KB (0.0580%) +deepmerge: 3.95 KB (0.0574%) +base64-js: 3.84 KB (0.0558%) +stream-browserify: 3.76 KB (0.0546%) +which-typed-array: 3.64 KB (0.0529%) +@swagger-api/apidom-error: 3.45 KB (0.0501%) +copy-to-clipboard: 3.29 KB (0.0477%) +format: 3.26 KB (0.0473%) +is-callable: 3.15 KB (0.0457%) +css.escape: 3.08 KB (0.0447%) +to-buffer: 3.03 KB (0.0440%) +serialize-error: 2.93 KB (0.0425%) +use-sync-external-store: 2.81 KB (0.0409%) +prop-types: 2.6 KB (0.0378%) +querystringify: 2.5 KB (0.0364%) +for-each: 2.32 KB (0.0337%) +has-symbols: 2.31 KB (0.0336%) +define-data-property: 2.28 KB (0.0331%) +xml-but-prettier: 2.17 KB (0.0314%) +function-bind: 2.12 KB (0.0308%) +ieee754: 2.1 KB (0.0306%) +safe-buffer: 1.63 KB (0.0237%) +util-deprecate: 1.58 KB (0.0229%) +randombytes: 1.54 KB (0.0224%) +js-file-download: 1.52 KB (0.0221%) +classnames: 1.49 KB (0.0217%) +call-bind-apply-helpers: 1.35 KB (0.0196%) +set-function-length: 1.24 KB (0.0181%) +repeat-string: 1.18 KB (0.0172%) +get-proto: 1.1 KB (0.0160%) +dunder-proto: 980 B (0.0139%) +@babel/runtime-corejs3: 847 B (0.0120%) +math-intrinsics: 781 B (0.0111%) +toggle-selection: 780 B (0.0111%) +requires-port: 753 B (0.0107%) +inherits: 753 B (0.0107%) +@swagger-api/apidom-json-pointer: 709 B (0.0101%) +fault: 691 B (0.00980%) +call-bound: 667 B (0.00946%) +call-bind: 643 B (0.00912%) +typed-array-buffer: 591 B (0.00838%) +has-property-descriptors: 588 B (0.00834%) +es-errors: 524 B (0.00743%) +available-typed-arrays: 475 B (0.00674%) +gopd: 303 B (0.00430%) +es-define-property: 288 B (0.00409%) +possible-typed-array-names: 264 B (0.00374%) +hasown: 206 B (0.00292%) +has-tostringtag: 189 B (0.00268%) +is-typed-array: 180 B (0.00255%) +isarray: 132 B (0.00187%) +es-object-atoms: 67 B (0.000950%) +: 3.18 MB (47.3%) diff --git a/node_modules/swagger-ui-dist/log.es-bundle-core-sizes.swagger-ui.txt b/node_modules/swagger-ui-dist/log.es-bundle-core-sizes.swagger-ui.txt new file mode 100644 index 0000000000000000000000000000000000000000..11de4f390c6924b75dcf5644ed01184287074a1f --- /dev/null +++ b/node_modules/swagger-ui-dist/log.es-bundle-core-sizes.swagger-ui.txt @@ -0,0 +1,14 @@ +readable-stream: 96.66 KB (5.57%) +buffer: 56.99 KB (3.28%) +sha.js: 18.92 KB (1.09%) +events: 14.54 KB (0.837%) +string_decoder: 9.24 KB (0.532%) +xml: 7.39 KB (0.426%) +process: 5.29 KB (0.305%) +deep-extend: 4.19 KB (0.241%) +stream-browserify: 3.76 KB (0.216%) +safe-buffer: 1.63 KB (0.0939%) +util-deprecate: 1.58 KB (0.0908%) +randombytes: 1.54 KB (0.0887%) +inherits: 753 B (0.0423%) +: 1.48 MB (87.2%) diff --git a/node_modules/swagger-ui-dist/log.es-bundle-sizes.swagger-ui.txt b/node_modules/swagger-ui-dist/log.es-bundle-sizes.swagger-ui.txt new file mode 100644 index 0000000000000000000000000000000000000000..79c0c1fd81b364ef502dd83c42d8ab0371af0f12 --- /dev/null +++ b/node_modules/swagger-ui-dist/log.es-bundle-sizes.swagger-ui.txt @@ -0,0 +1,114 @@ +ramda: 367.12 KB (5.33%) +lodash: 256.63 KB (3.73%) +ramda-adjunct: 255.04 KB (3.70%) +autolinker: 203.32 KB (2.95%) +@swagger-api/apidom-ns-openapi-3-0: 192.76 KB (2.80%) +swagger-client: 176.74 KB (2.57%) +@swagger-api/apidom-ns-openapi-3-1: 142.98 KB (2.08%) +immutable: 139.22 KB (2.02%) +react-dom: 129.93 KB (1.89%) +remarkable: 125.56 KB (1.82%) +highlight.js: 111.85 KB (1.62%) +dompurify: 105.71 KB (1.54%) +@swagger-api/apidom-reference: 100.62 KB (1.46%) +readable-stream: 96.66 KB (1.40%) +js-yaml: 90.16 KB (1.31%) +core-js-pure: 87.18 KB (1.27%) +minim: 57.35 KB (0.833%) +buffer: 56.99 KB (0.828%) +@swagger-api/apidom-core: 54.17 KB (0.787%) +@swagger-api/apidom-ast: 53.99 KB (0.784%) +@swagger-api/apidom-ns-json-schema-draft-4: 52.01 KB (0.755%) +react-syntax-highlighter: 40.38 KB (0.586%) +apg-lite: 38.54 KB (0.560%) +short-unique-id: 37.48 KB (0.544%) +react-redux: 36.62 KB (0.532%) +@swaggerexpert/cookie: 35.16 KB (0.511%) +@swagger-api/apidom-ns-json-schema-2019-09: 35.04 KB (0.509%) +fast-json-patch: 31.89 KB (0.463%) +@swaggerexpert/json-pointer: 30.48 KB (0.443%) +@swagger-api/apidom-ns-json-schema-draft-7: 23.62 KB (0.343%) +@swagger-api/apidom-ns-json-schema-2020-12: 22.4 KB (0.325%) +@swagger-api/apidom-ns-json-schema-draft-6: 21.63 KB (0.314%) +reselect: 21.47 KB (0.312%) +openapi-path-templating: 20.81 KB (0.302%) +neotraverse: 20.33 KB (0.295%) +sha.js: 18.92 KB (0.275%) +ts-mixer: 17.56 KB (0.255%) +tslib: 17.23 KB (0.250%) +redux: 16.37 KB (0.238%) +url-parse: 16.23 KB (0.236%) +events: 14.54 KB (0.211%) +openapi-server-url-templating: 14.38 KB (0.209%) +get-intrinsic: 14.02 KB (0.204%) +zenscroll: 12.31 KB (0.179%) +react-debounce-input: 11.95 KB (0.174%) +react-immutable-proptypes: 11.82 KB (0.172%) +ret: 10.82 KB (0.157%) +lodash.debounce: 10.53 KB (0.153%) +unraw: 9.9 KB (0.144%) +string_decoder: 9.24 KB (0.134%) +xml: 7.39 KB (0.107%) +react-copy-to-clipboard: 7.33 KB (0.106%) +react: 6.95 KB (0.101%) +randexp: 6.15 KB (0.0893%) +react-immutable-pure-component: 6.01 KB (0.0872%) +redux-immutable: 5.43 KB (0.0789%) +process: 5.29 KB (0.0768%) +drange: 4.8 KB (0.0698%) +lowlight: 4.42 KB (0.0643%) +scheduler: 4.33 KB (0.0629%) +deep-extend: 4.19 KB (0.0609%) +@babel/runtime: 3.99 KB (0.0580%) +deepmerge: 3.95 KB (0.0574%) +base64-js: 3.84 KB (0.0558%) +stream-browserify: 3.76 KB (0.0546%) +which-typed-array: 3.64 KB (0.0529%) +@swagger-api/apidom-error: 3.45 KB (0.0501%) +copy-to-clipboard: 3.29 KB (0.0477%) +format: 3.26 KB (0.0473%) +is-callable: 3.15 KB (0.0457%) +css.escape: 3.08 KB (0.0447%) +to-buffer: 3.03 KB (0.0440%) +serialize-error: 2.93 KB (0.0425%) +use-sync-external-store: 2.81 KB (0.0409%) +prop-types: 2.6 KB (0.0378%) +querystringify: 2.5 KB (0.0364%) +for-each: 2.32 KB (0.0337%) +has-symbols: 2.31 KB (0.0336%) +define-data-property: 2.28 KB (0.0331%) +xml-but-prettier: 2.17 KB (0.0314%) +function-bind: 2.12 KB (0.0308%) +ieee754: 2.1 KB (0.0306%) +safe-buffer: 1.63 KB (0.0237%) +util-deprecate: 1.58 KB (0.0229%) +randombytes: 1.54 KB (0.0224%) +js-file-download: 1.52 KB (0.0221%) +classnames: 1.49 KB (0.0217%) +call-bind-apply-helpers: 1.35 KB (0.0196%) +set-function-length: 1.24 KB (0.0181%) +repeat-string: 1.18 KB (0.0172%) +get-proto: 1.1 KB (0.0160%) +dunder-proto: 980 B (0.0139%) +@babel/runtime-corejs3: 847 B (0.0120%) +math-intrinsics: 781 B (0.0111%) +toggle-selection: 780 B (0.0111%) +requires-port: 753 B (0.0107%) +inherits: 753 B (0.0107%) +@swagger-api/apidom-json-pointer: 709 B (0.0101%) +fault: 691 B (0.00980%) +call-bound: 667 B (0.00946%) +call-bind: 643 B (0.00912%) +typed-array-buffer: 591 B (0.00838%) +has-property-descriptors: 588 B (0.00834%) +es-errors: 524 B (0.00743%) +available-typed-arrays: 475 B (0.00674%) +gopd: 303 B (0.00430%) +es-define-property: 288 B (0.00409%) +possible-typed-array-names: 264 B (0.00374%) +hasown: 206 B (0.00292%) +has-tostringtag: 189 B (0.00268%) +is-typed-array: 180 B (0.00255%) +isarray: 132 B (0.00187%) +es-object-atoms: 67 B (0.000950%) +: 3.18 MB (47.3%) diff --git a/node_modules/swagger-ui-dist/oauth2-redirect.html b/node_modules/swagger-ui-dist/oauth2-redirect.html new file mode 100644 index 0000000000000000000000000000000000000000..c4b7be174277c7dd6021a90f84d778453d913cd1 --- /dev/null +++ b/node_modules/swagger-ui-dist/oauth2-redirect.html @@ -0,0 +1,6 @@ + + + + + + diff --git a/node_modules/swagger-ui-dist/oauth2-redirect.js b/node_modules/swagger-ui-dist/oauth2-redirect.js new file mode 100644 index 0000000000000000000000000000000000000000..af2f1342f93e27f5eb296da0b2e8ba7db9ac03ee --- /dev/null +++ b/node_modules/swagger-ui-dist/oauth2-redirect.js @@ -0,0 +1 @@ +"use strict";function run(){var e,r,t,a=window.opener.swaggerUIRedirectOauth2,o=a.state,n=a.redirectUrl;if((t=(r=/code|token|error/.test(window.location.hash)?window.location.hash.substring(1).replace("?","&"):location.search.substring(1)).split("&")).forEach((function(e,r,t){t[r]='"'+e.replace("=",'":"')+'"'})),e=(r=r?JSON.parse("{"+t.join()+"}",(function(e,r){return""===e?r:decodeURIComponent(r)})):{}).state===o,"accessCode"!==a.auth.schema.get("flow")&&"authorizationCode"!==a.auth.schema.get("flow")&&"authorization_code"!==a.auth.schema.get("flow")||a.auth.code)a.callback({auth:a.auth,token:r,isValid:e,redirectUrl:n});else if(e||a.errCb({authId:a.auth.name,source:"auth",level:"warning",message:"Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"}),r.code)delete a.state,a.auth.code=r.code,a.callback({auth:a.auth,redirectUrl:n});else{let e;r.error&&(e="["+r.error+"]: "+(r.error_description?r.error_description+". ":"no accessCode received from the server. ")+(r.error_uri?"More info: "+r.error_uri:"")),a.errCb({authId:a.auth.name,source:"auth",level:"error",message:e||"[Authorization failed]: no accessCode received from the server"})}window.close()}"loading"!==document.readyState?run():document.addEventListener("DOMContentLoaded",(function(){run()})); \ No newline at end of file diff --git a/node_modules/swagger-ui-dist/package.json b/node_modules/swagger-ui-dist/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a1d893a8f42c5c737f680a6ccb9b2c249bfd88f1 --- /dev/null +++ b/node_modules/swagger-ui-dist/package.json @@ -0,0 +1,20 @@ +{ + "name": "swagger-ui-dist", + "version": "5.32.8", + "main": "index.js", + "repository": "git@github.com:swagger-api/swagger-ui.git", + "contributors": [ + "(in alphabetical order)", + "Anna Bodnia ", + "Buu Nguyen ", + "Josh Ponelat ", + "Kyle Shockey ", + "Robert Barnwell ", + "Sahar Jafari " + ], + "license": "Apache-2.0", + "dependencies": { + "@scarf/scarf": "=1.4.0" + }, + "devDependencies": {} +} diff --git a/node_modules/swagger-ui-dist/swagger-initializer.js b/node_modules/swagger-ui-dist/swagger-initializer.js new file mode 100644 index 0000000000000000000000000000000000000000..8ea0ea3afc39da4d2cb66232b9c2208cdd821570 --- /dev/null +++ b/node_modules/swagger-ui-dist/swagger-initializer.js @@ -0,0 +1,20 @@ +window.onload = function() { + // + + // the following lines will be replaced by docker/configurator, when it runs in a docker-container + window.ui = SwaggerUIBundle({ + url: "https://petstore.swagger.io/v2/swagger.json", + dom_id: '#swagger-ui', + deepLinking: true, + presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIStandalonePreset + ], + plugins: [ + SwaggerUIBundle.plugins.DownloadUrl + ], + layout: "StandaloneLayout" + }); + + // +}; diff --git a/node_modules/swagger-ui-dist/swagger-ui-bundle.js b/node_modules/swagger-ui-dist/swagger-ui-bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..a80cbc22600f2c05873f92f86ad4183b3976a04a --- /dev/null +++ b/node_modules/swagger-ui-dist/swagger-ui-bundle.js @@ -0,0 +1,2 @@ +/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */ +!function webpackUniversalModuleDefinition(s,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.SwaggerUIBundle=o():s.SwaggerUIBundle=o()}(this,(()=>(()=>{var s={67526(s,o){"use strict";o.byteLength=function byteLength(s){var o=getLens(s),i=o[0],a=o[1];return 3*(i+a)/4-a},o.toByteArray=function toByteArray(s){var o,i,_=getLens(s),w=_[0],x=_[1],C=new u(function _byteLength(s,o,i){return 3*(o+i)/4-i}(0,w,x)),j=0,L=x>0?w-4:w;for(i=0;i>16&255,C[j++]=o>>8&255,C[j++]=255&o;2===x&&(o=a[s.charCodeAt(i)]<<2|a[s.charCodeAt(i+1)]>>4,C[j++]=255&o);1===x&&(o=a[s.charCodeAt(i)]<<10|a[s.charCodeAt(i+1)]<<4|a[s.charCodeAt(i+2)]>>2,C[j++]=o>>8&255,C[j++]=255&o);return C},o.fromByteArray=function fromByteArray(s){for(var o,a=s.length,u=a%3,_=[],w=16383,x=0,C=a-u;xC?C:x+w));1===u?(o=s[a-1],_.push(i[o>>2]+i[o<<4&63]+"==")):2===u&&(o=(s[a-2]<<8)+s[a-1],_.push(i[o>>10]+i[o>>4&63]+i[o<<2&63]+"="));return _.join("")};for(var i=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",w=0;w<64;++w)i[w]=_[w],a[_.charCodeAt(w)]=w;function getLens(s){var o=s.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=s.indexOf("=");return-1===i&&(i=o),[i,i===o?0:4-i%4]}function encodeChunk(s,o,a){for(var u,_,w=[],x=o;x>18&63]+i[_>>12&63]+i[_>>6&63]+i[63&_]);return w.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},48287(s,o,i){"use strict";const a=i(67526),u=i(251),_="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;o.Buffer=Buffer,o.SlowBuffer=function SlowBuffer(s){+s!=s&&(s=0);return Buffer.alloc(+s)},o.INSPECT_MAX_BYTES=50;const w=2147483647;function createBuffer(s){if(s>w)throw new RangeError('The value "'+s+'" is invalid for option "size"');const o=new Uint8Array(s);return Object.setPrototypeOf(o,Buffer.prototype),o}function Buffer(s,o,i){if("number"==typeof s){if("string"==typeof o)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(s)}return from(s,o,i)}function from(s,o,i){if("string"==typeof s)return function fromString(s,o){"string"==typeof o&&""!==o||(o="utf8");if(!Buffer.isEncoding(o))throw new TypeError("Unknown encoding: "+o);const i=0|byteLength(s,o);let a=createBuffer(i);const u=a.write(s,o);u!==i&&(a=a.slice(0,u));return a}(s,o);if(ArrayBuffer.isView(s))return function fromArrayView(s){if(isInstance(s,Uint8Array)){const o=new Uint8Array(s);return fromArrayBuffer(o.buffer,o.byteOffset,o.byteLength)}return fromArrayLike(s)}(s);if(null==s)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(isInstance(s,ArrayBuffer)||s&&isInstance(s.buffer,ArrayBuffer))return fromArrayBuffer(s,o,i);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(s,SharedArrayBuffer)||s&&isInstance(s.buffer,SharedArrayBuffer)))return fromArrayBuffer(s,o,i);if("number"==typeof s)throw new TypeError('The "value" argument must not be of type number. Received type number');const a=s.valueOf&&s.valueOf();if(null!=a&&a!==s)return Buffer.from(a,o,i);const u=function fromObject(s){if(Buffer.isBuffer(s)){const o=0|checked(s.length),i=createBuffer(o);return 0===i.length||s.copy(i,0,0,o),i}if(void 0!==s.length)return"number"!=typeof s.length||numberIsNaN(s.length)?createBuffer(0):fromArrayLike(s);if("Buffer"===s.type&&Array.isArray(s.data))return fromArrayLike(s.data)}(s);if(u)return u;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof s[Symbol.toPrimitive])return Buffer.from(s[Symbol.toPrimitive]("string"),o,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}function assertSize(s){if("number"!=typeof s)throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function allocUnsafe(s){return assertSize(s),createBuffer(s<0?0:0|checked(s))}function fromArrayLike(s){const o=s.length<0?0:0|checked(s.length),i=createBuffer(o);for(let a=0;a=w)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+w.toString(16)+" bytes");return 0|s}function byteLength(s,o){if(Buffer.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||isInstance(s,ArrayBuffer))return s.byteLength;if("string"!=typeof s)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const i=s.length,a=arguments.length>2&&!0===arguments[2];if(!a&&0===i)return 0;let u=!1;for(;;)switch(o){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return utf8ToBytes(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return base64ToBytes(s).length;default:if(u)return a?-1:utf8ToBytes(s).length;o=(""+o).toLowerCase(),u=!0}}function slowToString(s,o,i){let a=!1;if((void 0===o||o<0)&&(o=0),o>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(o>>>=0))return"";for(s||(s="utf8");;)switch(s){case"hex":return hexSlice(this,o,i);case"utf8":case"utf-8":return utf8Slice(this,o,i);case"ascii":return asciiSlice(this,o,i);case"latin1":case"binary":return latin1Slice(this,o,i);case"base64":return base64Slice(this,o,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,o,i);default:if(a)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),a=!0}}function swap(s,o,i){const a=s[o];s[o]=s[i],s[i]=a}function bidirectionalIndexOf(s,o,i,a,u){if(0===s.length)return-1;if("string"==typeof i?(a=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),numberIsNaN(i=+i)&&(i=u?0:s.length-1),i<0&&(i=s.length+i),i>=s.length){if(u)return-1;i=s.length-1}else if(i<0){if(!u)return-1;i=0}if("string"==typeof o&&(o=Buffer.from(o,a)),Buffer.isBuffer(o))return 0===o.length?-1:arrayIndexOf(s,o,i,a,u);if("number"==typeof o)return o&=255,"function"==typeof Uint8Array.prototype.indexOf?u?Uint8Array.prototype.indexOf.call(s,o,i):Uint8Array.prototype.lastIndexOf.call(s,o,i):arrayIndexOf(s,[o],i,a,u);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(s,o,i,a,u){let _,w=1,x=s.length,C=o.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(s.length<2||o.length<2)return-1;w=2,x/=2,C/=2,i/=2}function read(s,o){return 1===w?s[o]:s.readUInt16BE(o*w)}if(u){let a=-1;for(_=i;_x&&(i=x-C),_=i;_>=0;_--){let i=!0;for(let a=0;au&&(a=u):a=u;const _=o.length;let w;for(a>_/2&&(a=_/2),w=0;w>8,u=i%256,_.push(u),_.push(a);return _}(o,s.length-i),s,i,a)}function base64Slice(s,o,i){return 0===o&&i===s.length?a.fromByteArray(s):a.fromByteArray(s.slice(o,i))}function utf8Slice(s,o,i){i=Math.min(s.length,i);const a=[];let u=o;for(;u239?4:o>223?3:o>191?2:1;if(u+w<=i){let i,a,x,C;switch(w){case 1:o<128&&(_=o);break;case 2:i=s[u+1],128==(192&i)&&(C=(31&o)<<6|63&i,C>127&&(_=C));break;case 3:i=s[u+1],a=s[u+2],128==(192&i)&&128==(192&a)&&(C=(15&o)<<12|(63&i)<<6|63&a,C>2047&&(C<55296||C>57343)&&(_=C));break;case 4:i=s[u+1],a=s[u+2],x=s[u+3],128==(192&i)&&128==(192&a)&&128==(192&x)&&(C=(15&o)<<18|(63&i)<<12|(63&a)<<6|63&x,C>65535&&C<1114112&&(_=C))}}null===_?(_=65533,w=1):_>65535&&(_-=65536,a.push(_>>>10&1023|55296),_=56320|1023&_),a.push(_),u+=w}return function decodeCodePointsArray(s){const o=s.length;if(o<=x)return String.fromCharCode.apply(String,s);let i="",a=0;for(;aa.length?(Buffer.isBuffer(o)||(o=Buffer.from(o)),o.copy(a,u)):Uint8Array.prototype.set.call(a,o,u);else{if(!Buffer.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(a,u)}u+=o.length}return a},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const s=this.length;if(s%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let o=0;oi&&(s+=" ... "),""},_&&(Buffer.prototype[_]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(s,o,i,a,u){if(isInstance(s,Uint8Array)&&(s=Buffer.from(s,s.offset,s.byteLength)),!Buffer.isBuffer(s))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof s);if(void 0===o&&(o=0),void 0===i&&(i=s?s.length:0),void 0===a&&(a=0),void 0===u&&(u=this.length),o<0||i>s.length||a<0||u>this.length)throw new RangeError("out of range index");if(a>=u&&o>=i)return 0;if(a>=u)return-1;if(o>=i)return 1;if(this===s)return 0;let _=(u>>>=0)-(a>>>=0),w=(i>>>=0)-(o>>>=0);const x=Math.min(_,w),C=this.slice(a,u),j=s.slice(o,i);for(let s=0;s>>=0,isFinite(i)?(i>>>=0,void 0===a&&(a="utf8")):(a=i,i=void 0)}const u=this.length-o;if((void 0===i||i>u)&&(i=u),s.length>0&&(i<0||o<0)||o>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");let _=!1;for(;;)switch(a){case"hex":return hexWrite(this,s,o,i);case"utf8":case"utf-8":return utf8Write(this,s,o,i);case"ascii":case"latin1":case"binary":return asciiWrite(this,s,o,i);case"base64":return base64Write(this,s,o,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,s,o,i);default:if(_)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),_=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function asciiSlice(s,o,i){let a="";i=Math.min(s.length,i);for(let u=o;ua)&&(i=a);let u="";for(let a=o;ai)throw new RangeError("Trying to access beyond buffer length")}function checkInt(s,o,i,a,u,_){if(!Buffer.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(o>u||o<_)throw new RangeError('"value" argument is out of bounds');if(i+a>s.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(s,o,i,a,u){checkIntBI(o,a,u,s,i,7);let _=Number(o&BigInt(4294967295));s[i++]=_,_>>=8,s[i++]=_,_>>=8,s[i++]=_,_>>=8,s[i++]=_;let w=Number(o>>BigInt(32)&BigInt(4294967295));return s[i++]=w,w>>=8,s[i++]=w,w>>=8,s[i++]=w,w>>=8,s[i++]=w,i}function wrtBigUInt64BE(s,o,i,a,u){checkIntBI(o,a,u,s,i,7);let _=Number(o&BigInt(4294967295));s[i+7]=_,_>>=8,s[i+6]=_,_>>=8,s[i+5]=_,_>>=8,s[i+4]=_;let w=Number(o>>BigInt(32)&BigInt(4294967295));return s[i+3]=w,w>>=8,s[i+2]=w,w>>=8,s[i+1]=w,w>>=8,s[i]=w,i+8}function checkIEEE754(s,o,i,a,u,_){if(i+a>s.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function writeFloat(s,o,i,a,_){return o=+o,i>>>=0,_||checkIEEE754(s,0,i,4),u.write(s,o,i,a,23,4),i+4}function writeDouble(s,o,i,a,_){return o=+o,i>>>=0,_||checkIEEE754(s,0,i,8),u.write(s,o,i,a,52,8),i+8}Buffer.prototype.slice=function slice(s,o){const i=this.length;(s=~~s)<0?(s+=i)<0&&(s=0):s>i&&(s=i),(o=void 0===o?i:~~o)<0?(o+=i)<0&&(o=0):o>i&&(o=i),o>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s],u=1,_=0;for(;++_>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s+--o],u=1;for(;o>0&&(u*=256);)a+=this[s+--o]*u;return a},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(s,o){return s>>>=0,o||checkOffset(s,1,this.length),this[s]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(s,o){return s>>>=0,o||checkOffset(s,2,this.length),this[s]|this[s+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(s,o){return s>>>=0,o||checkOffset(s,2,this.length),this[s]<<8|this[s+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),(this[s]|this[s+1]<<8|this[s+2]<<16)+16777216*this[s+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),16777216*this[s]+(this[s+1]<<16|this[s+2]<<8|this[s+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(s){validateNumber(s>>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=o+256*this[++s]+65536*this[++s]+this[++s]*2**24,u=this[++s]+256*this[++s]+65536*this[++s]+i*2**24;return BigInt(a)+(BigInt(u)<>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=o*2**24+65536*this[++s]+256*this[++s]+this[++s],u=this[++s]*2**24+65536*this[++s]+256*this[++s]+i;return(BigInt(a)<>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=this[s],u=1,_=0;for(;++_=u&&(a-=Math.pow(2,8*o)),a},Buffer.prototype.readIntBE=function readIntBE(s,o,i){s>>>=0,o>>>=0,i||checkOffset(s,o,this.length);let a=o,u=1,_=this[s+--a];for(;a>0&&(u*=256);)_+=this[s+--a]*u;return u*=128,_>=u&&(_-=Math.pow(2,8*o)),_},Buffer.prototype.readInt8=function readInt8(s,o){return s>>>=0,o||checkOffset(s,1,this.length),128&this[s]?-1*(255-this[s]+1):this[s]},Buffer.prototype.readInt16LE=function readInt16LE(s,o){s>>>=0,o||checkOffset(s,2,this.length);const i=this[s]|this[s+1]<<8;return 32768&i?4294901760|i:i},Buffer.prototype.readInt16BE=function readInt16BE(s,o){s>>>=0,o||checkOffset(s,2,this.length);const i=this[s+1]|this[s]<<8;return 32768&i?4294901760|i:i},Buffer.prototype.readInt32LE=function readInt32LE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),this[s]|this[s+1]<<8|this[s+2]<<16|this[s+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),this[s]<<24|this[s+1]<<16|this[s+2]<<8|this[s+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(s){validateNumber(s>>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=this[s+4]+256*this[s+5]+65536*this[s+6]+(i<<24);return(BigInt(a)<>>=0,"offset");const o=this[s],i=this[s+7];void 0!==o&&void 0!==i||boundsError(s,this.length-8);const a=(o<<24)+65536*this[++s]+256*this[++s]+this[++s];return(BigInt(a)<>>=0,o||checkOffset(s,4,this.length),u.read(this,s,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(s,o){return s>>>=0,o||checkOffset(s,4,this.length),u.read(this,s,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(s,o){return s>>>=0,o||checkOffset(s,8,this.length),u.read(this,s,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(s,o){return s>>>=0,o||checkOffset(s,8,this.length),u.read(this,s,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(s,o,i,a){if(s=+s,o>>>=0,i>>>=0,!a){checkInt(this,s,o,i,Math.pow(2,8*i)-1,0)}let u=1,_=0;for(this[o]=255&s;++_>>=0,i>>>=0,!a){checkInt(this,s,o,i,Math.pow(2,8*i)-1,0)}let u=i-1,_=1;for(this[o+u]=255&s;--u>=0&&(_*=256);)this[o+u]=s/_&255;return o+i},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,1,255,0),this[o]=255&s,o+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,65535,0),this[o]=255&s,this[o+1]=s>>>8,o+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,65535,0),this[o]=s>>>8,this[o+1]=255&s,o+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,4294967295,0),this[o+3]=s>>>24,this[o+2]=s>>>16,this[o+1]=s>>>8,this[o]=255&s,o+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,4294967295,0),this[o]=s>>>24,this[o+1]=s>>>16,this[o+2]=s>>>8,this[o+3]=255&s,o+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(s,o=0){return wrtBigUInt64LE(this,s,o,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(s,o=0){return wrtBigUInt64BE(this,s,o,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeIntLE=function writeIntLE(s,o,i,a){if(s=+s,o>>>=0,!a){const a=Math.pow(2,8*i-1);checkInt(this,s,o,i,a-1,-a)}let u=0,_=1,w=0;for(this[o]=255&s;++u>>=0,!a){const a=Math.pow(2,8*i-1);checkInt(this,s,o,i,a-1,-a)}let u=i-1,_=1,w=0;for(this[o+u]=255&s;--u>=0&&(_*=256);)s<0&&0===w&&0!==this[o+u+1]&&(w=1),this[o+u]=(s/_|0)-w&255;return o+i},Buffer.prototype.writeInt8=function writeInt8(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,1,127,-128),s<0&&(s=255+s+1),this[o]=255&s,o+1},Buffer.prototype.writeInt16LE=function writeInt16LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,32767,-32768),this[o]=255&s,this[o+1]=s>>>8,o+2},Buffer.prototype.writeInt16BE=function writeInt16BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,2,32767,-32768),this[o]=s>>>8,this[o+1]=255&s,o+2},Buffer.prototype.writeInt32LE=function writeInt32LE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,2147483647,-2147483648),this[o]=255&s,this[o+1]=s>>>8,this[o+2]=s>>>16,this[o+3]=s>>>24,o+4},Buffer.prototype.writeInt32BE=function writeInt32BE(s,o,i){return s=+s,o>>>=0,i||checkInt(this,s,o,4,2147483647,-2147483648),s<0&&(s=4294967295+s+1),this[o]=s>>>24,this[o+1]=s>>>16,this[o+2]=s>>>8,this[o+3]=255&s,o+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(s,o=0){return wrtBigUInt64LE(this,s,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(s,o=0){return wrtBigUInt64BE(this,s,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeFloatLE=function writeFloatLE(s,o,i){return writeFloat(this,s,o,!0,i)},Buffer.prototype.writeFloatBE=function writeFloatBE(s,o,i){return writeFloat(this,s,o,!1,i)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(s,o,i){return writeDouble(this,s,o,!0,i)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(s,o,i){return writeDouble(this,s,o,!1,i)},Buffer.prototype.copy=function copy(s,o,i,a){if(!Buffer.isBuffer(s))throw new TypeError("argument should be a Buffer");if(i||(i=0),a||0===a||(a=this.length),o>=s.length&&(o=s.length),o||(o=0),a>0&&a=this.length)throw new RangeError("Index out of range");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),s.length-o>>=0,i=void 0===i?this.length:i>>>0,s||(s=0),"number"==typeof s)for(u=o;u=a+4;i-=3)o=`_${s.slice(i-3,i)}${o}`;return`${s.slice(0,i)}${o}`}function checkIntBI(s,o,i,a,u,_){if(s>i||s3?0===o||o===BigInt(0)?`>= 0${a} and < 2${a} ** ${8*(_+1)}${a}`:`>= -(2${a} ** ${8*(_+1)-1}${a}) and < 2 ** ${8*(_+1)-1}${a}`:`>= ${o}${a} and <= ${i}${a}`,new C.ERR_OUT_OF_RANGE("value",u,s)}!function checkBounds(s,o,i){validateNumber(o,"offset"),void 0!==s[o]&&void 0!==s[o+i]||boundsError(o,s.length-(i+1))}(a,u,_)}function validateNumber(s,o){if("number"!=typeof s)throw new C.ERR_INVALID_ARG_TYPE(o,"number",s)}function boundsError(s,o,i){if(Math.floor(s)!==s)throw validateNumber(s,i),new C.ERR_OUT_OF_RANGE(i||"offset","an integer",s);if(o<0)throw new C.ERR_BUFFER_OUT_OF_BOUNDS;throw new C.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${o}`,s)}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),E("ERR_INVALID_ARG_TYPE",(function(s,o){return`The "${s}" argument must be of type number. Received type ${typeof o}`}),TypeError),E("ERR_OUT_OF_RANGE",(function(s,o,i){let a=`The value of "${s}" is out of range.`,u=i;return Number.isInteger(i)&&Math.abs(i)>2**32?u=addNumericalSeparator(String(i)):"bigint"==typeof i&&(u=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(u=addNumericalSeparator(u)),u+="n"),a+=` It must be ${o}. Received ${u}`,a}),RangeError);const j=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(s,o){let i;o=o||1/0;const a=s.length;let u=null;const _=[];for(let w=0;w55295&&i<57344){if(!u){if(i>56319){(o-=3)>-1&&_.push(239,191,189);continue}if(w+1===a){(o-=3)>-1&&_.push(239,191,189);continue}u=i;continue}if(i<56320){(o-=3)>-1&&_.push(239,191,189),u=i;continue}i=65536+(u-55296<<10|i-56320)}else u&&(o-=3)>-1&&_.push(239,191,189);if(u=null,i<128){if((o-=1)<0)break;_.push(i)}else if(i<2048){if((o-=2)<0)break;_.push(i>>6|192,63&i|128)}else if(i<65536){if((o-=3)<0)break;_.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((o-=4)<0)break;_.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return _}function base64ToBytes(s){return a.toByteArray(function base64clean(s){if((s=(s=s.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;s.length%4!=0;)s+="=";return s}(s))}function blitBuffer(s,o,i,a){let u;for(u=0;u=o.length||u>=s.length);++u)o[u+i]=s[u];return u}function isInstance(s,o){return s instanceof o||null!=s&&null!=s.constructor&&null!=s.constructor.name&&s.constructor.name===o.name}function numberIsNaN(s){return s!=s}const L=function(){const s="0123456789abcdef",o=new Array(256);for(let i=0;i<16;++i){const a=16*i;for(let u=0;u<16;++u)o[a+u]=s[i]+s[u]}return o}();function defineBigIntMethod(s){return"undefined"==typeof BigInt?BufferBigIntNotDefined:s}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}},13144(s,o,i){"use strict";var a=i(66743),u=i(11002),_=i(10076),w=i(47119);s.exports=w||a.call(_,u)},12205(s,o,i){"use strict";var a=i(66743),u=i(11002),_=i(13144);s.exports=function applyBind(){return _(a,u,arguments)}},11002(s){"use strict";s.exports=Function.prototype.apply},10076(s){"use strict";s.exports=Function.prototype.call},73126(s,o,i){"use strict";var a=i(66743),u=i(69675),_=i(10076),w=i(13144);s.exports=function callBindBasic(s){if(s.length<1||"function"!=typeof s[0])throw new u("a function is required");return w(a,_,s)}},47119(s){"use strict";s.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},10487(s,o,i){"use strict";var a=i(96897),u=i(30655),_=i(73126),w=i(12205);s.exports=function callBind(s){var o=_(arguments),i=s.length-(arguments.length-1);return a(o,1+(i>0?i:0),!0)},u?u(s.exports,"apply",{value:w}):s.exports.apply=w},36556(s,o,i){"use strict";var a=i(70453),u=i(73126),_=u([a("%String.prototype.indexOf%")]);s.exports=function callBoundIntrinsic(s,o){var i=a(s,!!o);return"function"==typeof i&&_(s,".prototype.")>-1?u([i]):i}},17965(s,o,i){"use strict";var a=i(16426),u={"text/plain":"Text","text/html":"Url",default:"Text"};s.exports=function copy(s,o){var i,_,w,x,C,j,L=!1;o||(o={}),i=o.debug||!1;try{if(w=a(),x=document.createRange(),C=document.getSelection(),(j=document.createElement("span")).textContent=s,j.ariaHidden="true",j.style.all="unset",j.style.position="fixed",j.style.top=0,j.style.clip="rect(0, 0, 0, 0)",j.style.whiteSpace="pre",j.style.webkitUserSelect="text",j.style.MozUserSelect="text",j.style.msUserSelect="text",j.style.userSelect="text",j.addEventListener("copy",(function(a){if(a.stopPropagation(),o.format)if(a.preventDefault(),void 0===a.clipboardData){i&&console.warn("unable to use e.clipboardData"),i&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var _=u[o.format]||u.default;window.clipboardData.setData(_,s)}else a.clipboardData.clearData(),a.clipboardData.setData(o.format,s);o.onCopy&&(a.preventDefault(),o.onCopy(a.clipboardData))})),document.body.appendChild(j),x.selectNodeContents(j),C.addRange(x),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");L=!0}catch(a){i&&console.error("unable to copy using execCommand: ",a),i&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(o.format||"text",s),o.onCopy&&o.onCopy(window.clipboardData),L=!0}catch(a){i&&console.error("unable to copy using clipboardData: ",a),i&&console.error("falling back to prompt"),_=function format(s){var o=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return s.replace(/#{\s*key\s*}/g,o)}("message"in o?o.message:"Copy to clipboard: #{key}, Enter"),window.prompt(_,s)}}finally{C&&("function"==typeof C.removeRange?C.removeRange(x):C.removeAllRanges()),j&&document.body.removeChild(j),w()}return L}},2205(s,o,i){var a;a=void 0!==i.g?i.g:this,s.exports=function(s){if(s.CSS&&s.CSS.escape)return s.CSS.escape;var cssEscape=function(s){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var o,i=String(s),a=i.length,u=-1,_="",w=i.charCodeAt(0);++u=1&&o<=31||127==o||0==u&&o>=48&&o<=57||1==u&&o>=48&&o<=57&&45==w?"\\"+o.toString(16)+" ":0==u&&1==a&&45==o||!(o>=128||45==o||95==o||o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122)?"\\"+i.charAt(u):i.charAt(u):_+="�";return _};return s.CSS||(s.CSS={}),s.CSS.escape=cssEscape,cssEscape}(a)},81919(s,o,i){"use strict";var a=i(48287).Buffer;function isSpecificValue(s){return s instanceof a||s instanceof Date||s instanceof RegExp}function cloneSpecificValue(s){if(s instanceof a){var o=a.alloc?a.alloc(s.length):new a(s.length);return s.copy(o),o}if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s);throw new Error("Unexpected situation")}function deepCloneArray(s){var o=[];return s.forEach((function(s,i){"object"==typeof s&&null!==s?Array.isArray(s)?o[i]=deepCloneArray(s):isSpecificValue(s)?o[i]=cloneSpecificValue(s):o[i]=u({},s):o[i]=s})),o}function safeGetProperty(s,o){return"__proto__"===o?void 0:s[o]}var u=s.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var s,o,i=arguments[0];return Array.prototype.slice.call(arguments,1).forEach((function(a){"object"!=typeof a||null===a||Array.isArray(a)||Object.keys(a).forEach((function(_){return o=safeGetProperty(i,_),(s=safeGetProperty(a,_))===i?void 0:"object"!=typeof s||null===s?void(i[_]=s):Array.isArray(s)?void(i[_]=deepCloneArray(s)):isSpecificValue(s)?void(i[_]=cloneSpecificValue(s)):"object"!=typeof o||null===o||Array.isArray(o)?void(i[_]=u({},s)):void(i[_]=u(o,s))}))})),i}},14744(s){"use strict";var o=function isMergeableObject(s){return function isNonNullObject(s){return!!s&&"object"==typeof s}(s)&&!function isSpecial(s){var o=Object.prototype.toString.call(s);return"[object RegExp]"===o||"[object Date]"===o||function isReactElement(s){return s.$$typeof===i}(s)}(s)};var i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function cloneUnlessOtherwiseSpecified(s,o){return!1!==o.clone&&o.isMergeableObject(s)?deepmerge(function emptyTarget(s){return Array.isArray(s)?[]:{}}(s),s,o):s}function defaultArrayMerge(s,o,i){return s.concat(o).map((function(s){return cloneUnlessOtherwiseSpecified(s,i)}))}function getKeys(s){return Object.keys(s).concat(function getEnumerableOwnPropertySymbols(s){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(s).filter((function(o){return Object.propertyIsEnumerable.call(s,o)})):[]}(s))}function propertyIsOnObject(s,o){try{return o in s}catch(s){return!1}}function mergeObject(s,o,i){var a={};return i.isMergeableObject(s)&&getKeys(s).forEach((function(o){a[o]=cloneUnlessOtherwiseSpecified(s[o],i)})),getKeys(o).forEach((function(u){(function propertyIsUnsafe(s,o){return propertyIsOnObject(s,o)&&!(Object.hasOwnProperty.call(s,o)&&Object.propertyIsEnumerable.call(s,o))})(s,u)||(propertyIsOnObject(s,u)&&i.isMergeableObject(o[u])?a[u]=function getMergeFunction(s,o){if(!o.customMerge)return deepmerge;var i=o.customMerge(s);return"function"==typeof i?i:deepmerge}(u,i)(s[u],o[u],i):a[u]=cloneUnlessOtherwiseSpecified(o[u],i))})),a}function deepmerge(s,i,a){(a=a||{}).arrayMerge=a.arrayMerge||defaultArrayMerge,a.isMergeableObject=a.isMergeableObject||o,a.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var u=Array.isArray(i);return u===Array.isArray(s)?u?a.arrayMerge(s,i,a):mergeObject(s,i,a):cloneUnlessOtherwiseSpecified(i,a)}deepmerge.all=function deepmergeAll(s,o){if(!Array.isArray(s))throw new Error("first argument should be an array");return s.reduce((function(s,i){return deepmerge(s,i,o)}),{})};var a=deepmerge;s.exports=a},30041(s,o,i){"use strict";var a=i(30655),u=i(58068),_=i(69675),w=i(75795);s.exports=function defineDataProperty(s,o,i){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new _("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new _("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new _("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new _("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new _("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new _("`loose`, if provided, must be a boolean");var x=arguments.length>3?arguments[3]:null,C=arguments.length>4?arguments[4]:null,j=arguments.length>5?arguments[5]:null,L=arguments.length>6&&arguments[6],B=!!w&&w(s,o);if(a)a(s,o,{configurable:null===j&&B?B.configurable:!j,enumerable:null===x&&B?B.enumerable:!x,value:i,writable:null===C&&B?B.writable:!C});else{if(!L&&(x||C||j))throw new u("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");s[o]=i}}},78004(s){"use strict";class SubRange{constructor(s,o){this.low=s,this.high=o,this.length=1+o-s}overlaps(s){return!(this.highs.high)}touches(s){return!(this.high+1s.high)}add(s){return new SubRange(Math.min(this.low,s.low),Math.max(this.high,s.high))}subtract(s){return s.low<=this.low&&s.high>=this.high?[]:s.low>this.low&&s.highs+o.length),0)}add(s,o){var _add=s=>{for(var o=0;o{for(var o=0;o{for(var o=0;o{for(var i=o.low;i<=o.high;)s.push(i),i++;return s}),[])}subranges(){return this.ranges.map((s=>({low:s.low,high:s.high,length:1+s.high-s.low})))}}s.exports=DRange},7176(s,o,i){"use strict";var a,u=i(73126),_=i(75795);try{a=[].__proto__===Array.prototype}catch(s){if(!s||"object"!=typeof s||!("code"in s)||"ERR_PROTO_ACCESS"!==s.code)throw s}var w=!!a&&_&&_(Object.prototype,"__proto__"),x=Object,C=x.getPrototypeOf;s.exports=w&&"function"==typeof w.get?u([w.get]):"function"==typeof C&&function getDunder(s){return C(null==s?s:x(s))}},30655(s){"use strict";var o=Object.defineProperty||!1;if(o)try{o({},"a",{value:1})}catch(s){o=!1}s.exports=o},41237(s){"use strict";s.exports=EvalError},69383(s){"use strict";s.exports=Error},79290(s){"use strict";s.exports=RangeError},79538(s){"use strict";s.exports=ReferenceError},58068(s){"use strict";s.exports=SyntaxError},69675(s){"use strict";s.exports=TypeError},35345(s){"use strict";s.exports=URIError},79612(s){"use strict";s.exports=Object},37007(s){"use strict";var o,i="object"==typeof Reflect?Reflect:null,a=i&&"function"==typeof i.apply?i.apply:function ReflectApply(s,o,i){return Function.prototype.apply.call(s,o,i)};o=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:function ReflectOwnKeys(s){return Object.getOwnPropertyNames(s)};var u=Number.isNaN||function NumberIsNaN(s){return s!=s};function EventEmitter(){EventEmitter.init.call(this)}s.exports=EventEmitter,s.exports.once=function once(s,o){return new Promise((function(i,a){function errorListener(i){s.removeListener(o,resolver),a(i)}function resolver(){"function"==typeof s.removeListener&&s.removeListener("error",errorListener),i([].slice.call(arguments))}eventTargetAgnosticAddListener(s,o,resolver,{once:!0}),"error"!==o&&function addErrorHandlerIfEventEmitter(s,o,i){"function"==typeof s.on&&eventTargetAgnosticAddListener(s,"error",o,i)}(s,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var _=10;function checkListener(s){if("function"!=typeof s)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}function _getMaxListeners(s){return void 0===s._maxListeners?EventEmitter.defaultMaxListeners:s._maxListeners}function _addListener(s,o,i,a){var u,_,w;if(checkListener(i),void 0===(_=s._events)?(_=s._events=Object.create(null),s._eventsCount=0):(void 0!==_.newListener&&(s.emit("newListener",o,i.listener?i.listener:i),_=s._events),w=_[o]),void 0===w)w=_[o]=i,++s._eventsCount;else if("function"==typeof w?w=_[o]=a?[i,w]:[w,i]:a?w.unshift(i):w.push(i),(u=_getMaxListeners(s))>0&&w.length>u&&!w.warned){w.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+w.length+" "+String(o)+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=s,x.type=o,x.count=w.length,function ProcessEmitWarning(s){console&&console.warn&&console.warn(s)}(x)}return s}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(s,o,i){var a={fired:!1,wrapFn:void 0,target:s,type:o,listener:i},u=onceWrapper.bind(a);return u.listener=i,a.wrapFn=u,u}function _listeners(s,o,i){var a=s._events;if(void 0===a)return[];var u=a[o];return void 0===u?[]:"function"==typeof u?i?[u.listener||u]:[u]:i?function unwrapListeners(s){for(var o=new Array(s.length),i=0;i0&&(w=o[0]),w instanceof Error)throw w;var x=new Error("Unhandled error."+(w?" ("+w.message+")":""));throw x.context=w,x}var C=_[s];if(void 0===C)return!1;if("function"==typeof C)a(C,this,o);else{var j=C.length,L=arrayClone(C,j);for(i=0;i=0;_--)if(i[_]===o||i[_].listener===o){w=i[_].listener,u=_;break}if(u<0)return this;0===u?i.shift():function spliceOne(s,o){for(;o+1=0;a--)this.removeListener(s,o[a]);return this},EventEmitter.prototype.listeners=function listeners(s){return _listeners(this,s,!0)},EventEmitter.prototype.rawListeners=function rawListeners(s){return _listeners(this,s,!1)},EventEmitter.listenerCount=function(s,o){return"function"==typeof s.listenerCount?s.listenerCount(o):listenerCount.call(s,o)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?o(this._events):[]}},85587(s,o,i){"use strict";var a=i(26311),u=create(Error);function create(s){return FormattedError.displayName=s.displayName||s.name,FormattedError;function FormattedError(o){return o&&(o=a.apply(null,arguments)),new s(o)}}s.exports=u,u.eval=create(EvalError),u.range=create(RangeError),u.reference=create(ReferenceError),u.syntax=create(SyntaxError),u.type=create(TypeError),u.uri=create(URIError),u.create=create},82682(s,o,i){"use strict";var a=i(69600),u=Object.prototype.toString,_=Object.prototype.hasOwnProperty;s.exports=function forEach(s,o,i){if(!a(o))throw new TypeError("iterator must be a function");var w;arguments.length>=3&&(w=i),function isArray(s){return"[object Array]"===u.call(s)}(s)?function forEachArray(s,o,i){for(var a=0,u=s.length;a0?parseInt(i):null};x1&&"boolean"!=typeof o)throw new L('"allowMissing" argument must be a boolean');if(null===Xe(/^%?[^%]*%?$/,s))throw new j("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function stringToPath(s){var o=Ye(s,0,1),i=Ye(s,-1);if("%"===o&&"%"!==i)throw new j("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==o)throw new j("invalid intrinsic syntax, expected opening `%`");var a=[];return He(s,Qe,(function(s,o,i,u){a[a.length]=i?He(u,et,"$1"):o||s})),a}(s),a=i.length>0?i[0]:"",u=tt("%"+a+"%",o),_=u.name,w=u.value,x=!1,C=u.alias;C&&(a=C[0],We(i,ze([0,1],C)));for(var B=1,$=!0;B=i.length){var Y=ae(w,U);w=($=!!Y)&&"get"in Y&&!("originalValue"in Y.get)?Y.get:w[U]}else $=qe(w,U),w=w[U];$&&!x&&(xe[_]=w)}}return w}},71064(s,o,i){"use strict";var a=i(79612);s.exports=a.getPrototypeOf||null},48648(s){"use strict";s.exports="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null},93628(s,o,i){"use strict";var a=i(48648),u=i(71064),_=i(7176);s.exports=a?function getProto(s){return a(s)}:u?function getProto(s){if(!s||"object"!=typeof s&&"function"!=typeof s)throw new TypeError("getProto: not an object");return u(s)}:_?function getProto(s){return _(s)}:null},6549(s){"use strict";s.exports=Object.getOwnPropertyDescriptor},75795(s,o,i){"use strict";var a=i(6549);if(a)try{a([],"length")}catch(s){a=null}s.exports=a},30592(s,o,i){"use strict";var a=i(30655),u=function hasPropertyDescriptors(){return!!a};u.hasArrayLengthDefineBug=function hasArrayLengthDefineBug(){if(!a)return null;try{return 1!==a([],"length",{value:1}).length}catch(s){return!0}},s.exports=u},64039(s,o,i){"use strict";var a="undefined"!=typeof Symbol&&Symbol,u=i(41333);s.exports=function hasNativeSymbols(){return"function"==typeof a&&("function"==typeof Symbol&&("symbol"==typeof a("foo")&&("symbol"==typeof Symbol("bar")&&u())))}},41333(s){"use strict";s.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var s={},o=Symbol("test"),i=Object(o);if("string"==typeof o)return!1;if("[object Symbol]"!==Object.prototype.toString.call(o))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var a in s[o]=42,s)return!1;if("function"==typeof Object.keys&&0!==Object.keys(s).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(s).length)return!1;var u=Object.getOwnPropertySymbols(s);if(1!==u.length||u[0]!==o)return!1;if(!Object.prototype.propertyIsEnumerable.call(s,o))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var _=Object.getOwnPropertyDescriptor(s,o);if(42!==_.value||!0!==_.enumerable)return!1}return!0}},49092(s,o,i){"use strict";var a=i(41333);s.exports=function hasToStringTagShams(){return a()&&!!Symbol.toStringTag}},9957(s,o,i){"use strict";var a=Function.prototype.call,u=Object.prototype.hasOwnProperty,_=i(66743);s.exports=_.call(a,u)},45981(s){function deepFreeze(s){return s instanceof Map?s.clear=s.delete=s.set=function(){throw new Error("map is read-only")}:s instanceof Set&&(s.add=s.clear=s.delete=function(){throw new Error("set is read-only")}),Object.freeze(s),Object.getOwnPropertyNames(s).forEach((function(o){var i=s[o];"object"!=typeof i||Object.isFrozen(i)||deepFreeze(i)})),s}var o=deepFreeze,i=deepFreeze;o.default=i;class Response{constructor(s){void 0===s.data&&(s.data={}),this.data=s.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function escapeHTML(s){return s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function inherit(s,...o){const i=Object.create(null);for(const o in s)i[o]=s[o];return o.forEach((function(s){for(const o in s)i[o]=s[o]})),i}const emitsWrappingTags=s=>!!s.kind;class HTMLRenderer{constructor(s,o){this.buffer="",this.classPrefix=o.classPrefix,s.walk(this)}addText(s){this.buffer+=escapeHTML(s)}openNode(s){if(!emitsWrappingTags(s))return;let o=s.kind;s.sublanguage||(o=`${this.classPrefix}${o}`),this.span(o)}closeNode(s){emitsWrappingTags(s)&&(this.buffer+="")}value(){return this.buffer}span(s){this.buffer+=``}}class TokenTree{constructor(){this.rootNode={children:[]},this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(s){this.top.children.push(s)}openNode(s){const o={kind:s,children:[]};this.add(o),this.stack.push(o)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(s){return this.constructor._walk(s,this.rootNode)}static _walk(s,o){return"string"==typeof o?s.addText(o):o.children&&(s.openNode(o),o.children.forEach((o=>this._walk(s,o))),s.closeNode(o)),s}static _collapse(s){"string"!=typeof s&&s.children&&(s.children.every((s=>"string"==typeof s))?s.children=[s.children.join("")]:s.children.forEach((s=>{TokenTree._collapse(s)})))}}class TokenTreeEmitter extends TokenTree{constructor(s){super(),this.options=s}addKeyword(s,o){""!==s&&(this.openNode(o),this.addText(s),this.closeNode())}addText(s){""!==s&&this.add(s)}addSublanguage(s,o){const i=s.root;i.kind=o,i.sublanguage=!0,this.add(i)}toHTML(){return new HTMLRenderer(this,this.options).value()}finalize(){return!0}}function source(s){return s?"string"==typeof s?s:s.source:null}const a=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;const u="[a-zA-Z]\\w*",_="[a-zA-Z_]\\w*",w="\\b\\d+(\\.\\d+)?",x="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",C="\\b(0b[01]+)",j={begin:"\\\\[\\s\\S]",relevance:0},L={className:"string",begin:"'",end:"'",illegal:"\\n",contains:[j]},B={className:"string",begin:'"',end:'"',illegal:"\\n",contains:[j]},$={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},COMMENT=function(s,o,i={}){const a=inherit({className:"comment",begin:s,end:o,contains:[]},i);return a.contains.push($),a.contains.push({className:"doctag",begin:"(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):",relevance:0}),a},U=COMMENT("//","$"),V=COMMENT("/\\*","\\*/"),z=COMMENT("#","$"),Y={className:"number",begin:w,relevance:0},Z={className:"number",begin:x,relevance:0},ee={className:"number",begin:C,relevance:0},ie={className:"number",begin:w+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},ae={begin:/(?=\/[^/\n]*\/)/,contains:[{className:"regexp",begin:/\//,end:/\/[gimuy]*/,illegal:/\n/,contains:[j,{begin:/\[/,end:/\]/,relevance:0,contains:[j]}]}]},ce={className:"title",begin:u,relevance:0},le={className:"title",begin:_,relevance:0},pe={begin:"\\.\\s*"+_,relevance:0};var de=Object.freeze({__proto__:null,MATCH_NOTHING_RE:/\b\B/,IDENT_RE:u,UNDERSCORE_IDENT_RE:_,NUMBER_RE:w,C_NUMBER_RE:x,BINARY_NUMBER_RE:C,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(s={})=>{const o=/^#![ ]*\//;return s.binary&&(s.begin=function concat(...s){return s.map((s=>source(s))).join("")}(o,/.*\b/,s.binary,/\b.*/)),inherit({className:"meta",begin:o,end:/$/,relevance:0,"on:begin":(s,o)=>{0!==s.index&&o.ignoreMatch()}},s)},BACKSLASH_ESCAPE:j,APOS_STRING_MODE:L,QUOTE_STRING_MODE:B,PHRASAL_WORDS_MODE:$,COMMENT,C_LINE_COMMENT_MODE:U,C_BLOCK_COMMENT_MODE:V,HASH_COMMENT_MODE:z,NUMBER_MODE:Y,C_NUMBER_MODE:Z,BINARY_NUMBER_MODE:ee,CSS_NUMBER_MODE:ie,REGEXP_MODE:ae,TITLE_MODE:ce,UNDERSCORE_TITLE_MODE:le,METHOD_GUARD:pe,END_SAME_AS_BEGIN:function(s){return Object.assign(s,{"on:begin":(s,o)=>{o.data._beginMatch=s[1]},"on:end":(s,o)=>{o.data._beginMatch!==s[1]&&o.ignoreMatch()}})}});function skipIfhasPrecedingDot(s,o){"."===s.input[s.index-1]&&o.ignoreMatch()}function beginKeywords(s,o){o&&s.beginKeywords&&(s.begin="\\b("+s.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",s.__beforeBegin=skipIfhasPrecedingDot,s.keywords=s.keywords||s.beginKeywords,delete s.beginKeywords,void 0===s.relevance&&(s.relevance=0))}function compileIllegal(s,o){Array.isArray(s.illegal)&&(s.illegal=function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}(...s.illegal))}function compileMatch(s,o){if(s.match){if(s.begin||s.end)throw new Error("begin & end are not supported with match");s.begin=s.match,delete s.match}}function compileRelevance(s,o){void 0===s.relevance&&(s.relevance=1)}const fe=["of","and","for","in","not","or","if","then","parent","list","value"];function compileKeywords(s,o,i="keyword"){const a={};return"string"==typeof s?compileList(i,s.split(" ")):Array.isArray(s)?compileList(i,s):Object.keys(s).forEach((function(i){Object.assign(a,compileKeywords(s[i],o,i))})),a;function compileList(s,i){o&&(i=i.map((s=>s.toLowerCase()))),i.forEach((function(o){const i=o.split("|");a[i[0]]=[s,scoreForKeyword(i[0],i[1])]}))}}function scoreForKeyword(s,o){return o?Number(o):function commonKeyword(s){return fe.includes(s.toLowerCase())}(s)?0:1}function compileLanguage(s,{plugins:o}){function langRe(o,i){return new RegExp(source(o),"m"+(s.case_insensitive?"i":"")+(i?"g":""))}class MultiRegex{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(s,o){o.position=this.position++,this.matchIndexes[this.matchAt]=o,this.regexes.push([o,s]),this.matchAt+=function countMatchGroups(s){return new RegExp(s.toString()+"|").exec("").length-1}(s)+1}compile(){0===this.regexes.length&&(this.exec=()=>null);const s=this.regexes.map((s=>s[1]));this.matcherRe=langRe(function join(s,o="|"){let i=0;return s.map((s=>{i+=1;const o=i;let u=source(s),_="";for(;u.length>0;){const s=a.exec(u);if(!s){_+=u;break}_+=u.substring(0,s.index),u=u.substring(s.index+s[0].length),"\\"===s[0][0]&&s[1]?_+="\\"+String(Number(s[1])+o):(_+=s[0],"("===s[0]&&i++)}return _})).map((s=>`(${s})`)).join(o)}(s),!0),this.lastIndex=0}exec(s){this.matcherRe.lastIndex=this.lastIndex;const o=this.matcherRe.exec(s);if(!o)return null;const i=o.findIndex(((s,o)=>o>0&&void 0!==s)),a=this.matchIndexes[i];return o.splice(0,i),Object.assign(o,a)}}class ResumableMultiRegex{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(s){if(this.multiRegexes[s])return this.multiRegexes[s];const o=new MultiRegex;return this.rules.slice(s).forEach((([s,i])=>o.addRule(s,i))),o.compile(),this.multiRegexes[s]=o,o}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0}addRule(s,o){this.rules.push([s,o]),"begin"===o.type&&this.count++}exec(s){const o=this.getMatcher(this.regexIndex);o.lastIndex=this.lastIndex;let i=o.exec(s);if(this.resumingScanAtSamePosition())if(i&&i.index===this.lastIndex);else{const o=this.getMatcher(0);o.lastIndex=this.lastIndex+1,i=o.exec(s)}return i&&(this.regexIndex+=i.position+1,this.regexIndex===this.count&&this.considerAll()),i}}if(s.compilerExtensions||(s.compilerExtensions=[]),s.contains&&s.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return s.classNameAliases=inherit(s.classNameAliases||{}),function compileMode(o,i){const a=o;if(o.isCompiled)return a;[compileMatch].forEach((s=>s(o,i))),s.compilerExtensions.forEach((s=>s(o,i))),o.__beforeBegin=null,[beginKeywords,compileIllegal,compileRelevance].forEach((s=>s(o,i))),o.isCompiled=!0;let u=null;if("object"==typeof o.keywords&&(u=o.keywords.$pattern,delete o.keywords.$pattern),o.keywords&&(o.keywords=compileKeywords(o.keywords,s.case_insensitive)),o.lexemes&&u)throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");return u=u||o.lexemes||/\w+/,a.keywordPatternRe=langRe(u,!0),i&&(o.begin||(o.begin=/\B|\b/),a.beginRe=langRe(o.begin),o.endSameAsBegin&&(o.end=o.begin),o.end||o.endsWithParent||(o.end=/\B|\b/),o.end&&(a.endRe=langRe(o.end)),a.terminatorEnd=source(o.end)||"",o.endsWithParent&&i.terminatorEnd&&(a.terminatorEnd+=(o.end?"|":"")+i.terminatorEnd)),o.illegal&&(a.illegalRe=langRe(o.illegal)),o.contains||(o.contains=[]),o.contains=[].concat(...o.contains.map((function(s){return function expandOrCloneMode(s){s.variants&&!s.cachedVariants&&(s.cachedVariants=s.variants.map((function(o){return inherit(s,{variants:null},o)})));if(s.cachedVariants)return s.cachedVariants;if(dependencyOnParent(s))return inherit(s,{starts:s.starts?inherit(s.starts):null});if(Object.isFrozen(s))return inherit(s);return s}("self"===s?o:s)}))),o.contains.forEach((function(s){compileMode(s,a)})),o.starts&&compileMode(o.starts,i),a.matcher=function buildModeRegex(s){const o=new ResumableMultiRegex;return s.contains.forEach((s=>o.addRule(s.begin,{rule:s,type:"begin"}))),s.terminatorEnd&&o.addRule(s.terminatorEnd,{type:"end"}),s.illegal&&o.addRule(s.illegal,{type:"illegal"}),o}(a),a}(s)}function dependencyOnParent(s){return!!s&&(s.endsWithParent||dependencyOnParent(s.starts))}function BuildVuePlugin(s){const o={props:["language","code","autodetect"],data:function(){return{detectedLanguage:"",unknownLanguage:!1}},computed:{className(){return this.unknownLanguage?"":"hljs "+this.detectedLanguage},highlighted(){if(!this.autoDetect&&!s.getLanguage(this.language))return console.warn(`The language "${this.language}" you specified could not be found.`),this.unknownLanguage=!0,escapeHTML(this.code);let o={};return this.autoDetect?(o=s.highlightAuto(this.code),this.detectedLanguage=o.language):(o=s.highlight(this.language,this.code,this.ignoreIllegals),this.detectedLanguage=this.language),o.value},autoDetect(){return!this.language||function hasValueOrEmptyAttribute(s){return Boolean(s||""===s)}(this.autodetect)},ignoreIllegals:()=>!0},render(s){return s("pre",{},[s("code",{class:this.className,domProps:{innerHTML:this.highlighted}})])}};return{Component:o,VuePlugin:{install(s){s.component("highlightjs",o)}}}}const ye={"after:highlightElement":({el:s,result:o,text:i})=>{const a=nodeStream(s);if(!a.length)return;const u=document.createElement("div");u.innerHTML=o.value,o.value=function mergeStreams(s,o,i){let a=0,u="";const _=[];function selectStream(){return s.length&&o.length?s[0].offset!==o[0].offset?s[0].offset"}function close(s){u+=""}function render(s){("start"===s.event?open:close)(s.node)}for(;s.length||o.length;){let o=selectStream();if(u+=escapeHTML(i.substring(a,o[0].offset)),a=o[0].offset,o===s){_.reverse().forEach(close);do{render(o.splice(0,1)[0]),o=selectStream()}while(o===s&&o.length&&o[0].offset===a);_.reverse().forEach(open)}else"start"===o[0].event?_.push(o[0].node):_.pop(),render(o.splice(0,1)[0])}return u+escapeHTML(i.substr(a))}(a,nodeStream(u),i)}};function tag(s){return s.nodeName.toLowerCase()}function nodeStream(s){const o=[];return function _nodeStream(s,i){for(let a=s.firstChild;a;a=a.nextSibling)3===a.nodeType?i+=a.nodeValue.length:1===a.nodeType&&(o.push({event:"start",offset:i,node:a}),i=_nodeStream(a,i),tag(a).match(/br|hr|img|input/)||o.push({event:"stop",offset:i,node:a}));return i}(s,0),o}const be={},error=s=>{console.error(s)},warn=(s,...o)=>{console.log(`WARN: ${s}`,...o)},deprecated=(s,o)=>{be[`${s}/${o}`]||(console.log(`Deprecated as of ${s}. ${o}`),be[`${s}/${o}`]=!0)},Se=escapeHTML,_e=inherit,we=Symbol("nomatch");var xe=function(s){const i=Object.create(null),a=Object.create(null),u=[];let _=!0;const w=/(^(<[^>]+>|\t|)+|\n)/gm,x="Could not find the language '{}', did you forget to load/include a language module?",C={disableAutodetect:!0,name:"Plain text",contains:[]};let j={noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:null,__emitter:TokenTreeEmitter};function shouldNotHighlight(s){return j.noHighlightRe.test(s)}function highlight(s,o,i,a){let u="",_="";"object"==typeof o?(u=s,i=o.ignoreIllegals,_=o.language,a=void 0):(deprecated("10.7.0","highlight(lang, code, ...args) has been deprecated."),deprecated("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),_=s,u=o);const w={code:u,language:_};fire("before:highlight",w);const x=w.result?w.result:_highlight(w.language,w.code,i,a);return x.code=w.code,fire("after:highlight",x),x}function _highlight(s,o,a,w){function keywordData(s,o){const i=L.case_insensitive?o[0].toLowerCase():o[0];return Object.prototype.hasOwnProperty.call(s.keywords,i)&&s.keywords[i]}function processBuffer(){null!=U.subLanguage?function processSubLanguage(){if(""===Y)return;let s=null;if("string"==typeof U.subLanguage){if(!i[U.subLanguage])return void z.addText(Y);s=_highlight(U.subLanguage,Y,!0,V[U.subLanguage]),V[U.subLanguage]=s.top}else s=highlightAuto(Y,U.subLanguage.length?U.subLanguage:null);U.relevance>0&&(Z+=s.relevance),z.addSublanguage(s.emitter,s.language)}():function processKeywords(){if(!U.keywords)return void z.addText(Y);let s=0;U.keywordPatternRe.lastIndex=0;let o=U.keywordPatternRe.exec(Y),i="";for(;o;){i+=Y.substring(s,o.index);const a=keywordData(U,o);if(a){const[s,u]=a;if(z.addText(i),i="",Z+=u,s.startsWith("_"))i+=o[0];else{const i=L.classNameAliases[s]||s;z.addKeyword(o[0],i)}}else i+=o[0];s=U.keywordPatternRe.lastIndex,o=U.keywordPatternRe.exec(Y)}i+=Y.substr(s),z.addText(i)}(),Y=""}function startNewMode(s){return s.className&&z.openNode(L.classNameAliases[s.className]||s.className),U=Object.create(s,{parent:{value:U}}),U}function endOfMode(s,o,i){let a=function startsWith(s,o){const i=s&&s.exec(o);return i&&0===i.index}(s.endRe,i);if(a){if(s["on:end"]){const i=new Response(s);s["on:end"](o,i),i.isMatchIgnored&&(a=!1)}if(a){for(;s.endsParent&&s.parent;)s=s.parent;return s}}if(s.endsWithParent)return endOfMode(s.parent,o,i)}function doIgnore(s){return 0===U.matcher.regexIndex?(Y+=s[0],1):(ae=!0,0)}function doBeginMatch(s){const o=s[0],i=s.rule,a=new Response(i),u=[i.__beforeBegin,i["on:begin"]];for(const i of u)if(i&&(i(s,a),a.isMatchIgnored))return doIgnore(o);return i&&i.endSameAsBegin&&(i.endRe=function escape(s){return new RegExp(s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"m")}(o)),i.skip?Y+=o:(i.excludeBegin&&(Y+=o),processBuffer(),i.returnBegin||i.excludeBegin||(Y=o)),startNewMode(i),i.returnBegin?0:o.length}function doEndMatch(s){const i=s[0],a=o.substr(s.index),u=endOfMode(U,s,a);if(!u)return we;const _=U;_.skip?Y+=i:(_.returnEnd||_.excludeEnd||(Y+=i),processBuffer(),_.excludeEnd&&(Y=i));do{U.className&&z.closeNode(),U.skip||U.subLanguage||(Z+=U.relevance),U=U.parent}while(U!==u.parent);return u.starts&&(u.endSameAsBegin&&(u.starts.endRe=u.endRe),startNewMode(u.starts)),_.returnEnd?0:i.length}let C={};function processLexeme(i,u){const w=u&&u[0];if(Y+=i,null==w)return processBuffer(),0;if("begin"===C.type&&"end"===u.type&&C.index===u.index&&""===w){if(Y+=o.slice(u.index,u.index+1),!_){const o=new Error("0 width match regex");throw o.languageName=s,o.badRule=C.rule,o}return 1}if(C=u,"begin"===u.type)return doBeginMatch(u);if("illegal"===u.type&&!a){const s=new Error('Illegal lexeme "'+w+'" for mode "'+(U.className||"")+'"');throw s.mode=U,s}if("end"===u.type){const s=doEndMatch(u);if(s!==we)return s}if("illegal"===u.type&&""===w)return 1;if(ie>1e5&&ie>3*u.index){throw new Error("potential infinite loop, way more iterations than matches")}return Y+=w,w.length}const L=getLanguage(s);if(!L)throw error(x.replace("{}",s)),new Error('Unknown language: "'+s+'"');const B=compileLanguage(L,{plugins:u});let $="",U=w||B;const V={},z=new j.__emitter(j);!function processContinuations(){const s=[];for(let o=U;o!==L;o=o.parent)o.className&&s.unshift(o.className);s.forEach((s=>z.openNode(s)))}();let Y="",Z=0,ee=0,ie=0,ae=!1;try{for(U.matcher.considerAll();;){ie++,ae?ae=!1:U.matcher.considerAll(),U.matcher.lastIndex=ee;const s=U.matcher.exec(o);if(!s)break;const i=processLexeme(o.substring(ee,s.index),s);ee=s.index+i}return processLexeme(o.substr(ee)),z.closeAllNodes(),z.finalize(),$=z.toHTML(),{relevance:Math.floor(Z),value:$,language:s,illegal:!1,emitter:z,top:U}}catch(i){if(i.message&&i.message.includes("Illegal"))return{illegal:!0,illegalBy:{msg:i.message,context:o.slice(ee-100,ee+100),mode:i.mode},sofar:$,relevance:0,value:Se(o),emitter:z};if(_)return{illegal:!1,relevance:0,value:Se(o),emitter:z,language:s,top:U,errorRaised:i};throw i}}function highlightAuto(s,o){o=o||j.languages||Object.keys(i);const a=function justTextHighlightResult(s){const o={relevance:0,emitter:new j.__emitter(j),value:Se(s),illegal:!1,top:C};return o.emitter.addText(s),o}(s),u=o.filter(getLanguage).filter(autoDetection).map((o=>_highlight(o,s,!1)));u.unshift(a);const _=u.sort(((s,o)=>{if(s.relevance!==o.relevance)return o.relevance-s.relevance;if(s.language&&o.language){if(getLanguage(s.language).supersetOf===o.language)return 1;if(getLanguage(o.language).supersetOf===s.language)return-1}return 0})),[w,x]=_,L=w;return L.second_best=x,L}const L={"before:highlightElement":({el:s})=>{j.useBR&&(s.innerHTML=s.innerHTML.replace(/\n/g,"").replace(//g,"\n"))},"after:highlightElement":({result:s})=>{j.useBR&&(s.value=s.value.replace(/\n/g,"
"))}},B=/^(<[^>]+>|\t)+/gm,$={"after:highlightElement":({result:s})=>{j.tabReplace&&(s.value=s.value.replace(B,(s=>s.replace(/\t/g,j.tabReplace))))}};function highlightElement(s){let o=null;const i=function blockLanguage(s){let o=s.className+" ";o+=s.parentNode?s.parentNode.className:"";const i=j.languageDetectRe.exec(o);if(i){const o=getLanguage(i[1]);return o||(warn(x.replace("{}",i[1])),warn("Falling back to no-highlight mode for this block.",s)),o?i[1]:"no-highlight"}return o.split(/\s+/).find((s=>shouldNotHighlight(s)||getLanguage(s)))}(s);if(shouldNotHighlight(i))return;fire("before:highlightElement",{el:s,language:i}),o=s;const u=o.textContent,_=i?highlight(u,{language:i,ignoreIllegals:!0}):highlightAuto(u);fire("after:highlightElement",{el:s,result:_,text:u}),s.innerHTML=_.value,function updateClassName(s,o,i){const u=o?a[o]:i;s.classList.add("hljs"),u&&s.classList.add(u)}(s,i,_.language),s.result={language:_.language,re:_.relevance,relavance:_.relevance},_.second_best&&(s.second_best={language:_.second_best.language,re:_.second_best.relevance,relavance:_.second_best.relevance})}const initHighlighting=()=>{if(initHighlighting.called)return;initHighlighting.called=!0,deprecated("10.6.0","initHighlighting() is deprecated. Use highlightAll() instead.");document.querySelectorAll("pre code").forEach(highlightElement)};let U=!1;function highlightAll(){if("loading"===document.readyState)return void(U=!0);document.querySelectorAll("pre code").forEach(highlightElement)}function getLanguage(s){return s=(s||"").toLowerCase(),i[s]||i[a[s]]}function registerAliases(s,{languageName:o}){"string"==typeof s&&(s=[s]),s.forEach((s=>{a[s.toLowerCase()]=o}))}function autoDetection(s){const o=getLanguage(s);return o&&!o.disableAutodetect}function fire(s,o){const i=s;u.forEach((function(s){s[i]&&s[i](o)}))}"undefined"!=typeof window&&window.addEventListener&&window.addEventListener("DOMContentLoaded",(function boot(){U&&highlightAll()}),!1),Object.assign(s,{highlight,highlightAuto,highlightAll,fixMarkup:function deprecateFixMarkup(s){return deprecated("10.2.0","fixMarkup will be removed entirely in v11.0"),deprecated("10.2.0","Please see https://github.com/highlightjs/highlight.js/issues/2534"),function fixMarkup(s){return j.tabReplace||j.useBR?s.replace(w,(s=>"\n"===s?j.useBR?"
":s:j.tabReplace?s.replace(/\t/g,j.tabReplace):s)):s}(s)},highlightElement,highlightBlock:function deprecateHighlightBlock(s){return deprecated("10.7.0","highlightBlock will be removed entirely in v12.0"),deprecated("10.7.0","Please use highlightElement now."),highlightElement(s)},configure:function configure(s){s.useBR&&(deprecated("10.3.0","'useBR' will be removed entirely in v11.0"),deprecated("10.3.0","Please see https://github.com/highlightjs/highlight.js/issues/2559")),j=_e(j,s)},initHighlighting,initHighlightingOnLoad:function initHighlightingOnLoad(){deprecated("10.6.0","initHighlightingOnLoad() is deprecated. Use highlightAll() instead."),U=!0},registerLanguage:function registerLanguage(o,a){let u=null;try{u=a(s)}catch(s){if(error("Language definition for '{}' could not be registered.".replace("{}",o)),!_)throw s;error(s),u=C}u.name||(u.name=o),i[o]=u,u.rawDefinition=a.bind(null,s),u.aliases&®isterAliases(u.aliases,{languageName:o})},unregisterLanguage:function unregisterLanguage(s){delete i[s];for(const o of Object.keys(a))a[o]===s&&delete a[o]},listLanguages:function listLanguages(){return Object.keys(i)},getLanguage,registerAliases,requireLanguage:function requireLanguage(s){deprecated("10.4.0","requireLanguage will be removed entirely in v11."),deprecated("10.4.0","Please see https://github.com/highlightjs/highlight.js/pull/2844");const o=getLanguage(s);if(o)return o;throw new Error("The '{}' language is required, but not loaded.".replace("{}",s))},autoDetection,inherit:_e,addPlugin:function addPlugin(s){!function upgradePluginAPI(s){s["before:highlightBlock"]&&!s["before:highlightElement"]&&(s["before:highlightElement"]=o=>{s["before:highlightBlock"](Object.assign({block:o.el},o))}),s["after:highlightBlock"]&&!s["after:highlightElement"]&&(s["after:highlightElement"]=o=>{s["after:highlightBlock"](Object.assign({block:o.el},o))})}(s),u.push(s)},vuePlugin:BuildVuePlugin(s).VuePlugin}),s.debugMode=function(){_=!1},s.safeMode=function(){_=!0},s.versionString="10.7.3";for(const s in de)"object"==typeof de[s]&&o(de[s]);return Object.assign(s,de),s.addPlugin(L),s.addPlugin(ye),s.addPlugin($),s}({});s.exports=xe},35344(s){function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function bash(s){const o={},i={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[o]}]};Object.assign(o,{className:"variable",variants:[{begin:concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},i]});const a={className:"subst",begin:/\$\(/,end:/\)/,contains:[s.BACKSLASH_ESCAPE]},u={begin:/<<-?\s*(?=\w+)/,starts:{contains:[s.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},_={className:"string",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE,o,a]};a.contains.push(_);const w={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},s.NUMBER_MODE,o]},x=s.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),C={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[s.inherit(s.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[x,s.SHEBANG(),C,w,s.HASH_COMMENT_MODE,u,_,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},o]}}},73402(s){function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function http(s){const o="HTTP/(2|1\\.[01])",i={className:"attribute",begin:concat("^",/[A-Za-z][A-Za-z0-9-]*/,"(?=\\:\\s)"),starts:{contains:[{className:"punctuation",begin:/: /,relevance:0,starts:{end:"$",relevance:0}}]}},a=[i,{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}];return{name:"HTTP",aliases:["https"],illegal:/\S/,contains:[{begin:"^(?="+o+" \\d{3})",end:/$/,contains:[{className:"meta",begin:o},{className:"number",begin:"\\b\\d{3}\\b"}],starts:{end:/\b\B/,illegal:/\S/,contains:a}},{begin:"(?=^[A-Z]+ (.*?) "+o+"$)",end:/$/,contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{className:"meta",begin:o},{className:"keyword",begin:"[A-Z]+"}],starts:{end:/\b\B/,illegal:/\S/,contains:a}},s.inherit(i,{relevance:0})]}}},95089(s){const o="[A-Za-z$_][0-9A-Za-z$_]*",i=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],a=["true","false","null","undefined","NaN","Infinity"],u=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer","BigInt64Array","BigUint64Array","BigInt"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>function source(s){return s?"string"==typeof s?s:s.source:null}(s))).join("")}s.exports=function javascript(s){const _=o,w="<>",x="",C={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(s,o)=>{const i=s[0].length+s.index,a=s.input[i];"<"!==a?">"===a&&(((s,{after:o})=>{const i="",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:s.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:j,contains:ce}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:w,end:x},{begin:C.begin,"on:begin":C.isTrulyOpeningTag,end:C.end}],subLanguage:"xml",contains:[{begin:C.begin,end:C.end,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:j,contains:["self",s.inherit(s.TITLE_MODE,{begin:_}),le],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:s.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[le,s.inherit(s.TITLE_MODE,{begin:_})]},{variants:[{begin:"\\."+_},{begin:"\\$"+_}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},s.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[s.inherit(s.TITLE_MODE,{begin:_}),"self",le]},{begin:"(get|set)\\s+(?="+_+"\\()",end:/\{/,keywords:"get set",contains:[s.inherit(s.TITLE_MODE,{begin:_}),{begin:/\(\)/},le]},{begin:/\$[(.]/}]}}},65772(s){s.exports=function json(s){const o={literal:"true false null"},i=[s.C_LINE_COMMENT_MODE,s.C_BLOCK_COMMENT_MODE],a=[s.QUOTE_STRING_MODE,s.C_NUMBER_MODE],u={end:",",endsWithParent:!0,excludeEnd:!0,contains:a,keywords:o},_={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[s.BACKSLASH_ESCAPE],illegal:"\\n"},s.inherit(u,{begin:/:/})].concat(i),illegal:"\\S"},w={begin:"\\[",end:"\\]",contains:[s.inherit(u)],illegal:"\\S"};return a.push(_,w),i.forEach((function(s){a.push(s)})),{name:"JSON",contains:a,keywords:o,illegal:"\\S"}}},26571(s){s.exports=function powershell(s){const o={$pattern:/-?[A-z\.\-]+\b/,keyword:"if else foreach return do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch hidden static parameter",built_in:"ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write"},i={begin:"`[\\s\\S]",relevance:0},a={className:"variable",variants:[{begin:/\$\B/},{className:"keyword",begin:/\$this/},{begin:/\$[\w\d][\w\d_:]*/}]},u={className:"string",variants:[{begin:/"/,end:/"/},{begin:/@"/,end:/^"@/}],contains:[i,a,{className:"variable",begin:/\$[A-z]/,end:/[^A-z]/}]},_={className:"string",variants:[{begin:/'/,end:/'/},{begin:/@'/,end:/^'@/}]},w=s.inherit(s.COMMENT(null,null),{variants:[{begin:/#/,end:/$/},{begin:/<#/,end:/#>/}],contains:[{className:"doctag",variants:[{begin:/\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/},{begin:/\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/}]}]}),x={className:"built_in",variants:[{begin:"(".concat("Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|Unprotect|Use|ForEach|Sort|Tee|Where",")+(-)[\\w\\d]+")}]},C={className:"class",beginKeywords:"class enum",end:/\s*[{]/,excludeEnd:!0,relevance:0,contains:[s.TITLE_MODE]},j={className:"function",begin:/function\s+/,end:/\s*\{|$/,excludeEnd:!0,returnBegin:!0,relevance:0,contains:[{begin:"function",relevance:0,className:"keyword"},{className:"title",begin:/\w[\w\d]*((-)[\w\d]+)*/,relevance:0},{begin:/\(/,end:/\)/,className:"params",relevance:0,contains:[a]}]},L={begin:/using\s/,end:/$/,returnBegin:!0,contains:[u,_,{className:"keyword",begin:/(using|assembly|command|module|namespace|type)/}]},B={variants:[{className:"operator",begin:"(".concat("-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|-split|-wildcard|-xor",")\\b")},{className:"literal",begin:/(-)[\w\d]+/,relevance:0}]},$={className:"function",begin:/\[.*\]\s*[\w]+[ ]??\(/,end:/$/,returnBegin:!0,relevance:0,contains:[{className:"keyword",begin:"(".concat(o.keyword.toString().replace(/\s/g,"|"),")\\b"),endsParent:!0,relevance:0},s.inherit(s.TITLE_MODE,{endsParent:!0})]},U=[$,w,i,s.NUMBER_MODE,u,_,x,a,{className:"literal",begin:/\$(null|true|false)\b/},{className:"selector-tag",begin:/@\B/,relevance:0}],V={begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[].concat("self",U,{begin:"("+["string","char","byte","int","long","bool","decimal","single","double","DateTime","xml","array","hashtable","void"].join("|")+")",className:"built_in",relevance:0},{className:"type",begin:/[\.\w\d]+/,relevance:0})};return $.contains.unshift(V),{name:"PowerShell",aliases:["ps","ps1"],case_insensitive:!0,keywords:o,contains:U.concat(C,j,L,B,V)}}},17285(s){function source(s){return s?"string"==typeof s?s:s.source:null}function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>source(s))).join("")}function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}s.exports=function xml(s){const o=concat(/[A-Z_]/,function optional(s){return concat("(",s,")?")}(/[A-Z0-9_.-]*:/),/[A-Z0-9_.-]*/),i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},u=s.inherit(a,{begin:/\(/,end:/\)/}),_=s.inherit(s.APOS_STRING_MODE,{className:"meta-string"}),w=s.inherit(s.QUOTE_STRING_MODE,{className:"meta-string"}),x={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[a,w,_,u,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[a,u,w,_]}]}]},s.COMMENT(//,{relevance:10}),{begin://,relevance:10},i,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[x],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[x],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:o,relevance:0,starts:x}]},{className:"tag",begin:concat(/<\//,lookahead(concat(o,/>/))),contains:[{className:"name",begin:o,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17533(s){s.exports=function yaml(s){var o="true false yes no null",i="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[s.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},u=s.inherit(a,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),_={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},w={end:",",endsWithParent:!0,excludeEnd:!0,keywords:o,relevance:0},x={begin:/\{/,end:/\}/,contains:[w],illegal:"\\n",relevance:0},C={begin:"\\[",end:"\\]",contains:[w],illegal:"\\n",relevance:0},j=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+i},{className:"type",begin:"!<"+i+">"},{className:"type",begin:"!"+i},{className:"type",begin:"!!"+i},{className:"meta",begin:"&"+s.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+s.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},s.HASH_COMMENT_MODE,{beginKeywords:o,keywords:{literal:o}},_,{className:"number",begin:s.C_NUMBER_RE+"\\b",relevance:0},x,C,a],L=[...j];return L.pop(),L.push(u),w.contains=L,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:j}}},251(s,o){o.read=function(s,o,i,a,u){var _,w,x=8*u-a-1,C=(1<>1,L=-7,B=i?u-1:0,$=i?-1:1,U=s[o+B];for(B+=$,_=U&(1<<-L)-1,U>>=-L,L+=x;L>0;_=256*_+s[o+B],B+=$,L-=8);for(w=_&(1<<-L)-1,_>>=-L,L+=a;L>0;w=256*w+s[o+B],B+=$,L-=8);if(0===_)_=1-j;else{if(_===C)return w?NaN:1/0*(U?-1:1);w+=Math.pow(2,a),_-=j}return(U?-1:1)*w*Math.pow(2,_-a)},o.write=function(s,o,i,a,u,_){var w,x,C,j=8*_-u-1,L=(1<>1,$=23===u?Math.pow(2,-24)-Math.pow(2,-77):0,U=a?0:_-1,V=a?1:-1,z=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(x=isNaN(o)?1:0,w=L):(w=Math.floor(Math.log(o)/Math.LN2),o*(C=Math.pow(2,-w))<1&&(w--,C*=2),(o+=w+B>=1?$/C:$*Math.pow(2,1-B))*C>=2&&(w++,C/=2),w+B>=L?(x=0,w=L):w+B>=1?(x=(o*C-1)*Math.pow(2,u),w+=B):(x=o*Math.pow(2,B-1)*Math.pow(2,u),w=0));u>=8;s[i+U]=255&x,U+=V,x/=256,u-=8);for(w=w<0;s[i+U]=255&w,U+=V,w/=256,j-=8);s[i+U-V]|=128*z}},9404(s){s.exports=function(){"use strict";var s=Array.prototype.slice;function createClass(s,o){o&&(s.prototype=Object.create(o.prototype)),s.prototype.constructor=s}function Iterable(s){return isIterable(s)?s:Seq(s)}function KeyedIterable(s){return isKeyed(s)?s:KeyedSeq(s)}function IndexedIterable(s){return isIndexed(s)?s:IndexedSeq(s)}function SetIterable(s){return isIterable(s)&&!isAssociative(s)?s:SetSeq(s)}function isIterable(s){return!(!s||!s[o])}function isKeyed(s){return!(!s||!s[i])}function isIndexed(s){return!(!s||!s[a])}function isAssociative(s){return isKeyed(s)||isIndexed(s)}function isOrdered(s){return!(!s||!s[u])}createClass(KeyedIterable,Iterable),createClass(IndexedIterable,Iterable),createClass(SetIterable,Iterable),Iterable.isIterable=isIterable,Iterable.isKeyed=isKeyed,Iterable.isIndexed=isIndexed,Iterable.isAssociative=isAssociative,Iterable.isOrdered=isOrdered,Iterable.Keyed=KeyedIterable,Iterable.Indexed=IndexedIterable,Iterable.Set=SetIterable;var o="@@__IMMUTABLE_ITERABLE__@@",i="@@__IMMUTABLE_KEYED__@@",a="@@__IMMUTABLE_INDEXED__@@",u="@@__IMMUTABLE_ORDERED__@@",_="delete",w=5,x=1<>>0;if(""+i!==o||4294967295===i)return NaN;o=i}return o<0?ensureSize(s)+o:o}function returnTrue(){return!0}function wholeSlice(s,o,i){return(0===s||void 0!==i&&s<=-i)&&(void 0===o||void 0!==i&&o>=i)}function resolveBegin(s,o){return resolveIndex(s,o,0)}function resolveEnd(s,o){return resolveIndex(s,o,o)}function resolveIndex(s,o,i){return void 0===s?i:s<0?Math.max(0,o+s):void 0===o?s:Math.min(o,s)}var $=0,U=1,V=2,z="function"==typeof Symbol&&Symbol.iterator,Y="@@iterator",Z=z||Y;function Iterator(s){this.next=s}function iteratorValue(s,o,i,a){var u=0===s?o:1===s?i:[o,i];return a?a.value=u:a={value:u,done:!1},a}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(s){return!!getIteratorFn(s)}function isIterator(s){return s&&"function"==typeof s.next}function getIterator(s){var o=getIteratorFn(s);return o&&o.call(s)}function getIteratorFn(s){var o=s&&(z&&s[z]||s[Y]);if("function"==typeof o)return o}function isArrayLike(s){return s&&"number"==typeof s.length}function Seq(s){return null==s?emptySequence():isIterable(s)?s.toSeq():seqFromValue(s)}function KeyedSeq(s){return null==s?emptySequence().toKeyedSeq():isIterable(s)?isKeyed(s)?s.toSeq():s.fromEntrySeq():keyedSeqFromValue(s)}function IndexedSeq(s){return null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s.toIndexedSeq():indexedSeqFromValue(s)}function SetSeq(s){return(null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s:indexedSeqFromValue(s)).toSetSeq()}Iterator.prototype.toString=function(){return"[Iterator]"},Iterator.KEYS=$,Iterator.VALUES=U,Iterator.ENTRIES=V,Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()},Iterator.prototype[Z]=function(){return this},createClass(Seq,Iterable),Seq.of=function(){return Seq(arguments)},Seq.prototype.toSeq=function(){return this},Seq.prototype.toString=function(){return this.__toString("Seq {","}")},Seq.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},Seq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!0)},Seq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!0)},createClass(KeyedSeq,Seq),KeyedSeq.prototype.toKeyedSeq=function(){return this},createClass(IndexedSeq,Seq),IndexedSeq.of=function(){return IndexedSeq(arguments)},IndexedSeq.prototype.toIndexedSeq=function(){return this},IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")},IndexedSeq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!1)},IndexedSeq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!1)},createClass(SetSeq,Seq),SetSeq.of=function(){return SetSeq(arguments)},SetSeq.prototype.toSetSeq=function(){return this},Seq.isSeq=isSeq,Seq.Keyed=KeyedSeq,Seq.Set=SetSeq,Seq.Indexed=IndexedSeq;var ee,ie,ae,ce="@@__IMMUTABLE_SEQ__@@";function ArraySeq(s){this._array=s,this.size=s.length}function ObjectSeq(s){var o=Object.keys(s);this._object=s,this._keys=o,this.size=o.length}function IterableSeq(s){this._iterable=s,this.size=s.length||s.size}function IteratorSeq(s){this._iterator=s,this._iteratorCache=[]}function isSeq(s){return!(!s||!s[ce])}function emptySequence(){return ee||(ee=new ArraySeq([]))}function keyedSeqFromValue(s){var o=Array.isArray(s)?new ArraySeq(s).fromEntrySeq():isIterator(s)?new IteratorSeq(s).fromEntrySeq():hasIterator(s)?new IterableSeq(s).fromEntrySeq():"object"==typeof s?new ObjectSeq(s):void 0;if(!o)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+s);return o}function indexedSeqFromValue(s){var o=maybeIndexedSeqFromValue(s);if(!o)throw new TypeError("Expected Array or iterable object of values: "+s);return o}function seqFromValue(s){var o=maybeIndexedSeqFromValue(s)||"object"==typeof s&&new ObjectSeq(s);if(!o)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+s);return o}function maybeIndexedSeqFromValue(s){return isArrayLike(s)?new ArraySeq(s):isIterator(s)?new IteratorSeq(s):hasIterator(s)?new IterableSeq(s):void 0}function seqIterate(s,o,i,a){var u=s._cache;if(u){for(var _=u.length-1,w=0;w<=_;w++){var x=u[i?_-w:w];if(!1===o(x[1],a?x[0]:w,s))return w+1}return w}return s.__iterateUncached(o,i)}function seqIterator(s,o,i,a){var u=s._cache;if(u){var _=u.length-1,w=0;return new Iterator((function(){var s=u[i?_-w:w];return w++>_?iteratorDone():iteratorValue(o,a?s[0]:w-1,s[1])}))}return s.__iteratorUncached(o,i)}function fromJS(s,o){return o?fromJSWith(o,s,"",{"":s}):fromJSDefault(s)}function fromJSWith(s,o,i,a){return Array.isArray(o)?s.call(a,i,IndexedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):isPlainObj(o)?s.call(a,i,KeyedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):o}function fromJSDefault(s){return Array.isArray(s)?IndexedSeq(s).map(fromJSDefault).toList():isPlainObj(s)?KeyedSeq(s).map(fromJSDefault).toMap():s}function isPlainObj(s){return s&&(s.constructor===Object||void 0===s.constructor)}function is(s,o){if(s===o||s!=s&&o!=o)return!0;if(!s||!o)return!1;if("function"==typeof s.valueOf&&"function"==typeof o.valueOf){if((s=s.valueOf())===(o=o.valueOf())||s!=s&&o!=o)return!0;if(!s||!o)return!1}return!("function"!=typeof s.equals||"function"!=typeof o.equals||!s.equals(o))}function deepEqual(s,o){if(s===o)return!0;if(!isIterable(o)||void 0!==s.size&&void 0!==o.size&&s.size!==o.size||void 0!==s.__hash&&void 0!==o.__hash&&s.__hash!==o.__hash||isKeyed(s)!==isKeyed(o)||isIndexed(s)!==isIndexed(o)||isOrdered(s)!==isOrdered(o))return!1;if(0===s.size&&0===o.size)return!0;var i=!isAssociative(s);if(isOrdered(s)){var a=s.entries();return o.every((function(s,o){var u=a.next().value;return u&&is(u[1],s)&&(i||is(u[0],o))}))&&a.next().done}var u=!1;if(void 0===s.size)if(void 0===o.size)"function"==typeof s.cacheResult&&s.cacheResult();else{u=!0;var _=s;s=o,o=_}var w=!0,x=o.__iterate((function(o,a){if(i?!s.has(o):u?!is(o,s.get(a,j)):!is(s.get(a,j),o))return w=!1,!1}));return w&&s.size===x}function Repeat(s,o){if(!(this instanceof Repeat))return new Repeat(s,o);if(this._value=s,this.size=void 0===o?1/0:Math.max(0,o),0===this.size){if(ie)return ie;ie=this}}function invariant(s,o){if(!s)throw new Error(o)}function Range(s,o,i){if(!(this instanceof Range))return new Range(s,o,i);if(invariant(0!==i,"Cannot step a Range by 0"),s=s||0,void 0===o&&(o=1/0),i=void 0===i?1:Math.abs(i),oa?iteratorDone():iteratorValue(s,u,i[o?a-u++:u++])}))},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(s,o){return void 0===o||this.has(s)?this._object[s]:o},ObjectSeq.prototype.has=function(s){return this._object.hasOwnProperty(s)},ObjectSeq.prototype.__iterate=function(s,o){for(var i=this._object,a=this._keys,u=a.length-1,_=0;_<=u;_++){var w=a[o?u-_:_];if(!1===s(i[w],w,this))return _+1}return _},ObjectSeq.prototype.__iterator=function(s,o){var i=this._object,a=this._keys,u=a.length-1,_=0;return new Iterator((function(){var w=a[o?u-_:_];return _++>u?iteratorDone():iteratorValue(s,w,i[w])}))},ObjectSeq.prototype[u]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);var i=getIterator(this._iterable),a=0;if(isIterator(i))for(var u;!(u=i.next()).done&&!1!==s(u.value,a++,this););return a},IterableSeq.prototype.__iteratorUncached=function(s,o){if(o)return this.cacheResult().__iterator(s,o);var i=getIterator(this._iterable);if(!isIterator(i))return new Iterator(iteratorDone);var a=0;return new Iterator((function(){var o=i.next();return o.done?o:iteratorValue(s,a++,o.value)}))},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);for(var i,a=this._iterator,u=this._iteratorCache,_=0;_=a.length){var o=i.next();if(o.done)return o;a[u]=o.value}return iteratorValue(s,u,a[u++])}))},createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(s,o){return this.has(s)?this._value:o},Repeat.prototype.includes=function(s){return is(this._value,s)},Repeat.prototype.slice=function(s,o){var i=this.size;return wholeSlice(s,o,i)?this:new Repeat(this._value,resolveEnd(o,i)-resolveBegin(s,i))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(s){return is(this._value,s)?0:-1},Repeat.prototype.lastIndexOf=function(s){return is(this._value,s)?this.size:-1},Repeat.prototype.__iterate=function(s,o){for(var i=0;i=0&&o=0&&ii?iteratorDone():iteratorValue(s,_++,w)}))},Range.prototype.equals=function(s){return s instanceof Range?this._start===s._start&&this._end===s._end&&this._step===s._step:deepEqual(this,s)},createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var le="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function imul(s,o){var i=65535&(s|=0),a=65535&(o|=0);return i*a+((s>>>16)*a+i*(o>>>16)<<16>>>0)|0};function smi(s){return s>>>1&1073741824|3221225471&s}function hash(s){if(!1===s||null==s)return 0;if("function"==typeof s.valueOf&&(!1===(s=s.valueOf())||null==s))return 0;if(!0===s)return 1;var o=typeof s;if("number"===o){if(s!=s||s===1/0)return 0;var i=0|s;for(i!==s&&(i^=4294967295*s);s>4294967295;)i^=s/=4294967295;return smi(i)}if("string"===o)return s.length>_e?cachedHashString(s):hashString(s);if("function"==typeof s.hashCode)return s.hashCode();if("object"===o)return hashJSObj(s);if("function"==typeof s.toString)return hashString(s.toString());throw new Error("Value type "+o+" cannot be hashed.")}function cachedHashString(s){var o=Pe[s];return void 0===o&&(o=hashString(s),xe===we&&(xe=0,Pe={}),xe++,Pe[s]=o),o}function hashString(s){for(var o=0,i=0;i0)switch(s.nodeType){case 1:return s.uniqueID;case 9:return s.documentElement&&s.documentElement.uniqueID}}var fe,ye="function"==typeof WeakMap;ye&&(fe=new WeakMap);var be=0,Se="__immutablehash__";"function"==typeof Symbol&&(Se=Symbol(Se));var _e=16,we=255,xe=0,Pe={};function assertNotInfinite(s){invariant(s!==1/0,"Cannot perform this action with an infinite size.")}function Map(s){return null==s?emptyMap():isMap(s)&&!isOrdered(s)?s:emptyMap().withMutations((function(o){var i=KeyedIterable(s);assertNotInfinite(i.size),i.forEach((function(s,i){return o.set(i,s)}))}))}function isMap(s){return!(!s||!s[Re])}createClass(Map,KeyedCollection),Map.of=function(){var o=s.call(arguments,0);return emptyMap().withMutations((function(s){for(var i=0;i=o.length)throw new Error("Missing value for key: "+o[i]);s.set(o[i],o[i+1])}}))},Map.prototype.toString=function(){return this.__toString("Map {","}")},Map.prototype.get=function(s,o){return this._root?this._root.get(0,void 0,s,o):o},Map.prototype.set=function(s,o){return updateMap(this,s,o)},Map.prototype.setIn=function(s,o){return this.updateIn(s,j,(function(){return o}))},Map.prototype.remove=function(s){return updateMap(this,s,j)},Map.prototype.deleteIn=function(s){return this.updateIn(s,(function(){return j}))},Map.prototype.update=function(s,o,i){return 1===arguments.length?s(this):this.updateIn([s],o,i)},Map.prototype.updateIn=function(s,o,i){i||(i=o,o=void 0);var a=updateInDeepMap(this,forceIterator(s),o,i);return a===j?void 0:a},Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},Map.prototype.mergeWith=function(o){return mergeIntoMapWith(this,o,s.call(arguments,1))},Map.prototype.mergeIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.merge?s.merge.apply(s,i):i[i.length-1]}))},Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)},Map.prototype.mergeDeepWith=function(o){var i=s.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(o),i)},Map.prototype.mergeDeepIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.mergeDeep?s.mergeDeep.apply(s,i):i[i.length-1]}))},Map.prototype.sort=function(s){return OrderedMap(sortFactory(this,s))},Map.prototype.sortBy=function(s,o){return OrderedMap(sortFactory(this,o,s))},Map.prototype.withMutations=function(s){var o=this.asMutable();return s(o),o.wasAltered()?o.__ensureOwner(this.__ownerID):this},Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},Map.prototype.asImmutable=function(){return this.__ensureOwner()},Map.prototype.wasAltered=function(){return this.__altered},Map.prototype.__iterator=function(s,o){return new MapIterator(this,s,o)},Map.prototype.__iterate=function(s,o){var i=this,a=0;return this._root&&this._root.iterate((function(o){return a++,s(o[1],o[0],i)}),o),a},Map.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeMap(this.size,this._root,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Map.isMap=isMap;var Te,Re="@@__IMMUTABLE_MAP__@@",$e=Map.prototype;function ArrayMapNode(s,o){this.ownerID=s,this.entries=o}function BitmapIndexedNode(s,o,i){this.ownerID=s,this.bitmap=o,this.nodes=i}function HashArrayMapNode(s,o,i){this.ownerID=s,this.count=o,this.nodes=i}function HashCollisionNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entries=i}function ValueNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entry=i}function MapIterator(s,o,i){this._type=o,this._reverse=i,this._stack=s._root&&mapIteratorFrame(s._root)}function mapIteratorValue(s,o){return iteratorValue(s,o[0],o[1])}function mapIteratorFrame(s,o){return{node:s,index:0,__prev:o}}function makeMap(s,o,i,a){var u=Object.create($e);return u.size=s,u._root=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyMap(){return Te||(Te=makeMap(0))}function updateMap(s,o,i){var a,u;if(s._root){var _=MakeRef(L),w=MakeRef(B);if(a=updateNode(s._root,s.__ownerID,0,void 0,o,i,_,w),!w.value)return s;u=s.size+(_.value?i===j?-1:1:0)}else{if(i===j)return s;u=1,a=new ArrayMapNode(s.__ownerID,[[o,i]])}return s.__ownerID?(s.size=u,s._root=a,s.__hash=void 0,s.__altered=!0,s):a?makeMap(u,a):emptyMap()}function updateNode(s,o,i,a,u,_,w,x){return s?s.update(o,i,a,u,_,w,x):_===j?s:(SetRef(x),SetRef(w),new ValueNode(o,a,[u,_]))}function isLeafNode(s){return s.constructor===ValueNode||s.constructor===HashCollisionNode}function mergeIntoNode(s,o,i,a,u){if(s.keyHash===a)return new HashCollisionNode(o,a,[s.entry,u]);var _,x=(0===i?s.keyHash:s.keyHash>>>i)&C,j=(0===i?a:a>>>i)&C;return new BitmapIndexedNode(o,1<>>=1)w[C]=1&i?o[_++]:void 0;return w[a]=u,new HashArrayMapNode(s,_+1,w)}function mergeIntoMapWith(s,o,i){for(var a=[],u=0;u>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135,s+=s>>8,127&(s+=s>>16)}function setIn(s,o,i,a){var u=a?s:arrCopy(s);return u[o]=i,u}function spliceIn(s,o,i,a){var u=s.length+1;if(a&&o+1===u)return s[o]=i,s;for(var _=new Array(u),w=0,x=0;x=qe)return createNodes(s,C,a,u);var U=s&&s===this.ownerID,V=U?C:arrCopy(C);return $?x?L===B-1?V.pop():V[L]=V.pop():V[L]=[a,u]:V.push([a,u]),U?(this.entries=V,this):new ArrayMapNode(s,V)}},BitmapIndexedNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=1<<((0===s?o:o>>>s)&C),_=this.bitmap;return _&u?this.nodes[popCount(_&u-1)].get(s+w,o,i,a):a},BitmapIndexedNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=1<=ze)return expandNodes(s,z,$,L,Z);if(U&&!Z&&2===z.length&&isLeafNode(z[1^V]))return z[1^V];if(U&&Z&&1===z.length&&isLeafNode(Z))return Z;var ee=s&&s===this.ownerID,ie=U?Z?$:$^B:$|B,ae=U?Z?setIn(z,V,Z,ee):spliceOut(z,V,ee):spliceIn(z,V,Z,ee);return ee?(this.bitmap=ie,this.nodes=ae,this):new BitmapIndexedNode(s,ie,ae)},HashArrayMapNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=(0===s?o:o>>>s)&C,_=this.nodes[u];return _?_.get(s+w,o,i,a):a},HashArrayMapNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=u===j,$=this.nodes,U=$[L];if(B&&!U)return this;var V=updateNode(U,s,o+w,i,a,u,_,x);if(V===U)return this;var z=this.count;if(U){if(!V&&--z0&&a=0&&s>>o&C;if(a>=this.array.length)return new VNode([],s);var u,_=0===a;if(o>0){var x=this.array[a];if((u=x&&x.removeBefore(s,o-w,i))===x&&_)return this}if(_&&!u)return this;var j=editableVNode(this,s);if(!_)for(var L=0;L>>o&C;if(u>=this.array.length)return this;if(o>0){var _=this.array[u];if((a=_&&_.removeAfter(s,o-w,i))===_&&u===this.array.length-1)return this}var x=editableVNode(this,s);return x.array.splice(u+1),a&&(x.array[u]=a),x};var Xe,Qe,et={};function iterateList(s,o){var i=s._origin,a=s._capacity,u=getTailOffset(a),_=s._tail;return iterateNodeOrLeaf(s._root,s._level,0);function iterateNodeOrLeaf(s,o,i){return 0===o?iterateLeaf(s,i):iterateNode(s,o,i)}function iterateLeaf(s,w){var C=w===u?_&&_.array:s&&s.array,j=w>i?0:i-w,L=a-w;return L>x&&(L=x),function(){if(j===L)return et;var s=o?--L:j++;return C&&C[s]}}function iterateNode(s,u,_){var C,j=s&&s.array,L=_>i?0:i-_>>u,B=1+(a-_>>u);return B>x&&(B=x),function(){for(;;){if(C){var s=C();if(s!==et)return s;C=null}if(L===B)return et;var i=o?--B:L++;C=iterateNodeOrLeaf(j&&j[i],u-w,_+(i<=s.size||o<0)return s.withMutations((function(s){o<0?setListBounds(s,o).set(0,i):setListBounds(s,0,o+1).set(o,i)}));o+=s._origin;var a=s._tail,u=s._root,_=MakeRef(B);return o>=getTailOffset(s._capacity)?a=updateVNode(a,s.__ownerID,0,o,i,_):u=updateVNode(u,s.__ownerID,s._level,o,i,_),_.value?s.__ownerID?(s._root=u,s._tail=a,s.__hash=void 0,s.__altered=!0,s):makeList(s._origin,s._capacity,s._level,u,a):s}function updateVNode(s,o,i,a,u,_){var x,j=a>>>i&C,L=s&&j0){var B=s&&s.array[j],$=updateVNode(B,o,i-w,a,u,_);return $===B?s:((x=editableVNode(s,o)).array[j]=$,x)}return L&&s.array[j]===u?s:(SetRef(_),x=editableVNode(s,o),void 0===u&&j===x.array.length-1?x.array.pop():x.array[j]=u,x)}function editableVNode(s,o){return o&&s&&o===s.ownerID?s:new VNode(s?s.array.slice():[],o)}function listNodeFor(s,o){if(o>=getTailOffset(s._capacity))return s._tail;if(o<1<0;)i=i.array[o>>>a&C],a-=w;return i}}function setListBounds(s,o,i){void 0!==o&&(o|=0),void 0!==i&&(i|=0);var a=s.__ownerID||new OwnerID,u=s._origin,_=s._capacity,x=u+o,j=void 0===i?_:i<0?_+i:u+i;if(x===u&&j===_)return s;if(x>=j)return s.clear();for(var L=s._level,B=s._root,$=0;x+$<0;)B=new VNode(B&&B.array.length?[void 0,B]:[],a),$+=1<<(L+=w);$&&(x+=$,u+=$,j+=$,_+=$);for(var U=getTailOffset(_),V=getTailOffset(j);V>=1<U?new VNode([],a):z;if(z&&V>U&&x<_&&z.array.length){for(var Z=B=editableVNode(B,a),ee=L;ee>w;ee-=w){var ie=U>>>ee&C;Z=Z.array[ie]=editableVNode(Z.array[ie],a)}Z.array[U>>>w&C]=z}if(j<_&&(Y=Y&&Y.removeAfter(a,0,j)),x>=V)x-=V,j-=V,L=w,B=null,Y=Y&&Y.removeBefore(a,0,x);else if(x>u||V>>L&C;if(ae!==V>>>L&C)break;ae&&($+=(1<u&&(B=B.removeBefore(a,L,x-$)),B&&Vu&&(u=x.size),isIterable(w)||(x=x.map((function(s){return fromJS(s)}))),a.push(x)}return u>s.size&&(s=s.setSize(u)),mergeIntoCollectionWith(s,o,a)}function getTailOffset(s){return s>>w<=x&&w.size>=2*_.size?(a=(u=w.filter((function(s,o){return void 0!==s&&C!==o}))).toKeyedSeq().map((function(s){return s[0]})).flip().toMap(),s.__ownerID&&(a.__ownerID=u.__ownerID=s.__ownerID)):(a=_.remove(o),u=C===w.size-1?w.pop():w.set(C,void 0))}else if(L){if(i===w.get(C)[1])return s;a=_,u=w.set(C,[o,i])}else a=_.set(o,w.size),u=w.set(w.size,[o,i]);return s.__ownerID?(s.size=a.size,s._map=a,s._list=u,s.__hash=void 0,s):makeOrderedMap(a,u)}function ToKeyedSequence(s,o){this._iter=s,this._useKeys=o,this.size=s.size}function ToIndexedSequence(s){this._iter=s,this.size=s.size}function ToSetSequence(s){this._iter=s,this.size=s.size}function FromEntriesSequence(s){this._iter=s,this.size=s.size}function flipFactory(s){var o=makeSequence(s);return o._iter=s,o.size=s.size,o.flip=function(){return s},o.reverse=function(){var o=s.reverse.apply(this);return o.flip=function(){return s.reverse()},o},o.has=function(o){return s.includes(o)},o.includes=function(o){return s.has(o)},o.cacheResult=cacheResultThrough,o.__iterateUncached=function(o,i){var a=this;return s.__iterate((function(s,i){return!1!==o(i,s,a)}),i)},o.__iteratorUncached=function(o,i){if(o===V){var a=s.__iterator(o,i);return new Iterator((function(){var s=a.next();if(!s.done){var o=s.value[0];s.value[0]=s.value[1],s.value[1]=o}return s}))}return s.__iterator(o===U?$:U,i)},o}function mapFactory(s,o,i){var a=makeSequence(s);return a.size=s.size,a.has=function(o){return s.has(o)},a.get=function(a,u){var _=s.get(a,j);return _===j?u:o.call(i,_,a,s)},a.__iterateUncached=function(a,u){var _=this;return s.__iterate((function(s,u,w){return!1!==a(o.call(i,s,u,w),u,_)}),u)},a.__iteratorUncached=function(a,u){var _=s.__iterator(V,u);return new Iterator((function(){var u=_.next();if(u.done)return u;var w=u.value,x=w[0];return iteratorValue(a,x,o.call(i,w[1],x,s),u)}))},a}function reverseFactory(s,o){var i=makeSequence(s);return i._iter=s,i.size=s.size,i.reverse=function(){return s},s.flip&&(i.flip=function(){var o=flipFactory(s);return o.reverse=function(){return s.flip()},o}),i.get=function(i,a){return s.get(o?i:-1-i,a)},i.has=function(i){return s.has(o?i:-1-i)},i.includes=function(o){return s.includes(o)},i.cacheResult=cacheResultThrough,i.__iterate=function(o,i){var a=this;return s.__iterate((function(s,i){return o(s,i,a)}),!i)},i.__iterator=function(o,i){return s.__iterator(o,!i)},i}function filterFactory(s,o,i,a){var u=makeSequence(s);return a&&(u.has=function(a){var u=s.get(a,j);return u!==j&&!!o.call(i,u,a,s)},u.get=function(a,u){var _=s.get(a,j);return _!==j&&o.call(i,_,a,s)?_:u}),u.__iterateUncached=function(u,_){var w=this,x=0;return s.__iterate((function(s,_,C){if(o.call(i,s,_,C))return x++,u(s,a?_:x-1,w)}),_),x},u.__iteratorUncached=function(u,_){var w=s.__iterator(V,_),x=0;return new Iterator((function(){for(;;){var _=w.next();if(_.done)return _;var C=_.value,j=C[0],L=C[1];if(o.call(i,L,j,s))return iteratorValue(u,a?j:x++,L,_)}}))},u}function countByFactory(s,o,i){var a=Map().asMutable();return s.__iterate((function(u,_){a.update(o.call(i,u,_,s),0,(function(s){return s+1}))})),a.asImmutable()}function groupByFactory(s,o,i){var a=isKeyed(s),u=(isOrdered(s)?OrderedMap():Map()).asMutable();s.__iterate((function(_,w){u.update(o.call(i,_,w,s),(function(s){return(s=s||[]).push(a?[w,_]:_),s}))}));var _=iterableClass(s);return u.map((function(o){return reify(s,_(o))}))}function sliceFactory(s,o,i,a){var u=s.size;if(void 0!==o&&(o|=0),void 0!==i&&(i===1/0?i=u:i|=0),wholeSlice(o,i,u))return s;var _=resolveBegin(o,u),w=resolveEnd(i,u);if(_!=_||w!=w)return sliceFactory(s.toSeq().cacheResult(),o,i,a);var x,C=w-_;C==C&&(x=C<0?0:C);var j=makeSequence(s);return j.size=0===x?x:s.size&&x||void 0,!a&&isSeq(s)&&x>=0&&(j.get=function(o,i){return(o=wrapIndex(this,o))>=0&&ox)return iteratorDone();var s=u.next();return a||o===U?s:iteratorValue(o,C-1,o===$?void 0:s.value[1],s)}))},j}function takeWhileFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterate(a,u);var w=0;return s.__iterate((function(s,u,x){return o.call(i,s,u,x)&&++w&&a(s,u,_)})),w},a.__iteratorUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterator(a,u);var w=s.__iterator(V,u),x=!0;return new Iterator((function(){if(!x)return iteratorDone();var s=w.next();if(s.done)return s;var u=s.value,C=u[0],j=u[1];return o.call(i,j,C,_)?a===V?s:iteratorValue(a,C,j,s):(x=!1,iteratorDone())}))},a}function skipWhileFactory(s,o,i,a){var u=makeSequence(s);return u.__iterateUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterate(u,_);var x=!0,C=0;return s.__iterate((function(s,_,j){if(!x||!(x=o.call(i,s,_,j)))return C++,u(s,a?_:C-1,w)})),C},u.__iteratorUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterator(u,_);var x=s.__iterator(V,_),C=!0,j=0;return new Iterator((function(){var s,_,L;do{if((s=x.next()).done)return a||u===U?s:iteratorValue(u,j++,u===$?void 0:s.value[1],s);var B=s.value;_=B[0],L=B[1],C&&(C=o.call(i,L,_,w))}while(C);return u===V?s:iteratorValue(u,_,L,s)}))},u}function concatFactory(s,o){var i=isKeyed(s),a=[s].concat(o).map((function(s){return isIterable(s)?i&&(s=KeyedIterable(s)):s=i?keyedSeqFromValue(s):indexedSeqFromValue(Array.isArray(s)?s:[s]),s})).filter((function(s){return 0!==s.size}));if(0===a.length)return s;if(1===a.length){var u=a[0];if(u===s||i&&isKeyed(u)||isIndexed(s)&&isIndexed(u))return u}var _=new ArraySeq(a);return i?_=_.toKeyedSeq():isIndexed(s)||(_=_.toSetSeq()),(_=_.flatten(!0)).size=a.reduce((function(s,o){if(void 0!==s){var i=o.size;if(void 0!==i)return s+i}}),0),_}function flattenFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=0,w=!1;function flatDeep(s,x){var C=this;s.__iterate((function(s,u){return(!o||x0}function zipWithFactory(s,o,i){var a=makeSequence(s);return a.size=new ArraySeq(i).map((function(s){return s.size})).min(),a.__iterate=function(s,o){for(var i,a=this.__iterator(U,o),u=0;!(i=a.next()).done&&!1!==s(i.value,u++,this););return u},a.__iteratorUncached=function(s,a){var u=i.map((function(s){return s=Iterable(s),getIterator(a?s.reverse():s)})),_=0,w=!1;return new Iterator((function(){var i;return w||(i=u.map((function(s){return s.next()})),w=i.some((function(s){return s.done}))),w?iteratorDone():iteratorValue(s,_++,o.apply(null,i.map((function(s){return s.value}))))}))},a}function reify(s,o){return isSeq(s)?o:s.constructor(o)}function validateEntry(s){if(s!==Object(s))throw new TypeError("Expected [K, V] tuple: "+s)}function resolveSize(s){return assertNotInfinite(s.size),ensureSize(s)}function iterableClass(s){return isKeyed(s)?KeyedIterable:isIndexed(s)?IndexedIterable:SetIterable}function makeSequence(s){return Object.create((isKeyed(s)?KeyedSeq:isIndexed(s)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(s,o){return s>o?1:s=0;i--)o={value:arguments[i],next:o};return this.__ownerID?(this.size=s,this._head=o,this.__hash=void 0,this.__altered=!0,this):makeStack(s,o)},Stack.prototype.pushAll=function(s){if(0===(s=IndexedIterable(s)).size)return this;assertNotInfinite(s.size);var o=this.size,i=this._head;return s.reverse().forEach((function(s){o++,i={value:s,next:i}})),this.__ownerID?(this.size=o,this._head=i,this.__hash=void 0,this.__altered=!0,this):makeStack(o,i)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(s){return this.pushAll(s)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(s,o){if(wholeSlice(s,o,this.size))return this;var i=resolveBegin(s,this.size);if(resolveEnd(o,this.size)!==this.size)return IndexedCollection.prototype.slice.call(this,s,o);for(var a=this.size-i,u=this._head;i--;)u=u.next;return this.__ownerID?(this.size=a,this._head=u,this.__hash=void 0,this.__altered=!0,this):makeStack(a,u)},Stack.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeStack(this.size,this._head,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Stack.prototype.__iterate=function(s,o){if(o)return this.reverse().__iterate(s);for(var i=0,a=this._head;a&&!1!==s(a.value,i++,this);)a=a.next;return i},Stack.prototype.__iterator=function(s,o){if(o)return this.reverse().__iterator(s);var i=0,a=this._head;return new Iterator((function(){if(a){var o=a.value;return a=a.next,iteratorValue(s,i++,o)}return iteratorDone()}))},Stack.isStack=isStack;var at,ct="@@__IMMUTABLE_STACK__@@",lt=Stack.prototype;function makeStack(s,o,i,a){var u=Object.create(lt);return u.size=s,u._head=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyStack(){return at||(at=makeStack(0))}function mixin(s,o){var keyCopier=function(i){s.prototype[i]=o[i]};return Object.keys(o).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(o).forEach(keyCopier),s}function isProtoKey(s){return"string"==typeof s&&("__proto__"===s||"constructor"===s)}lt[ct]=!0,lt.withMutations=$e.withMutations,lt.asMutable=$e.asMutable,lt.asImmutable=$e.asImmutable,lt.wasAltered=$e.wasAltered,Iterable.Iterator=Iterator,mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var s=new Array(this.size||0);return this.valueSeq().__iterate((function(o,i){s[i]=o})),s},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJS?s.toJS():s})).__toJS()},toJSON:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJSON?s.toJSON():s})).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,!0)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var s={};return this.__iterate((function(o,i){isProtoKey(i)||(s[i]=o)})),s},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(s,o){return 0===this.size?s+o:s+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+o},concat:function(){return reify(this,concatFactory(this,s.call(arguments,0)))},includes:function(s){return this.some((function(o){return is(o,s)}))},entries:function(){return this.__iterator(V)},every:function(s,o){assertNotInfinite(this.size);var i=!0;return this.__iterate((function(a,u,_){if(!s.call(o,a,u,_))return i=!1,!1})),i},filter:function(s,o){return reify(this,filterFactory(this,s,o,!0))},find:function(s,o,i){var a=this.findEntry(s,o);return a?a[1]:i},forEach:function(s,o){return assertNotInfinite(this.size),this.__iterate(o?s.bind(o):s)},join:function(s){assertNotInfinite(this.size),s=void 0!==s?""+s:",";var o="",i=!0;return this.__iterate((function(a){i?i=!1:o+=s,o+=null!=a?a.toString():""})),o},keys:function(){return this.__iterator($)},map:function(s,o){return reify(this,mapFactory(this,s,o))},reduce:function(s,o,i){var a,u;return assertNotInfinite(this.size),arguments.length<2?u=!0:a=o,this.__iterate((function(o,_,w){u?(u=!1,a=o):a=s.call(i,a,o,_,w)})),a},reduceRight:function(s,o,i){var a=this.toKeyedSeq().reverse();return a.reduce.apply(a,arguments)},reverse:function(){return reify(this,reverseFactory(this,!0))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!0))},some:function(s,o){return!this.every(not(s),o)},sort:function(s){return reify(this,sortFactory(this,s))},values:function(){return this.__iterator(U)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(s,o){return ensureSize(s?this.toSeq().filter(s,o):this)},countBy:function(s,o){return countByFactory(this,s,o)},equals:function(s){return deepEqual(this,s)},entrySeq:function(){var s=this;if(s._cache)return new ArraySeq(s._cache);var o=s.toSeq().map(entryMapper).toIndexedSeq();return o.fromEntrySeq=function(){return s.toSeq()},o},filterNot:function(s,o){return this.filter(not(s),o)},findEntry:function(s,o,i){var a=i;return this.__iterate((function(i,u,_){if(s.call(o,i,u,_))return a=[u,i],!1})),a},findKey:function(s,o){var i=this.findEntry(s,o);return i&&i[0]},findLast:function(s,o,i){return this.toKeyedSeq().reverse().find(s,o,i)},findLastEntry:function(s,o,i){return this.toKeyedSeq().reverse().findEntry(s,o,i)},findLastKey:function(s,o){return this.toKeyedSeq().reverse().findKey(s,o)},first:function(){return this.find(returnTrue)},flatMap:function(s,o){return reify(this,flatMapFactory(this,s,o))},flatten:function(s){return reify(this,flattenFactory(this,s,!0))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(s,o){return this.find((function(o,i){return is(i,s)}),void 0,o)},getIn:function(s,o){for(var i,a=this,u=forceIterator(s);!(i=u.next()).done;){var _=i.value;if((a=a&&a.get?a.get(_,j):j)===j)return o}return a},groupBy:function(s,o){return groupByFactory(this,s,o)},has:function(s){return this.get(s,j)!==j},hasIn:function(s){return this.getIn(s,j)!==j},isSubset:function(s){return s="function"==typeof s.includes?s:Iterable(s),this.every((function(o){return s.includes(o)}))},isSuperset:function(s){return(s="function"==typeof s.isSubset?s:Iterable(s)).isSubset(this)},keyOf:function(s){return this.findKey((function(o){return is(o,s)}))},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(s){return this.toKeyedSeq().reverse().keyOf(s)},max:function(s){return maxFactory(this,s)},maxBy:function(s,o){return maxFactory(this,o,s)},min:function(s){return maxFactory(this,s?neg(s):defaultNegComparator)},minBy:function(s,o){return maxFactory(this,o?neg(o):defaultNegComparator,s)},rest:function(){return this.slice(1)},skip:function(s){return this.slice(Math.max(0,s))},skipLast:function(s){return reify(this,this.toSeq().reverse().skip(s).reverse())},skipWhile:function(s,o){return reify(this,skipWhileFactory(this,s,o,!0))},skipUntil:function(s,o){return this.skipWhile(not(s),o)},sortBy:function(s,o){return reify(this,sortFactory(this,o,s))},take:function(s){return this.slice(0,Math.max(0,s))},takeLast:function(s){return reify(this,this.toSeq().reverse().take(s).reverse())},takeWhile:function(s,o){return reify(this,takeWhileFactory(this,s,o))},takeUntil:function(s,o){return this.takeWhile(not(s),o)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var ut=Iterable.prototype;ut[o]=!0,ut[Z]=ut.values,ut.__toJS=ut.toArray,ut.__toStringMapper=quoteString,ut.inspect=ut.toSource=function(){return this.toString()},ut.chain=ut.flatMap,ut.contains=ut.includes,mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(s,o){var i=this,a=0;return reify(this,this.toSeq().map((function(u,_){return s.call(o,[_,u],a++,i)})).fromEntrySeq())},mapKeys:function(s,o){var i=this;return reify(this,this.toSeq().flip().map((function(a,u){return s.call(o,a,u,i)})).flip())}});var pt=KeyedIterable.prototype;function keyMapper(s,o){return o}function entryMapper(s,o){return[o,s]}function not(s){return function(){return!s.apply(this,arguments)}}function neg(s){return function(){return-s.apply(this,arguments)}}function quoteString(s){return"string"==typeof s?JSON.stringify(s):String(s)}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(s,o){return so?-1:0}function hashIterable(s){if(s.size===1/0)return 0;var o=isOrdered(s),i=isKeyed(s),a=o?1:0;return murmurHashOfSize(s.__iterate(i?o?function(s,o){a=31*a+hashMerge(hash(s),hash(o))|0}:function(s,o){a=a+hashMerge(hash(s),hash(o))|0}:o?function(s){a=31*a+hash(s)|0}:function(s){a=a+hash(s)|0}),a)}function murmurHashOfSize(s,o){return o=le(o,3432918353),o=le(o<<15|o>>>-15,461845907),o=le(o<<13|o>>>-13,5),o=le((o=o+3864292196^s)^o>>>16,2246822507),o=smi((o=le(o^o>>>13,3266489909))^o>>>16)}function hashMerge(s,o){return s^o+2654435769+(s<<6)+(s>>2)}return pt[i]=!0,pt[Z]=ut.entries,pt.__toJS=ut.toObject,pt.__toStringMapper=function(s,o){return JSON.stringify(o)+": "+quoteString(s)},mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,!1)},filter:function(s,o){return reify(this,filterFactory(this,s,o,!1))},findIndex:function(s,o){var i=this.findEntry(s,o);return i?i[0]:-1},indexOf:function(s){var o=this.keyOf(s);return void 0===o?-1:o},lastIndexOf:function(s){var o=this.lastKeyOf(s);return void 0===o?-1:o},reverse:function(){return reify(this,reverseFactory(this,!1))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!1))},splice:function(s,o){var i=arguments.length;if(o=Math.max(0|o,0),0===i||2===i&&!o)return this;s=resolveBegin(s,s<0?this.count():this.size);var a=this.slice(0,s);return reify(this,1===i?a:a.concat(arrCopy(arguments,2),this.slice(s+o)))},findLastIndex:function(s,o){var i=this.findLastEntry(s,o);return i?i[0]:-1},first:function(){return this.get(0)},flatten:function(s){return reify(this,flattenFactory(this,s,!1))},get:function(s,o){return(s=wrapIndex(this,s))<0||this.size===1/0||void 0!==this.size&&s>this.size?o:this.find((function(o,i){return i===s}),void 0,o)},has:function(s){return(s=wrapIndex(this,s))>=0&&(void 0!==this.size?this.size===1/0||s=o||i<0||B&&s-j>=_}function timerExpired(){var s=now();if(shouldInvoke(s))return trailingEdge(s);x=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-C);return B?U(i,_-(s-j)):i}(s))}function trailingEdge(s){return x=void 0,V&&a?invokeFunc(s):(a=u=void 0,w)}function debounced(){var s=now(),i=shouldInvoke(s);if(a=arguments,u=this,C=s,i){if(void 0===x)return function leadingEdge(s){return j=s,x=setTimeout(timerExpired,o),L?invokeFunc(s):w}(C);if(B)return x=setTimeout(timerExpired,o),invokeFunc(C)}return void 0===x&&(x=setTimeout(timerExpired,o)),w}return o=toNumber(o)||0,isObject(i)&&(L=!!i.leading,_=(B="maxWait"in i)?$(toNumber(i.maxWait)||0,o):_,V="trailing"in i?!!i.trailing:V),debounced.cancel=function cancel(){void 0!==x&&clearTimeout(x),j=0,a=C=u=x=void 0},debounced.flush=function flush(){return void 0===x?w:trailingEdge(now())},debounced}},55580(s,o,i){var a=i(56110)(i(9325),"DataView");s.exports=a},21549(s,o,i){var a=i(22032),u=i(63862),_=i(66721),w=i(12749),x=i(35749);function Hash(s){var o=-1,i=null==s?0:s.length;for(this.clear();++o-1}},70695(s,o,i){var a=i(78096),u=i(72428),_=i(56449),w=i(3656),x=i(30361),C=i(37167),j=Object.prototype.hasOwnProperty;s.exports=function arrayLikeKeys(s,o){var i=_(s),L=!i&&u(s),B=!i&&!L&&w(s),$=!i&&!L&&!B&&C(s),U=i||L||B||$,V=U?a(s.length,String):[],z=V.length;for(var Y in s)!o&&!j.call(s,Y)||U&&("length"==Y||B&&("offset"==Y||"parent"==Y)||$&&("buffer"==Y||"byteLength"==Y||"byteOffset"==Y)||x(Y,z))||V.push(Y);return V}},34932(s){s.exports=function arrayMap(s,o){for(var i=-1,a=null==s?0:s.length,u=Array(a);++i0&&i(j)?o>1?baseFlatten(j,o-1,i,_,w):a(w,j):_||(w[w.length]=j)}return w}},86649(s,o,i){var a=i(83221)();s.exports=a},30641(s,o,i){var a=i(86649),u=i(95950);s.exports=function baseForOwn(s,o){return s&&a(s,o,u)}},47422(s,o,i){var a=i(31769),u=i(77797);s.exports=function baseGet(s,o){for(var i=0,_=(o=a(o,s)).length;null!=s&&i<_;)s=s[u(o[i++])];return i&&i==_?s:void 0}},82199(s,o,i){var a=i(14528),u=i(56449);s.exports=function baseGetAllKeys(s,o,i){var _=o(s);return u(s)?_:a(_,i(s))}},72552(s,o,i){var a=i(51873),u=i(659),_=i(59350),w=a?a.toStringTag:void 0;s.exports=function baseGetTag(s){return null==s?void 0===s?"[object Undefined]":"[object Null]":w&&w in Object(s)?u(s):_(s)}},20426(s){var o=Object.prototype.hasOwnProperty;s.exports=function baseHas(s,i){return null!=s&&o.call(s,i)}},28077(s){s.exports=function baseHasIn(s,o){return null!=s&&o in Object(s)}},96131(s,o,i){var a=i(2523),u=i(85463),_=i(76959);s.exports=function baseIndexOf(s,o,i){return o==o?_(s,o,i):a(s,u,i)}},27534(s,o,i){var a=i(72552),u=i(40346);s.exports=function baseIsArguments(s){return u(s)&&"[object Arguments]"==a(s)}},60270(s,o,i){var a=i(87068),u=i(40346);s.exports=function baseIsEqual(s,o,i,_,w){return s===o||(null==s||null==o||!u(s)&&!u(o)?s!=s&&o!=o:a(s,o,i,_,baseIsEqual,w))}},87068(s,o,i){var a=i(37217),u=i(25911),_=i(21986),w=i(50689),x=i(5861),C=i(56449),j=i(3656),L=i(37167),B="[object Arguments]",$="[object Array]",U="[object Object]",V=Object.prototype.hasOwnProperty;s.exports=function baseIsEqualDeep(s,o,i,z,Y,Z){var ee=C(s),ie=C(o),ae=ee?$:x(s),ce=ie?$:x(o),le=(ae=ae==B?U:ae)==U,pe=(ce=ce==B?U:ce)==U,de=ae==ce;if(de&&j(s)){if(!j(o))return!1;ee=!0,le=!1}if(de&&!le)return Z||(Z=new a),ee||L(s)?u(s,o,i,z,Y,Z):_(s,o,ae,i,z,Y,Z);if(!(1&i)){var fe=le&&V.call(s,"__wrapped__"),ye=pe&&V.call(o,"__wrapped__");if(fe||ye){var be=fe?s.value():s,Se=ye?o.value():o;return Z||(Z=new a),Y(be,Se,i,z,Z)}}return!!de&&(Z||(Z=new a),w(s,o,i,z,Y,Z))}},29172(s,o,i){var a=i(5861),u=i(40346);s.exports=function baseIsMap(s){return u(s)&&"[object Map]"==a(s)}},41799(s,o,i){var a=i(37217),u=i(60270);s.exports=function baseIsMatch(s,o,i,_){var w=i.length,x=w,C=!_;if(null==s)return!x;for(s=Object(s);w--;){var j=i[w];if(C&&j[2]?j[1]!==s[j[0]]:!(j[0]in s))return!1}for(;++wu?0:u+o),(i=i>u?u:i)<0&&(i+=u),u=o>i?0:i-o>>>0,o>>>=0;for(var _=Array(u);++a=u?s:a(s,o,i)}},49653(s,o,i){var a=i(37828);s.exports=function cloneArrayBuffer(s){var o=new s.constructor(s.byteLength);return new a(o).set(new a(s)),o}},93290(s,o,i){s=i.nmd(s);var a=i(9325),u=o&&!o.nodeType&&o,_=u&&s&&!s.nodeType&&s,w=_&&_.exports===u?a.Buffer:void 0,x=w?w.allocUnsafe:void 0;s.exports=function cloneBuffer(s,o){if(o)return s.slice();var i=s.length,a=x?x(i):new s.constructor(i);return s.copy(a),a}},76169(s,o,i){var a=i(49653);s.exports=function cloneDataView(s,o){var i=o?a(s.buffer):s.buffer;return new s.constructor(i,s.byteOffset,s.byteLength)}},73201(s){var o=/\w*$/;s.exports=function cloneRegExp(s){var i=new s.constructor(s.source,o.exec(s));return i.lastIndex=s.lastIndex,i}},93736(s,o,i){var a=i(51873),u=a?a.prototype:void 0,_=u?u.valueOf:void 0;s.exports=function cloneSymbol(s){return _?Object(_.call(s)):{}}},71961(s,o,i){var a=i(49653);s.exports=function cloneTypedArray(s,o){var i=o?a(s.buffer):s.buffer;return new s.constructor(i,s.byteOffset,s.length)}},91596(s){var o=Math.max;s.exports=function composeArgs(s,i,a,u){for(var _=-1,w=s.length,x=a.length,C=-1,j=i.length,L=o(w-x,0),B=Array(j+L),$=!u;++C1?i[_-1]:void 0,x=_>2?i[2]:void 0;for(w=s.length>3&&"function"==typeof w?(_--,w):void 0,x&&u(i[0],i[1],x)&&(w=_<3?void 0:w,_=1),o=Object(o);++a<_;){var C=i[a];C&&s(o,C,a,w)}return o}))}},38329(s,o,i){var a=i(64894);s.exports=function createBaseEach(s,o){return function(i,u){if(null==i)return i;if(!a(i))return s(i,u);for(var _=i.length,w=o?_:-1,x=Object(i);(o?w--:++w<_)&&!1!==u(x[w],w,x););return i}}},83221(s){s.exports=function createBaseFor(s){return function(o,i,a){for(var u=-1,_=Object(o),w=a(o),x=w.length;x--;){var C=w[s?x:++u];if(!1===i(_[C],C,_))break}return o}}},11842(s,o,i){var a=i(82819),u=i(9325);s.exports=function createBind(s,o,i){var _=1&o,w=a(s);return function wrapper(){return(this&&this!==u&&this instanceof wrapper?w:s).apply(_?i:this,arguments)}}},12507(s,o,i){var a=i(28754),u=i(49698),_=i(63912),w=i(13222);s.exports=function createCaseFirst(s){return function(o){o=w(o);var i=u(o)?_(o):void 0,x=i?i[0]:o.charAt(0),C=i?a(i,1).join(""):o.slice(1);return x[s]()+C}}},45539(s,o,i){var a=i(40882),u=i(50828),_=i(66645),w=RegExp("['’]","g");s.exports=function createCompounder(s){return function(o){return a(_(u(o).replace(w,"")),s,"")}}},82819(s,o,i){var a=i(39344),u=i(23805);s.exports=function createCtor(s){return function(){var o=arguments;switch(o.length){case 0:return new s;case 1:return new s(o[0]);case 2:return new s(o[0],o[1]);case 3:return new s(o[0],o[1],o[2]);case 4:return new s(o[0],o[1],o[2],o[3]);case 5:return new s(o[0],o[1],o[2],o[3],o[4]);case 6:return new s(o[0],o[1],o[2],o[3],o[4],o[5]);case 7:return new s(o[0],o[1],o[2],o[3],o[4],o[5],o[6])}var i=a(s.prototype),_=s.apply(i,o);return u(_)?_:i}}},77078(s,o,i){var a=i(91033),u=i(82819),_=i(37471),w=i(18073),x=i(11287),C=i(36306),j=i(9325);s.exports=function createCurry(s,o,i){var L=u(s);return function wrapper(){for(var u=arguments.length,B=Array(u),$=u,U=x(wrapper);$--;)B[$]=arguments[$];var V=u<3&&B[0]!==U&&B[u-1]!==U?[]:C(B,U);return(u-=V.length)-1?x[C?o[j]:j]:void 0}}},37471(s,o,i){var a=i(91596),u=i(53320),_=i(58523),w=i(82819),x=i(18073),C=i(11287),j=i(68294),L=i(36306),B=i(9325);s.exports=function createHybrid(s,o,i,$,U,V,z,Y,Z,ee){var ie=128&o,ae=1&o,ce=2&o,le=24&o,pe=512&o,de=ce?void 0:w(s);return function wrapper(){for(var fe=arguments.length,ye=Array(fe),be=fe;be--;)ye[be]=arguments[be];if(le)var Se=C(wrapper),_e=_(ye,Se);if($&&(ye=a(ye,$,U,le)),V&&(ye=u(ye,V,z,le)),fe-=_e,le&&fe1&&ye.reverse(),ie&&ZL))return!1;var $=C.get(s),U=C.get(o);if($&&U)return $==o&&U==s;var V=-1,z=!0,Y=2&i?new a:void 0;for(C.set(s,o),C.set(o,s);++V1?"& ":"")+i[u],i=i.join(a>2?", ":" "),s.replace(o,"{\n/* [wrapped with "+i+"] */\n")}},45891(s,o,i){var a=i(51873),u=i(72428),_=i(56449),w=a?a.isConcatSpreadable:void 0;s.exports=function isFlattenable(s){return _(s)||u(s)||!!(w&&s&&s[w])}},30361(s){var o=/^(?:0|[1-9]\d*)$/;s.exports=function isIndex(s,i){var a=typeof s;return!!(i=null==i?9007199254740991:i)&&("number"==a||"symbol"!=a&&o.test(s))&&s>-1&&s%1==0&&s-1}},31175(s,o,i){var a=i(26025);s.exports=function listCacheSet(s,o){var i=this.__data__,u=a(i,s);return u<0?(++this.size,i.push([s,o])):i[u][1]=o,this}},63040(s,o,i){var a=i(21549),u=i(80079),_=i(68223);s.exports=function mapCacheClear(){this.size=0,this.__data__={hash:new a,map:new(_||u),string:new a}}},17670(s,o,i){var a=i(12651);s.exports=function mapCacheDelete(s){var o=a(this,s).delete(s);return this.size-=o?1:0,o}},90289(s,o,i){var a=i(12651);s.exports=function mapCacheGet(s){return a(this,s).get(s)}},4509(s,o,i){var a=i(12651);s.exports=function mapCacheHas(s){return a(this,s).has(s)}},72949(s,o,i){var a=i(12651);s.exports=function mapCacheSet(s,o){var i=a(this,s),u=i.size;return i.set(s,o),this.size+=i.size==u?0:1,this}},20317(s){s.exports=function mapToArray(s){var o=-1,i=Array(s.size);return s.forEach((function(s,a){i[++o]=[a,s]})),i}},67197(s){s.exports=function matchesStrictComparable(s,o){return function(i){return null!=i&&(i[s]===o&&(void 0!==o||s in Object(i)))}}},62224(s,o,i){var a=i(50104);s.exports=function memoizeCapped(s){var o=a(s,(function(s){return 500===i.size&&i.clear(),s})),i=o.cache;return o}},3209(s,o,i){var a=i(91596),u=i(53320),_=i(36306),w="__lodash_placeholder__",x=128,C=Math.min;s.exports=function mergeData(s,o){var i=s[1],j=o[1],L=i|j,B=L<131,$=j==x&&8==i||j==x&&256==i&&s[7].length<=o[8]||384==j&&o[7].length<=o[8]&&8==i;if(!B&&!$)return s;1&j&&(s[2]=o[2],L|=1&i?0:4);var U=o[3];if(U){var V=s[3];s[3]=V?a(V,U,o[4]):U,s[4]=V?_(s[3],w):o[4]}return(U=o[5])&&(V=s[5],s[5]=V?u(V,U,o[6]):U,s[6]=V?_(s[5],w):o[6]),(U=o[7])&&(s[7]=U),j&x&&(s[8]=null==s[8]?o[8]:C(s[8],o[8])),null==s[9]&&(s[9]=o[9]),s[0]=o[0],s[1]=L,s}},48152(s,o,i){var a=i(28303),u=a&&new a;s.exports=u},81042(s,o,i){var a=i(56110)(Object,"create");s.exports=a},3650(s,o,i){var a=i(74335)(Object.keys,Object);s.exports=a},90181(s){s.exports=function nativeKeysIn(s){var o=[];if(null!=s)for(var i in Object(s))o.push(i);return o}},86009(s,o,i){s=i.nmd(s);var a=i(34840),u=o&&!o.nodeType&&o,_=u&&s&&!s.nodeType&&s,w=_&&_.exports===u&&a.process,x=function(){try{var s=_&&_.require&&_.require("util").types;return s||w&&w.binding&&w.binding("util")}catch(s){}}();s.exports=x},59350(s){var o=Object.prototype.toString;s.exports=function objectToString(s){return o.call(s)}},74335(s){s.exports=function overArg(s,o){return function(i){return s(o(i))}}},56757(s,o,i){var a=i(91033),u=Math.max;s.exports=function overRest(s,o,i){return o=u(void 0===o?s.length-1:o,0),function(){for(var _=arguments,w=-1,x=u(_.length-o,0),C=Array(x);++w0){if(++i>=800)return arguments[0]}else i=0;return s.apply(void 0,arguments)}}},51420(s,o,i){var a=i(80079);s.exports=function stackClear(){this.__data__=new a,this.size=0}},90938(s){s.exports=function stackDelete(s){var o=this.__data__,i=o.delete(s);return this.size=o.size,i}},63605(s){s.exports=function stackGet(s){return this.__data__.get(s)}},29817(s){s.exports=function stackHas(s){return this.__data__.has(s)}},80945(s,o,i){var a=i(80079),u=i(68223),_=i(53661);s.exports=function stackSet(s,o){var i=this.__data__;if(i instanceof a){var w=i.__data__;if(!u||w.length<199)return w.push([s,o]),this.size=++i.size,this;i=this.__data__=new _(w)}return i.set(s,o),this.size=i.size,this}},76959(s){s.exports=function strictIndexOf(s,o,i){for(var a=i-1,u=s.length;++a=o||i<0||Y&&s-V>=L}function timerExpired(){var s=u();if(shouldInvoke(s))return trailingEdge(s);$=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-U);return Y?x(i,L-(s-V)):i}(s))}function trailingEdge(s){return $=void 0,Z&&C?invokeFunc(s):(C=j=void 0,B)}function debounced(){var s=u(),i=shouldInvoke(s);if(C=arguments,j=this,U=s,i){if(void 0===$)return function leadingEdge(s){return V=s,$=setTimeout(timerExpired,o),z?invokeFunc(s):B}(U);if(Y)return clearTimeout($),$=setTimeout(timerExpired,o),invokeFunc(U)}return void 0===$&&($=setTimeout(timerExpired,o)),B}return o=_(o)||0,a(i)&&(z=!!i.leading,L=(Y="maxWait"in i)?w(_(i.maxWait)||0,o):L,Z="trailing"in i?!!i.trailing:Z),debounced.cancel=function cancel(){void 0!==$&&clearTimeout($),V=0,C=U=j=$=void 0},debounced.flush=function flush(){return void 0===$?B:trailingEdge(u())},debounced}},50828(s,o,i){var a=i(24647),u=i(13222),_=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,w=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");s.exports=function deburr(s){return(s=u(s))&&s.replace(_,a).replace(w,"")}},75288(s){s.exports=function eq(s,o){return s===o||s!=s&&o!=o}},60680(s,o,i){var a=i(13222),u=/[\\^$.*+?()[\]{}|]/g,_=RegExp(u.source);s.exports=function escapeRegExp(s){return(s=a(s))&&_.test(s)?s.replace(u,"\\$&"):s}},7309(s,o,i){var a=i(62006)(i(24713));s.exports=a},24713(s,o,i){var a=i(2523),u=i(15389),_=i(61489),w=Math.max;s.exports=function findIndex(s,o,i){var x=null==s?0:s.length;if(!x)return-1;var C=null==i?0:_(i);return C<0&&(C=w(x+C,0)),a(s,u(o,3),C)}},35970(s,o,i){var a=i(83120);s.exports=function flatten(s){return(null==s?0:s.length)?a(s,1):[]}},73424(s,o,i){var a=i(16962),u=i(2874),_=Array.prototype.push;function baseAry(s,o){return 2==o?function(o,i){return s(o,i)}:function(o){return s(o)}}function cloneArray(s){for(var o=s?s.length:0,i=Array(o);o--;)i[o]=s[o];return i}function wrapImmutable(s,o){return function(){var i=arguments.length;if(i){for(var a=Array(i);i--;)a[i]=arguments[i];var u=a[0]=o.apply(void 0,a);return s.apply(void 0,a),u}}}s.exports=function baseConvert(s,o,i,w){var x="function"==typeof o,C=o===Object(o);if(C&&(w=i,i=o,o=void 0),null==i)throw new TypeError;w||(w={});var j=!("cap"in w)||w.cap,L=!("curry"in w)||w.curry,B=!("fixed"in w)||w.fixed,$=!("immutable"in w)||w.immutable,U=!("rearg"in w)||w.rearg,V=x?i:u,z="curry"in w&&w.curry,Y="fixed"in w&&w.fixed,Z="rearg"in w&&w.rearg,ee=x?i.runInContext():void 0,ie=x?i:{ary:s.ary,assign:s.assign,clone:s.clone,curry:s.curry,forEach:s.forEach,isArray:s.isArray,isError:s.isError,isFunction:s.isFunction,isWeakMap:s.isWeakMap,iteratee:s.iteratee,keys:s.keys,rearg:s.rearg,toInteger:s.toInteger,toPath:s.toPath},ae=ie.ary,ce=ie.assign,le=ie.clone,pe=ie.curry,de=ie.forEach,fe=ie.isArray,ye=ie.isError,be=ie.isFunction,Se=ie.isWeakMap,_e=ie.keys,we=ie.rearg,xe=ie.toInteger,Pe=ie.toPath,Te=_e(a.aryMethod),Re={castArray:function(s){return function(){var o=arguments[0];return fe(o)?s(cloneArray(o)):s.apply(void 0,arguments)}},iteratee:function(s){return function(){var o=arguments[1],i=s(arguments[0],o),a=i.length;return j&&"number"==typeof o?(o=o>2?o-2:1,a&&a<=o?i:baseAry(i,o)):i}},mixin:function(s){return function(o){var i=this;if(!be(i))return s(i,Object(o));var a=[];return de(_e(o),(function(s){be(o[s])&&a.push([s,i.prototype[s]])})),s(i,Object(o)),de(a,(function(s){var o=s[1];be(o)?i.prototype[s[0]]=o:delete i.prototype[s[0]]})),i}},nthArg:function(s){return function(o){var i=o<0?1:xe(o)+1;return pe(s(o),i)}},rearg:function(s){return function(o,i){var a=i?i.length:0;return pe(s(o,i),a)}},runInContext:function(o){return function(i){return baseConvert(s,o(i),w)}}};function castCap(s,o){if(j){var i=a.iterateeRearg[s];if(i)return function iterateeRearg(s,o){return overArg(s,(function(s){var i=o.length;return function baseArity(s,o){return 2==o?function(o,i){return s.apply(void 0,arguments)}:function(o){return s.apply(void 0,arguments)}}(we(baseAry(s,i),o),i)}))}(o,i);var u=!x&&a.iterateeAry[s];if(u)return function iterateeAry(s,o){return overArg(s,(function(s){return"function"==typeof s?baseAry(s,o):s}))}(o,u)}return o}function castFixed(s,o,i){if(B&&(Y||!a.skipFixed[s])){var u=a.methodSpread[s],w=u&&u.start;return void 0===w?ae(o,i):function flatSpread(s,o){return function(){for(var i=arguments.length,a=i-1,u=Array(i);i--;)u[i]=arguments[i];var w=u[o],x=u.slice(0,o);return w&&_.apply(x,w),o!=a&&_.apply(x,u.slice(o+1)),s.apply(this,x)}}(o,w)}return o}function castRearg(s,o,i){return U&&i>1&&(Z||!a.skipRearg[s])?we(o,a.methodRearg[s]||a.aryRearg[i]):o}function cloneByPath(s,o){for(var i=-1,a=(o=Pe(o)).length,u=a-1,_=le(Object(s)),w=_;null!=w&&++i1?pe(o,i):o}(0,u=castCap(_,u),s),!1}})),!u})),u||(u=w),u==o&&(u=z?pe(u,1):function(){return o.apply(this,arguments)}),u.convert=createConverter(_,o),u.placeholder=o.placeholder=i,u}if(!C)return wrap(o,i,V);var $e=i,qe=[];return de(Te,(function(s){de(a.aryMethod[s],(function(s){var o=$e[a.remap[s]||s];o&&qe.push([s,wrap(s,o,$e)])}))})),de(_e($e),(function(s){var o=$e[s];if("function"==typeof o){for(var i=qe.length;i--;)if(qe[i][0]==s)return;o.convert=createConverter(s,o),qe.push([s,o])}})),de(qe,(function(s){$e[s[0]]=s[1]})),$e.convert=function convertLib(s){return $e.runInContext.convert(s)(void 0)},$e.placeholder=$e,de(_e($e),(function(s){de(a.realToAlias[s]||[],(function(o){$e[o]=$e[s]}))})),$e}},16962(s,o){o.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},o.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},o.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},o.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},o.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},o.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},o.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},o.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},o.realToAlias=function(){var s=Object.prototype.hasOwnProperty,i=o.aliasToReal,a={};for(var u in i){var _=i[u];s.call(a,_)?a[_].push(u):a[_]=[u]}return a}(),o.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},o.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},o.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},47934(s,o,i){s.exports={ary:i(64626),assign:i(74733),clone:i(32629),curry:i(49747),forEach:i(83729),isArray:i(56449),isError:i(23546),isFunction:i(1882),isWeakMap:i(47886),iteratee:i(33855),keys:i(88984),rearg:i(84195),toInteger:i(61489),toPath:i(42072)}},56367(s,o,i){s.exports=i(77731)},79920(s,o,i){var a=i(73424),u=i(47934);s.exports=function convert(s,o,i){return a(u,s,o,i)}},2874(s){s.exports={}},77731(s,o,i){var a=i(79920)("set",i(63560));a.placeholder=i(2874),s.exports=a},58156(s,o,i){var a=i(47422);s.exports=function get(s,o,i){var u=null==s?void 0:a(s,o);return void 0===u?i:u}},61448(s,o,i){var a=i(20426),u=i(49326);s.exports=function has(s,o){return null!=s&&u(s,o,a)}},80631(s,o,i){var a=i(28077),u=i(49326);s.exports=function hasIn(s,o){return null!=s&&u(s,o,a)}},83488(s){s.exports=function identity(s){return s}},72428(s,o,i){var a=i(27534),u=i(40346),_=Object.prototype,w=_.hasOwnProperty,x=_.propertyIsEnumerable,C=a(function(){return arguments}())?a:function(s){return u(s)&&w.call(s,"callee")&&!x.call(s,"callee")};s.exports=C},56449(s){var o=Array.isArray;s.exports=o},64894(s,o,i){var a=i(1882),u=i(30294);s.exports=function isArrayLike(s){return null!=s&&u(s.length)&&!a(s)}},83693(s,o,i){var a=i(64894),u=i(40346);s.exports=function isArrayLikeObject(s){return u(s)&&a(s)}},53812(s,o,i){var a=i(72552),u=i(40346);s.exports=function isBoolean(s){return!0===s||!1===s||u(s)&&"[object Boolean]"==a(s)}},3656(s,o,i){s=i.nmd(s);var a=i(9325),u=i(89935),_=o&&!o.nodeType&&o,w=_&&s&&!s.nodeType&&s,x=w&&w.exports===_?a.Buffer:void 0,C=(x?x.isBuffer:void 0)||u;s.exports=C},62193(s,o,i){var a=i(88984),u=i(5861),_=i(72428),w=i(56449),x=i(64894),C=i(3656),j=i(55527),L=i(37167),B=Object.prototype.hasOwnProperty;s.exports=function isEmpty(s){if(null==s)return!0;if(x(s)&&(w(s)||"string"==typeof s||"function"==typeof s.splice||C(s)||L(s)||_(s)))return!s.length;var o=u(s);if("[object Map]"==o||"[object Set]"==o)return!s.size;if(j(s))return!a(s).length;for(var i in s)if(B.call(s,i))return!1;return!0}},2404(s,o,i){var a=i(60270);s.exports=function isEqual(s,o){return a(s,o)}},23546(s,o,i){var a=i(72552),u=i(40346),_=i(11331);s.exports=function isError(s){if(!u(s))return!1;var o=a(s);return"[object Error]"==o||"[object DOMException]"==o||"string"==typeof s.message&&"string"==typeof s.name&&!_(s)}},1882(s,o,i){var a=i(72552),u=i(23805);s.exports=function isFunction(s){if(!u(s))return!1;var o=a(s);return"[object Function]"==o||"[object GeneratorFunction]"==o||"[object AsyncFunction]"==o||"[object Proxy]"==o}},30294(s){s.exports=function isLength(s){return"number"==typeof s&&s>-1&&s%1==0&&s<=9007199254740991}},87730(s,o,i){var a=i(29172),u=i(27301),_=i(86009),w=_&&_.isMap,x=w?u(w):a;s.exports=x},5187(s){s.exports=function isNull(s){return null===s}},98023(s,o,i){var a=i(72552),u=i(40346);s.exports=function isNumber(s){return"number"==typeof s||u(s)&&"[object Number]"==a(s)}},23805(s){s.exports=function isObject(s){var o=typeof s;return null!=s&&("object"==o||"function"==o)}},40346(s){s.exports=function isObjectLike(s){return null!=s&&"object"==typeof s}},11331(s,o,i){var a=i(72552),u=i(28879),_=i(40346),w=Function.prototype,x=Object.prototype,C=w.toString,j=x.hasOwnProperty,L=C.call(Object);s.exports=function isPlainObject(s){if(!_(s)||"[object Object]"!=a(s))return!1;var o=u(s);if(null===o)return!0;var i=j.call(o,"constructor")&&o.constructor;return"function"==typeof i&&i instanceof i&&C.call(i)==L}},38440(s,o,i){var a=i(16038),u=i(27301),_=i(86009),w=_&&_.isSet,x=w?u(w):a;s.exports=x},85015(s,o,i){var a=i(72552),u=i(56449),_=i(40346);s.exports=function isString(s){return"string"==typeof s||!u(s)&&_(s)&&"[object String]"==a(s)}},44394(s,o,i){var a=i(72552),u=i(40346);s.exports=function isSymbol(s){return"symbol"==typeof s||u(s)&&"[object Symbol]"==a(s)}},37167(s,o,i){var a=i(4901),u=i(27301),_=i(86009),w=_&&_.isTypedArray,x=w?u(w):a;s.exports=x},47886(s,o,i){var a=i(5861),u=i(40346);s.exports=function isWeakMap(s){return u(s)&&"[object WeakMap]"==a(s)}},33855(s,o,i){var a=i(9999),u=i(15389);s.exports=function iteratee(s){return u("function"==typeof s?s:a(s,1))}},95950(s,o,i){var a=i(70695),u=i(88984),_=i(64894);s.exports=function keys(s){return _(s)?a(s):u(s)}},37241(s,o,i){var a=i(70695),u=i(72903),_=i(64894);s.exports=function keysIn(s){return _(s)?a(s,!0):u(s)}},68090(s){s.exports=function last(s){var o=null==s?0:s.length;return o?s[o-1]:void 0}},50104(s,o,i){var a=i(53661);function memoize(s,o){if("function"!=typeof s||null!=o&&"function"!=typeof o)throw new TypeError("Expected a function");var memoized=function(){var i=arguments,a=o?o.apply(this,i):i[0],u=memoized.cache;if(u.has(a))return u.get(a);var _=s.apply(this,i);return memoized.cache=u.set(a,_)||u,_};return memoized.cache=new(memoize.Cache||a),memoized}memoize.Cache=a,s.exports=memoize},55364(s,o,i){var a=i(85250),u=i(20999)((function(s,o,i){a(s,o,i)}));s.exports=u},6048(s){s.exports=function negate(s){if("function"!=typeof s)throw new TypeError("Expected a function");return function(){var o=arguments;switch(o.length){case 0:return!s.call(this);case 1:return!s.call(this,o[0]);case 2:return!s.call(this,o[0],o[1]);case 3:return!s.call(this,o[0],o[1],o[2])}return!s.apply(this,o)}}},63950(s){s.exports=function noop(){}},10124(s,o,i){var a=i(9325);s.exports=function(){return a.Date.now()}},90179(s,o,i){var a=i(34932),u=i(9999),_=i(19931),w=i(31769),x=i(21791),C=i(53138),j=i(38816),L=i(83349),B=j((function(s,o){var i={};if(null==s)return i;var j=!1;o=a(o,(function(o){return o=w(o,s),j||(j=o.length>1),o})),x(s,L(s),i),j&&(i=u(i,7,C));for(var B=o.length;B--;)_(i,o[B]);return i}));s.exports=B},50583(s,o,i){var a=i(47237),u=i(17255),_=i(28586),w=i(77797);s.exports=function property(s){return _(s)?a(w(s)):u(s)}},84195(s,o,i){var a=i(66977),u=i(38816),_=u((function(s,o){return a(s,256,void 0,void 0,void 0,o)}));s.exports=_},40860(s,o,i){var a=i(40882),u=i(80909),_=i(15389),w=i(85558),x=i(56449);s.exports=function reduce(s,o,i){var C=x(s)?a:w,j=arguments.length<3;return C(s,_(o,4),i,j,u)}},63560(s,o,i){var a=i(73170);s.exports=function set(s,o,i){return null==s?s:a(s,o,i)}},42426(s,o,i){var a=i(14248),u=i(15389),_=i(90916),w=i(56449),x=i(36800);s.exports=function some(s,o,i){var C=w(s)?a:_;return i&&x(s,o,i)&&(o=void 0),C(s,u(o,3))}},63345(s){s.exports=function stubArray(){return[]}},89935(s){s.exports=function stubFalse(){return!1}},17400(s,o,i){var a=i(99374),u=1/0;s.exports=function toFinite(s){return s?(s=a(s))===u||s===-1/0?17976931348623157e292*(s<0?-1:1):s==s?s:0:0===s?s:0}},61489(s,o,i){var a=i(17400);s.exports=function toInteger(s){var o=a(s),i=o%1;return o==o?i?o-i:o:0}},80218(s,o,i){var a=i(13222);s.exports=function toLower(s){return a(s).toLowerCase()}},99374(s,o,i){var a=i(54128),u=i(23805),_=i(44394),w=/^[-+]0x[0-9a-f]+$/i,x=/^0b[01]+$/i,C=/^0o[0-7]+$/i,j=parseInt;s.exports=function toNumber(s){if("number"==typeof s)return s;if(_(s))return NaN;if(u(s)){var o="function"==typeof s.valueOf?s.valueOf():s;s=u(o)?o+"":o}if("string"!=typeof s)return 0===s?s:+s;s=a(s);var i=x.test(s);return i||C.test(s)?j(s.slice(2),i?2:8):w.test(s)?NaN:+s}},42072(s,o,i){var a=i(34932),u=i(23007),_=i(56449),w=i(44394),x=i(61802),C=i(77797),j=i(13222);s.exports=function toPath(s){return _(s)?a(s,C):w(s)?[s]:u(x(j(s)))}},69884(s,o,i){var a=i(21791),u=i(37241);s.exports=function toPlainObject(s){return a(s,u(s))}},13222(s,o,i){var a=i(77556);s.exports=function toString(s){return null==s?"":a(s)}},55808(s,o,i){var a=i(12507)("toUpperCase");s.exports=a},66645(s,o,i){var a=i(1733),u=i(45434),_=i(13222),w=i(22225);s.exports=function words(s,o,i){return s=_(s),void 0===(o=i?void 0:o)?u(s)?w(s):a(s):s.match(o)||[]}},53758(s,o,i){var a=i(30980),u=i(56017),_=i(94033),w=i(56449),x=i(40346),C=i(80257),j=Object.prototype.hasOwnProperty;function lodash(s){if(x(s)&&!w(s)&&!(s instanceof a)){if(s instanceof u)return s;if(j.call(s,"__wrapped__"))return C(s)}return new u(s)}lodash.prototype=_.prototype,lodash.prototype.constructor=lodash,s.exports=lodash},47248(s,o,i){var a=i(16547),u=i(51234);s.exports=function zipObject(s,o){return u(s||[],o||[],a)}},43768(s,o,i){"use strict";var a=i(45981),u=i(85587);o.highlight=highlight,o.highlightAuto=function highlightAuto(s,o){var i,w,x,C,j=o||{},L=j.subset||a.listLanguages(),B=j.prefix,$=L.length,U=-1;null==B&&(B=_);if("string"!=typeof s)throw u("Expected `string` for value, got `%s`",s);w={relevance:0,language:null,value:[]},i={relevance:0,language:null,value:[]};for(;++U<$;)C=L[U],a.getLanguage(C)&&((x=highlight(C,s,o)).language=C,x.relevance>w.relevance&&(w=x),x.relevance>i.relevance&&(w=i,i=x));w.language&&(i.secondBest=w);return i},o.registerLanguage=function registerLanguage(s,o){a.registerLanguage(s,o)},o.listLanguages=function listLanguages(){return a.listLanguages()},o.registerAlias=function registerAlias(s,o){var i,u=s;o&&((u={})[s]=o);for(i in u)a.registerAliases(u[i],{languageName:i})},Emitter.prototype.addText=function text(s){var o,i,a=this.stack;if(""===s)return;o=a[a.length-1],(i=o.children[o.children.length-1])&&"text"===i.type?i.value+=s:o.children.push({type:"text",value:s})},Emitter.prototype.addKeyword=function addKeyword(s,o){this.openNode(o),this.addText(s),this.closeNode()},Emitter.prototype.addSublanguage=function addSublanguage(s,o){var i=this.stack,a=i[i.length-1],u=s.rootNode.children,_=o?{type:"element",tagName:"span",properties:{className:[o]},children:u}:u;a.children=a.children.concat(_)},Emitter.prototype.openNode=function open(s){var o=this.stack,i=this.options.classPrefix+s,a=o[o.length-1],u={type:"element",tagName:"span",properties:{className:[i]},children:[]};a.children.push(u),o.push(u)},Emitter.prototype.closeNode=function close(){this.stack.pop()},Emitter.prototype.closeAllNodes=noop,Emitter.prototype.finalize=noop,Emitter.prototype.toHTML=function toHtmlNoop(){return""};var _="hljs-";function highlight(s,o,i){var w,x=a.configure({}),C=(i||{}).prefix;if("string"!=typeof s)throw u("Expected `string` for name, got `%s`",s);if(!a.getLanguage(s))throw u("Unknown language: `%s` is not registered",s);if("string"!=typeof o)throw u("Expected `string` for value, got `%s`",o);if(null==C&&(C=_),a.configure({__emitter:Emitter,classPrefix:C}),w=a.highlight(o,{language:s,ignoreIllegals:!0}),a.configure(x||{}),w.errorRaised)throw w.errorRaised;return{relevance:w.relevance,language:w.language,value:w.emitter.rootNode.children}}function Emitter(s){this.options=s,this.rootNode={children:[]},this.stack=[this.rootNode]}function noop(){}},71514(s){"use strict";s.exports=Math.abs},58968(s){"use strict";s.exports=Math.floor},94459(s){"use strict";s.exports=Number.isNaN||function isNaN(s){return s!=s}},6188(s){"use strict";s.exports=Math.max},68002(s){"use strict";s.exports=Math.min},75880(s){"use strict";s.exports=Math.pow},70414(s){"use strict";s.exports=Math.round},73093(s,o,i){"use strict";var a=i(94459);s.exports=function sign(s){return a(s)||0===s?s:s<0?-1:1}},92340(s,o,i){const a=i(6048);function coerceElementMatchingCallback(s){return"string"==typeof s?o=>o.element===s:s.constructor&&s.extend?o=>o instanceof s:s}class ArraySlice{constructor(s){this.elements=s||[]}toValue(){return this.elements.map((s=>s.toValue()))}map(s,o){return this.elements.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(s,o))}reject(s,o){return s=coerceElementMatchingCallback(s),new ArraySlice(this.elements.filter(a(s),o))}find(s,o){return s=coerceElementMatchingCallback(s),this.elements.find(s,o)}forEach(s,o){this.elements.forEach(s,o)}reduce(s,o){return this.elements.reduce(s,o)}includes(s){return this.elements.some((o=>o.equals(s)))}shift(){return this.elements.shift()}unshift(s){this.elements.unshift(this.refract(s))}push(s){return this.elements.push(this.refract(s)),this}add(s){this.push(s)}get(s){return this.elements[s]}getValue(s){const o=this.elements[s];if(o)return o.toValue()}get length(){return this.elements.length}get isEmpty(){return 0===this.elements.length}get first(){return this.elements[0]}}"undefined"!=typeof Symbol&&(ArraySlice.prototype[Symbol.iterator]=function symbol(){return this.elements[Symbol.iterator]()}),s.exports=ArraySlice},55973(s){class KeyValuePair{constructor(s,o){this.key=s,this.value=o}clone(){const s=new KeyValuePair;return this.key&&(s.key=this.key.clone()),this.value&&(s.value=this.value.clone()),s}}s.exports=KeyValuePair},3110(s,o,i){const a=i(5187),u=i(85015),_=i(98023),w=i(53812),x=i(23805),C=i(85105),j=i(86804);class Namespace{constructor(s){this.elementMap={},this.elementDetection=[],this.Element=j.Element,this.KeyValuePair=j.KeyValuePair,s&&s.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(s){return s.namespace&&s.namespace({base:this}),s.load&&s.load({base:this}),this}useDefault(){return this.register("null",j.NullElement).register("string",j.StringElement).register("number",j.NumberElement).register("boolean",j.BooleanElement).register("array",j.ArrayElement).register("object",j.ObjectElement).register("member",j.MemberElement).register("ref",j.RefElement).register("link",j.LinkElement),this.detect(a,j.NullElement,!1).detect(u,j.StringElement,!1).detect(_,j.NumberElement,!1).detect(w,j.BooleanElement,!1).detect(Array.isArray,j.ArrayElement,!1).detect(x,j.ObjectElement,!1),this}register(s,o){return this._elements=void 0,this.elementMap[s]=o,this}unregister(s){return this._elements=void 0,delete this.elementMap[s],this}detect(s,o,i){return void 0===i||i?this.elementDetection.unshift([s,o]):this.elementDetection.push([s,o]),this}toElement(s){if(s instanceof this.Element)return s;let o;for(let i=0;i{const o=s[0].toUpperCase()+s.substr(1);this._elements[o]=this.elementMap[s]}))),this._elements}get serialiser(){return new C(this)}}C.prototype.Namespace=Namespace,s.exports=Namespace},10866(s,o,i){const a=i(6048),u=i(92340);class ObjectSlice extends u{map(s,o){return this.elements.map((i=>s.bind(o)(i.value,i.key,i)))}filter(s,o){return new ObjectSlice(this.elements.filter((i=>s.bind(o)(i.value,i.key,i))))}reject(s,o){return this.filter(a(s.bind(o)))}forEach(s,o){return this.elements.forEach(((i,a)=>{s.bind(o)(i.value,i.key,i,a)}))}keys(){return this.map(((s,o)=>o.toValue()))}values(){return this.map((s=>s.toValue()))}}s.exports=ObjectSlice},86804(s,o,i){const a=i(10316),u=i(41067),_=i(71167),w=i(40239),x=i(12242),C=i(6233),j=i(87726),L=i(61045),B=i(86303),$=i(14540),U=i(92340),V=i(10866),z=i(55973);function refract(s){if(s instanceof a)return s;if("string"==typeof s)return new _(s);if("number"==typeof s)return new w(s);if("boolean"==typeof s)return new x(s);if(null===s)return new u;if(Array.isArray(s))return new C(s.map(refract));if("object"==typeof s){return new L(s)}return s}a.prototype.ObjectElement=L,a.prototype.RefElement=$,a.prototype.MemberElement=j,a.prototype.refract=refract,U.prototype.refract=refract,s.exports={Element:a,NullElement:u,StringElement:_,NumberElement:w,BooleanElement:x,ArrayElement:C,MemberElement:j,ObjectElement:L,LinkElement:B,RefElement:$,refract,ArraySlice:U,ObjectSlice:V,KeyValuePair:z}},86303(s,o,i){const a=i(10316);s.exports=class LinkElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="link"}get relation(){return this.attributes.get("relation")}set relation(s){this.attributes.set("relation",s)}get href(){return this.attributes.get("href")}set href(s){this.attributes.set("href",s)}}},14540(s,o,i){const a=i(10316);s.exports=class RefElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(s){this.attributes.set("path",s)}}},34035(s,o,i){const a=i(3110),u=i(86804);o.g$=a,o.KeyValuePair=i(55973),o.G6=u.ArraySlice,o.ot=u.ObjectSlice,o.Hg=u.Element,o.Om=u.StringElement,o.kT=u.NumberElement,o.bd=u.BooleanElement,o.Os=u.NullElement,o.wE=u.ArrayElement,o.Sh=u.ObjectElement,o.Pr=u.MemberElement,o.sI=u.RefElement,o.Ft=u.LinkElement,o.e=u.refract,i(85105),i(75147)},6233(s,o,i){const a=i(6048),u=i(10316),_=i(92340);class ArrayElement extends u{constructor(s,o,i){super(s||[],o,i),this.element="array"}primitive(){return"array"}get(s){return this.content[s]}getValue(s){const o=this.get(s);if(o)return o.toValue()}getIndex(s){return this.content[s]}set(s,o){return this.content[s]=this.refract(o),this}remove(s){const o=this.content.splice(s,1);return o.length?o[0]:null}map(s,o){return this.content.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return new _(this.content.filter(s,o))}reject(s,o){return this.filter(a(s),o)}reduce(s,o){let i,a;void 0!==o?(i=0,a=this.refract(o)):(i=1,a="object"===this.primitive()?this.first.value:this.first);for(let o=i;o{s.bind(o)(i,this.refract(a))}))}shift(){return this.content.shift()}unshift(s){this.content.unshift(this.refract(s))}push(s){return this.content.push(this.refract(s)),this}add(s){this.push(s)}findElements(s,o){const i=o||{},a=!!i.recursive,u=void 0===i.results?[]:i.results;return this.forEach(((o,i,_)=>{a&&void 0!==o.findElements&&o.findElements(s,{results:u,recursive:a}),s(o,i,_)&&u.push(o)})),u}find(s){return new _(this.findElements(s,{recursive:!0}))}findByElement(s){return this.find((o=>o.element===s))}findByClass(s){return this.find((o=>o.classes.includes(s)))}getById(s){return this.find((o=>o.id.toValue()===s)).first}includes(s){return this.content.some((o=>o.equals(s)))}contains(s){return this.includes(s)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(s){return new this.constructor(this.content.concat(s.content))}"fantasy-land/concat"(s){return this.concat(s)}"fantasy-land/map"(s){return new this.constructor(this.map(s))}"fantasy-land/chain"(s){return this.map((o=>s(o)),this).reduce(((s,o)=>s.concat(o)),this.empty())}"fantasy-land/filter"(s){return new this.constructor(this.content.filter(s))}"fantasy-land/reduce"(s,o){return this.content.reduce(s,o)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}ArrayElement.empty=function empty(){return new this},ArrayElement["fantasy-land/empty"]=ArrayElement.empty,"undefined"!=typeof Symbol&&(ArrayElement.prototype[Symbol.iterator]=function symbol(){return this.content[Symbol.iterator]()}),s.exports=ArrayElement},12242(s,o,i){const a=i(10316);s.exports=class BooleanElement extends a{constructor(s,o,i){super(s,o,i),this.element="boolean"}primitive(){return"boolean"}}},10316(s,o,i){const a=i(2404),u=i(55973),_=i(92340);class Element{constructor(s,o,i){o&&(this.meta=o),i&&(this.attributes=i),this.content=s}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this,this.meta.freeze()),this._attributes&&(this.attributes.parent=this,this.attributes.freeze()),this.children.forEach((s=>{s.parent=this,s.freeze()}),this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const s=new this.constructor;return s.element=this.element,this.meta.length&&(s._meta=this.meta.clone()),this.attributes.length&&(s._attributes=this.attributes.clone()),this.content?this.content.clone?s.content=this.content.clone():Array.isArray(this.content)?s.content=this.content.map((s=>s.clone())):s.content=this.content:s.content=this.content,s}toValue(){return this.content instanceof Element?this.content.toValue():this.content instanceof u?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map((s=>s.toValue()),this):this.content}toRef(s){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const o=new this.RefElement(this.id.toValue());return s&&(o.path=s),o}findRecursive(...s){if(arguments.length>1&&!this.isFrozen)throw new Error("Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`");const o=s.pop();let i=new _;const append=(s,o)=>(s.push(o),s),checkElement=(s,i)=>{i.element===o&&s.push(i);const a=i.findRecursive(o);return a&&a.reduce(append,s),i.content instanceof u&&(i.content.key&&checkElement(s,i.content.key),i.content.value&&checkElement(s,i.content.value)),s};return this.content&&(this.content.element&&checkElement(i,this.content),Array.isArray(this.content)&&this.content.reduce(checkElement,i)),s.isEmpty||(i=i.filter((o=>{let i=o.parents.map((s=>s.element));for(const o in s){const a=s[o],u=i.indexOf(a);if(-1===u)return!1;i=i.splice(0,u)}return!0}))),i}set(s){return this.content=s,this}equals(s){return a(this.toValue(),s)}getMetaProperty(s,o){if(!this.meta.hasKey(s)){if(this.isFrozen){const s=this.refract(o);return s.freeze(),s}this.meta.set(s,o)}return this.meta.get(s)}setMetaProperty(s,o){this.meta.set(s,o)}get element(){return this._storedElement||"element"}set element(s){this._storedElement=s}get content(){return this._content}set content(s){if(s instanceof Element)this._content=s;else if(s instanceof _)this.content=s.elements;else if("string"==typeof s||"number"==typeof s||"boolean"==typeof s||"null"===s||null==s)this._content=s;else if(s instanceof u)this._content=s;else if(Array.isArray(s))this._content=s.map(this.refract);else{if("object"!=typeof s)throw new Error("Cannot set content to given value");this._content=Object.keys(s).map((o=>new this.MemberElement(o,s[o])))}}get meta(){if(!this._meta){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._meta=new this.ObjectElement}return this._meta}set meta(s){s instanceof this.ObjectElement?this._meta=s:this.meta.set(s||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._attributes=new this.ObjectElement}return this._attributes}set attributes(s){s instanceof this.ObjectElement?this._attributes=s:this.attributes.set(s||{})}get id(){return this.getMetaProperty("id","")}set id(s){this.setMetaProperty("id",s)}get classes(){return this.getMetaProperty("classes",[])}set classes(s){this.setMetaProperty("classes",s)}get title(){return this.getMetaProperty("title","")}set title(s){this.setMetaProperty("title",s)}get description(){return this.getMetaProperty("description","")}set description(s){this.setMetaProperty("description",s)}get links(){return this.getMetaProperty("links",[])}set links(s){this.setMetaProperty("links",s)}get isFrozen(){return Object.isFrozen(this)}get parents(){let{parent:s}=this;const o=new _;for(;s;)o.push(s),s=s.parent;return o}get children(){if(Array.isArray(this.content))return new _(this.content);if(this.content instanceof u){const s=new _([this.content.key]);return this.content.value&&s.push(this.content.value),s}return this.content instanceof Element?new _([this.content]):new _}get recursiveChildren(){const s=new _;return this.children.forEach((o=>{s.push(o),o.recursiveChildren.forEach((o=>{s.push(o)}))})),s}}s.exports=Element},87726(s,o,i){const a=i(55973),u=i(10316);s.exports=class MemberElement extends u{constructor(s,o,i,u){super(new a,i,u),this.element="member",this.key=s,this.value=o}get key(){return this.content.key}set key(s){this.content.key=this.refract(s)}get value(){return this.content.value}set value(s){this.content.value=this.refract(s)}}},41067(s,o,i){const a=i(10316);s.exports=class NullElement extends a{constructor(s,o,i){super(s||null,o,i),this.element="null"}primitive(){return"null"}set(){return new Error("Cannot set the value of null")}}},40239(s,o,i){const a=i(10316);s.exports=class NumberElement extends a{constructor(s,o,i){super(s,o,i),this.element="number"}primitive(){return"number"}}},61045(s,o,i){const a=i(6048),u=i(23805),_=i(6233),w=i(87726),x=i(10866);s.exports=class ObjectElement extends _{constructor(s,o,i){super(s||[],o,i),this.element="object"}primitive(){return"object"}toValue(){return this.content.reduce(((s,o)=>(s[o.key.toValue()]=o.value?o.value.toValue():void 0,s)),{})}get(s){const o=this.getMember(s);if(o)return o.value}getMember(s){if(void 0!==s)return this.content.find((o=>o.key.toValue()===s))}remove(s){let o=null;return this.content=this.content.filter((i=>i.key.toValue()!==s||(o=i,!1))),o}getKey(s){const o=this.getMember(s);if(o)return o.key}set(s,o){if(u(s))return Object.keys(s).forEach((o=>{this.set(o,s[o])})),this;const i=s,a=this.getMember(i);return a?a.value=o:this.content.push(new w(i,o)),this}keys(){return this.content.map((s=>s.key.toValue()))}values(){return this.content.map((s=>s.value.toValue()))}hasKey(s){return this.content.some((o=>o.key.equals(s)))}items(){return this.content.map((s=>[s.key.toValue(),s.value.toValue()]))}map(s,o){return this.content.map((i=>s.bind(o)(i.value,i.key,i)))}compactMap(s,o){const i=[];return this.forEach(((a,u,_)=>{const w=s.bind(o)(a,u,_);w&&i.push(w)})),i}filter(s,o){return new x(this.content).filter(s,o)}reject(s,o){return this.filter(a(s),o)}forEach(s,o){return this.content.forEach((i=>s.bind(o)(i.value,i.key,i)))}}},71167(s,o,i){const a=i(10316);s.exports=class StringElement extends a{constructor(s,o,i){super(s,o,i),this.element="string"}primitive(){return"string"}get length(){return this.content.length}}},75147(s,o,i){const a=i(85105);s.exports=class JSON06Serialiser extends a{serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);let o;s._attributes&&s.attributes.get("variable")&&(o=s.attributes.get("variable"));const i={element:s.element};s._meta&&s._meta.length>0&&(i.meta=this.serialiseObject(s.meta));const a="enum"===s.element||-1!==s.attributes.keys().indexOf("enumerations");if(a){const o=this.enumSerialiseAttributes(s);o&&(i.attributes=o)}else if(s._attributes&&s._attributes.length>0){let{attributes:a}=s;a.get("metadata")&&(a=a.clone(),a.set("meta",a.get("metadata")),a.remove("metadata")),"member"===s.element&&o&&(a=a.clone(),a.remove("variable")),a.length>0&&(i.attributes=this.serialiseObject(a))}if(a)i.content=this.enumSerialiseContent(s,i);else if(this[`${s.element}SerialiseContent`])i.content=this[`${s.element}SerialiseContent`](s,i);else if(void 0!==s.content){let a;o&&s.content.key?(a=s.content.clone(),a.key.attributes.set("variable",o),a=this.serialiseContent(a)):a=this.serialiseContent(s.content),this.shouldSerialiseContent(s,a)&&(i.content=a)}else this.shouldSerialiseContent(s,s.content)&&s instanceof this.namespace.elements.Array&&(i.content=[]);return i}shouldSerialiseContent(s,o){return"parseResult"===s.element||"httpRequest"===s.element||"httpResponse"===s.element||"category"===s.element||"link"===s.element||void 0!==o&&(!Array.isArray(o)||0!==o.length)}refSerialiseContent(s,o){return delete o.attributes,{href:s.toValue(),path:s.path.toValue()}}sourceMapSerialiseContent(s){return s.toValue()}dataStructureSerialiseContent(s){return[this.serialiseContent(s.content)]}enumSerialiseAttributes(s){const o=s.attributes.clone(),i=o.remove("enumerations")||new this.namespace.elements.Array([]),a=o.get("default");let u=o.get("samples")||new this.namespace.elements.Array([]);if(a&&a.content&&(a.content.attributes&&a.content.attributes.remove("typeAttributes"),o.set("default",new this.namespace.elements.Array([a.content]))),u.forEach((s=>{s.content&&s.content.element&&s.content.attributes.remove("typeAttributes")})),s.content&&0!==i.length&&u.unshift(s.content),u=u.map((s=>s instanceof this.namespace.elements.Array?[s]:new this.namespace.elements.Array([s.content]))),u.length&&o.set("samples",u),o.length>0)return this.serialiseObject(o)}enumSerialiseContent(s){if(s._attributes){const o=s.attributes.get("enumerations");if(o&&o.length>0)return o.content.map((s=>{const o=s.clone();return o.attributes.remove("typeAttributes"),this.serialise(o)}))}if(s.content){const o=s.content.clone();return o.attributes.remove("typeAttributes"),[this.serialise(o)]}return[]}deserialise(s){if("string"==typeof s)return new this.namespace.elements.String(s);if("number"==typeof s)return new this.namespace.elements.Number(s);if("boolean"==typeof s)return new this.namespace.elements.Boolean(s);if(null===s)return new this.namespace.elements.Null;if(Array.isArray(s))return new this.namespace.elements.Array(s.map(this.deserialise,this));const o=this.namespace.getElementClass(s.element),i=new o;i.element!==s.element&&(i.element=s.element),s.meta&&this.deserialiseObject(s.meta,i.meta),s.attributes&&this.deserialiseObject(s.attributes,i.attributes);const a=this.deserialiseContent(s.content);if(void 0===a&&null!==i.content||(i.content=a),"enum"===i.element){i.content&&i.attributes.set("enumerations",i.content);let s=i.attributes.get("samples");if(i.attributes.remove("samples"),s){const a=s;s=new this.namespace.elements.Array,a.forEach((a=>{a.forEach((a=>{const u=new o(a);u.element=i.element,s.push(u)}))}));const u=s.shift();i.content=u?u.content:void 0,i.attributes.set("samples",s)}else i.content=void 0;let a=i.attributes.get("default");if(a&&a.length>0){a=a.get(0);const s=new o(a);s.element=i.element,i.attributes.set("default",s)}}else if("dataStructure"===i.element&&Array.isArray(i.content))[i.content]=i.content;else if("category"===i.element){const s=i.attributes.get("meta");s&&(i.attributes.set("metadata",s),i.attributes.remove("meta"))}else"member"===i.element&&i.key&&i.key._attributes&&i.key._attributes.getValue("variable")&&(i.attributes.set("variable",i.key.attributes.get("variable")),i.key.attributes.remove("variable"));return i}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const o={key:this.serialise(s.key)};return s.value&&(o.value=this.serialise(s.value)),o}return s&&s.map?s.map(this.serialise,this):s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const o=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(o.value=this.deserialise(s.value)),o}if(s.map)return s.map(this.deserialise,this)}return s}shouldRefract(s){return!!(s._attributes&&s.attributes.keys().length||s._meta&&s.meta.keys().length)||"enum"!==s.element&&(s.element!==s.primitive()||"member"===s.element)}convertKeyToRefract(s,o){return this.shouldRefract(o)?this.serialise(o):"enum"===o.element?this.serialiseEnum(o):"array"===o.element?o.map((o=>this.shouldRefract(o)||"default"===s?this.serialise(o):"array"===o.element||"object"===o.element||"enum"===o.element?o.children.map((s=>this.serialise(s))):o.toValue())):"object"===o.element?(o.content||[]).map(this.serialise,this):o.toValue()}serialiseEnum(s){return s.children.map((s=>this.serialise(s)))}serialiseObject(s){const o={};return s.forEach(((s,i)=>{if(s){const a=i.toValue();o[a]=this.convertKeyToRefract(a,s)}})),o}deserialiseObject(s,o){Object.keys(s).forEach((i=>{o.set(i,this.deserialise(s[i]))}))}}},85105(s){s.exports=class JSONSerialiser{constructor(s){this.namespace=s||new this.Namespace}serialise(s){if(!(s instanceof this.namespace.elements.Element))throw new TypeError(`Given element \`${s}\` is not an Element instance`);const o={element:s.element};s._meta&&s._meta.length>0&&(o.meta=this.serialiseObject(s.meta)),s._attributes&&s._attributes.length>0&&(o.attributes=this.serialiseObject(s.attributes));const i=this.serialiseContent(s.content);return void 0!==i&&(o.content=i),o}deserialise(s){if(!s.element)throw new Error("Given value is not an object containing an element name");const o=new(this.namespace.getElementClass(s.element));o.element!==s.element&&(o.element=s.element),s.meta&&this.deserialiseObject(s.meta,o.meta),s.attributes&&this.deserialiseObject(s.attributes,o.attributes);const i=this.deserialiseContent(s.content);return void 0===i&&null!==o.content||(o.content=i),o}serialiseContent(s){if(s instanceof this.namespace.elements.Element)return this.serialise(s);if(s instanceof this.namespace.KeyValuePair){const o={key:this.serialise(s.key)};return s.value&&(o.value=this.serialise(s.value)),o}if(s&&s.map){if(0===s.length)return;return s.map(this.serialise,this)}return s}deserialiseContent(s){if(s){if(s.element)return this.deserialise(s);if(s.key){const o=new this.namespace.KeyValuePair(this.deserialise(s.key));return s.value&&(o.value=this.deserialise(s.value)),o}if(s.map)return s.map(this.deserialise,this)}return s}serialiseObject(s){const o={};if(s.forEach(((s,i)=>{s&&(o[i.toValue()]=this.serialise(s))})),0!==Object.keys(o).length)return o}deserialiseObject(s,o){Object.keys(s).forEach((i=>{o.set(i,this.deserialise(s[i]))}))}}},76578(s){"use strict";s.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]},65606(s){var o,i,a=s.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(s){if(o===setTimeout)return setTimeout(s,0);if((o===defaultSetTimout||!o)&&setTimeout)return o=setTimeout,setTimeout(s,0);try{return o(s,0)}catch(i){try{return o.call(null,s,0)}catch(i){return o.call(this,s,0)}}}!function(){try{o="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(s){o=defaultSetTimout}try{i="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(s){i=defaultClearTimeout}}();var u,_=[],w=!1,x=-1;function cleanUpNextTick(){w&&u&&(w=!1,u.length?_=u.concat(_):x=-1,_.length&&drainQueue())}function drainQueue(){if(!w){var s=runTimeout(cleanUpNextTick);w=!0;for(var o=_.length;o;){for(u=_,_=[];++x1)for(var i=1;i_)throw new RangeError("requested too many random bytes");var i=w.allocUnsafe(s);if(s>0)if(s>u)for(var C=0;C=0||(u[i]=s[i]);return u}(s,o);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);for(a=0;a<_.length;a++)i=_[a],o.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(s,i)&&(u[i]=s[i])}return u}function _defineProperties(s,o){for(var i=0;i=0||(u[i]=s[i]);return u}(s,o);if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(s);for(a=0;a<_.length;a++)i=_[a],o.indexOf(i)>=0||Object.prototype.propertyIsEnumerable.call(s,i)&&(u[i]=s[i])}return u}function ownKeys(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter((function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable}))),i.push.apply(i,a)}return i}function _objectSpread(s){for(var o=1;o=a?i.notify(s):o.length>u.length&&i.notify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:""})}))}))})),_defineProperty(_assertThisInitialized(i),"onKeyDown",(function(s){"Enter"===s.key&&i.forceNotify(s);var o=i.props.onKeyDown;o&&(s.persist(),o(s))})),_defineProperty(_assertThisInitialized(i),"onBlur",(function(s){i.forceNotify(s);var o=i.props.onBlur;o&&(s.persist(),o(s))})),_defineProperty(_assertThisInitialized(i),"createNotifier",(function(s){if(s<0)i.notify=function(){return null};else if(0===s)i.notify=i.doNotify;else{var o=(0,u.default)((function(s){i.isDebouncing=!1,i.doNotify(s)}),s);i.notify=function(s){i.isDebouncing=!0,o(s)},i.flush=function(){return o.flush()},i.cancel=function(){i.isDebouncing=!1,o.cancel()}}})),_defineProperty(_assertThisInitialized(i),"doNotify",(function(){i.props.onChange.apply(void 0,arguments)})),_defineProperty(_assertThisInitialized(i),"forceNotify",(function(s){var o=i.props.debounceTimeout;if(i.isDebouncing||!(o>0)){i.cancel&&i.cancel();var a=i.state.value,u=i.props.minLength;a.length>=u?i.doNotify(s):i.doNotify(_objectSpread(_objectSpread({},s),{},{target:_objectSpread(_objectSpread({},s.target),{},{value:a})}))}})),i.isDebouncing=!1,i.state={value:void 0===s.value||null===s.value?"":s.value};var a=i.props.debounceTimeout;return i.createNotifier(a),i}return function _createClass(s,o,i){return o&&_defineProperties(s.prototype,o),i&&_defineProperties(s,i),Object.defineProperty(s,"prototype",{writable:!1}),s}(DebounceInput,[{key:"componentDidUpdate",value:function componentDidUpdate(s){if(!this.isDebouncing){var o=this.props,i=o.value,a=o.debounceTimeout,u=s.debounceTimeout,_=s.value,w=this.state.value;void 0!==i&&_!==i&&w!==i&&this.setState({value:i}),a!==u&&this.createNotifier(a)}}},{key:"componentWillUnmount",value:function componentWillUnmount(){this.flush&&this.flush()}},{key:"render",value:function render(){var s,o,i=this.props,u=i.element,w=(i.onChange,i.value,i.minLength,i.debounceTimeout,i.forceNotifyByEnter),x=i.forceNotifyOnBlur,C=i.onKeyDown,j=i.onBlur,L=i.inputRef,B=_objectWithoutProperties(i,_),$=this.state.value;s=w?{onKeyDown:this.onKeyDown}:C?{onKeyDown:C}:{},o=x?{onBlur:this.onBlur}:j?{onBlur:j}:{};var U=L?{ref:L}:{};return a.default.createElement(u,_objectSpread(_objectSpread(_objectSpread(_objectSpread({},B),{},{onChange:this.onChange,value:$},s),o),U))}}]),DebounceInput}(a.default.PureComponent);o.DebounceInput=w,_defineProperty(w,"defaultProps",{element:"input",type:"text",onKeyDown:void 0,onBlur:void 0,value:void 0,minLength:0,debounceTimeout:100,forceNotifyByEnter:!0,forceNotifyOnBlur:!0,inputRef:void 0})},24677(s,o,i){"use strict";var a=i(81214).DebounceInput;a.DebounceInput=a,s.exports=a},22551(s,o,i){"use strict";var a=i(96540),u=i(69982);function p(s){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+s,i=1;i
\n )\n\n return (\n \n \n {braceOpen}\n {!isRef ? null : }\n \n {\n \n \n {!description ? null : (\n \n \n \n \n )}\n {externalDocsUrl && (\n \n \n \n \n )}\n {!deprecated ? null : (\n \n \n \n \n )}\n {!(properties && properties.size)\n ? null\n : properties\n .entrySeq()\n .filter(([, value]) => {\n return (\n (!value.get(\"readOnly\") || includeReadOnly) &&\n (!value.get(\"writeOnly\") || includeWriteOnly)\n )\n })\n .map(([key, value]) => {\n let isDeprecated = isOAS3() && value.get(\"deprecated\")\n let isRequired =\n List.isList(requiredProperties) &&\n requiredProperties.contains(key)\n\n let classNames = [\"property-row\"]\n\n if (isDeprecated) {\n classNames.push(\"deprecated\")\n }\n\n if (isRequired) {\n classNames.push(\"required\")\n }\n\n return (\n \n \n \n \n )\n })\n .toArray()}\n {extensions.size === 0 ? null : (\n <>\n \n \n \n \n \n )}\n {!additionalProperties ||\n !additionalProperties.size ? null : (\n \n \n \n \n )}\n {!allOf ? null : (\n \n \n \n \n )}\n {!anyOf ? null : (\n \n \n \n \n )}\n {!oneOf ? null : (\n \n \n \n \n )}\n {!not ? null : (\n \n \n \n \n )}\n \n
description:\n \n
externalDocs:\n \n {externalDocsDescription || externalDocsUrl}\n \n
deprecated:true
\n {key}\n {isRequired && *}\n \n \n
 
{\"< * >:\"}\n \n
{\"allOf ->\"}\n {allOf.map((schema, k) => {\n return (\n
\n \n
\n )\n })}\n
{\"anyOf ->\"}\n {anyOf.map((schema, k) => {\n return (\n
\n \n
\n )\n })}\n
{\"oneOf ->\"}\n {oneOf.map((schema, k) => {\n return (\n
\n \n
\n )\n })}\n
{\"not ->\"}\n
\n \n
\n
\n }\n
\n {braceClose}\n \n {infoProperties.size\n ? infoProperties\n .entrySeq()\n .map(([key, v]) => (\n \n ))\n : null}\n
\n )\n }\n}\n","import React, { Component } from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport { sanitizeUrl } from \"core/utils/url\"\n\nconst propClass = \"property\"\n\nexport default class ArrayModel extends Component {\n static propTypes = {\n schema: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n specSelectors: PropTypes.object.isRequired,\n name: PropTypes.string,\n displayName: PropTypes.string,\n required: PropTypes.bool,\n expandDepth: PropTypes.number,\n specPath: ImPropTypes.list.isRequired,\n depth: PropTypes.number,\n includeReadOnly: PropTypes.bool,\n includeWriteOnly: PropTypes.bool,\n }\n\n render(){\n let { getComponent, getConfigs, schema, depth, expandDepth, name, displayName, specPath } = this.props\n let description = schema.get(\"description\")\n let items = schema.get(\"items\")\n let title = schema.get(\"title\") || displayName || name\n let properties = schema.filter( ( v, key) => [\"type\", \"items\", \"description\", \"$$ref\", \"externalDocs\"].indexOf(key) === -1 )\n let externalDocsUrl = schema.getIn([\"externalDocs\", \"url\"])\n let externalDocsDescription = schema.getIn([\"externalDocs\", \"description\"])\n\n\n const Markdown = getComponent(\"Markdown\", true)\n const ModelCollapse = getComponent(\"ModelCollapse\")\n const Model = getComponent(\"Model\")\n const Property = getComponent(\"Property\")\n const Link = getComponent(\"Link\")\n\n const titleEl = title &&\n \n { title }\n \n\n /*\n Note: we set `name={null}` in below because we don't want\n the name of the current Model passed (and displayed) as the name of the array element Model\n */\n\n return \n \n [\n {\n properties.size ? properties.entrySeq().map( ( [ key, v ] ) => ) : null\n }\n {\n !description ? (properties.size ?
: null) :\n \n }\n { externalDocsUrl &&\n
\n {externalDocsDescription || externalDocsUrl}\n
\n }\n \n \n \n ]\n
\n
\n }\n}\n","/**\n * @prettier\n */\nimport React, { Component } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { getExtensions } from \"core/utils\"\nimport { sanitizeUrl } from \"core/utils/url\"\n\nconst propClass = \"property primitive\"\n\nexport default class Primitive extends Component {\n static propTypes = {\n schema: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n name: PropTypes.string,\n displayName: PropTypes.string,\n depth: PropTypes.number,\n expandDepth: PropTypes.number,\n }\n\n render() {\n let {\n schema,\n getComponent,\n getConfigs,\n name,\n displayName,\n depth,\n expandDepth,\n } = this.props\n\n const { showExtensions } = getConfigs()\n\n if (!schema || !schema.get) {\n // don't render if schema isn't correctly formed\n return
\n }\n\n let type = schema.get(\"type\")\n let format = schema.get(\"format\")\n let xml = schema.get(\"xml\")\n let enumArray = schema.get(\"enum\")\n let title = schema.get(\"title\") || displayName || name\n let description = schema.get(\"description\")\n const extensions = getExtensions(schema)\n\n let properties = schema\n .filter(\n (_, key) =>\n [\n \"enum\",\n \"type\",\n \"format\",\n \"description\",\n \"$$ref\",\n \"externalDocs\",\n ].indexOf(key) === -1\n )\n .filterNot((_, key) => extensions.has(key))\n let externalDocsUrl = schema.getIn([\"externalDocs\", \"url\"])\n let externalDocsDescription = schema.getIn([\"externalDocs\", \"description\"])\n\n const Markdown = getComponent(\"Markdown\", true)\n const EnumModel = getComponent(\"EnumModel\")\n const Property = getComponent(\"Property\")\n const ModelCollapse = getComponent(\"ModelCollapse\")\n const Link = getComponent(\"Link\")\n const ModelExtensions = getComponent(\"ModelExtensions\")\n\n const titleEl = title && (\n \n {title}\n \n )\n\n return (\n \n \n \n {name && depth > 1 && {title}}\n {type}\n {format && (${format})}\n {properties.size\n ? properties\n .entrySeq()\n .map(([key, v]) => (\n \n ))\n : null}\n {showExtensions && extensions.size > 0 ? (\n \n ) : null}\n {!description ? null : }\n {externalDocsUrl && (\n
\n \n {externalDocsDescription || externalDocsUrl}\n \n
\n )}\n {xml && xml.size ? (\n \n
\n xml:\n {xml\n .entrySeq()\n .map(([key, v]) => (\n \n
\n    {key}: {String(v)}\n
\n ))\n .toArray()}\n
\n ) : null}\n {enumArray && (\n \n )}\n
\n \n
\n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport default class Schemes extends React.Component {\n\n static propTypes = {\n specActions: PropTypes.object.isRequired,\n schemes: PropTypes.object.isRequired,\n currentScheme: PropTypes.string.isRequired,\n path: PropTypes.string,\n method: PropTypes.string,\n }\n\n UNSAFE_componentWillMount() {\n let { schemes } = this.props\n\n //fire 'change' event to set default 'value' of select\n this.setScheme(schemes.first())\n }\n\n UNSAFE_componentWillReceiveProps(nextProps) {\n if ( !this.props.currentScheme || !nextProps.schemes.includes(this.props.currentScheme) ) {\n // if we don't have a selected currentScheme or if our selected scheme is no longer an option,\n // then fire 'change' event and select the first scheme in the list of options\n this.setScheme(nextProps.schemes.first())\n }\n }\n\n onChange =( e ) => {\n this.setScheme( e.target.value )\n }\n\n setScheme = ( value ) => {\n let { path, method, specActions } = this.props\n\n specActions.setScheme( value, path, method )\n }\n\n render() {\n let { schemes, currentScheme } = this.props\n\n return (\n \n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport default class SchemesContainer extends React.Component {\n\n static propTypes = {\n specActions: PropTypes.object.isRequired,\n specSelectors: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired\n }\n\n render () {\n const {specActions, specSelectors, getComponent} = this.props\n\n const currentScheme = specSelectors.operationScheme()\n const schemes = specSelectors.schemes()\n\n const Schemes = getComponent(\"schemes\")\n\n const schemesArePresent = schemes && schemes.size\n\n return schemesArePresent ? (\n \n ) : null\n }\n}\n","import React, { PureComponent, Component } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { List, fromJS } from \"immutable\"\nimport cx from \"classnames\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport DebounceInput from \"react-debounce-input\"\nimport { stringify, isImmutable } from \"core/utils\"\n\nconst noop = ()=> {}\nconst JsonSchemaPropShape = {\n getComponent: PropTypes.func.isRequired,\n value: PropTypes.any,\n onChange: PropTypes.func,\n keyName: PropTypes.any,\n fn: PropTypes.object.isRequired,\n schema: PropTypes.object,\n errors: ImPropTypes.list,\n required: PropTypes.bool,\n dispatchInitialValue: PropTypes.bool,\n description: PropTypes.any,\n disabled: PropTypes.bool,\n}\n\nconst JsonSchemaDefaultProps = {\n value: \"\",\n onChange: noop,\n schema: {},\n keyName: \"\",\n required: false,\n errors: List()\n}\n\nexport class JsonSchemaForm extends Component {\n\n static propTypes = JsonSchemaPropShape\n static defaultProps = JsonSchemaDefaultProps\n\n componentDidMount() {\n const { dispatchInitialValue, value, onChange } = this.props\n if(dispatchInitialValue) {\n onChange(value)\n } else if(dispatchInitialValue === false) {\n onChange(\"\")\n }\n }\n\n render() {\n let { schema, errors, value, onChange, getComponent, fn, disabled } = this.props\n const format = schema && schema.get ? schema.get(\"format\") : null\n const type = schema && schema.get ? schema.get(\"type\") : null\n const objectType = fn.getSchemaObjectType(schema)\n const isFileUploadIntended = fn.isFileUploadIntended(schema)\n\n let getComponentSilently = (name) => getComponent(name, false, { failSilently: true })\n let Comp = type ? format ?\n getComponentSilently(`JsonSchema_${type}_${format}`) :\n getComponentSilently(`JsonSchema_${type}`) :\n getComponent(\"JsonSchema_string\")\n\n if (!isFileUploadIntended && List.isList(type) && (objectType === \"array\" || objectType === \"object\")) {\n Comp = getComponent(\"JsonSchema_object\")\n }\n\n if (!Comp) {\n Comp = getComponent(\"JsonSchema_string\")\n }\n\n return \n }\n}\n\nexport class JsonSchema_string extends Component {\n static propTypes = JsonSchemaPropShape\n static defaultProps = JsonSchemaDefaultProps\n onChange = (e) => {\n const value = this.props.schema && this.props.schema.get(\"type\") === \"file\" ? e.target.files[0] : e.target.value\n this.props.onChange(value, this.props.keyName)\n }\n onEnumChange = (val) => this.props.onChange(val)\n render() {\n let { getComponent, value, schema, errors, required, description, disabled } = this.props\n const enumValue = schema && schema.get ? schema.get(\"enum\") : null\n const format = schema && schema.get ? schema.get(\"format\") : null\n const type = schema && schema.get ? schema.get(\"type\") : null\n const schemaIn = schema && schema.get ? schema.get(\"in\") : null\n if (!value) {\n value = \"\" // value should not be null; this fixes a Debounce error\n } else if (isImmutable(value) || typeof value === \"object\") {\n value = stringify(value)\n }\n\n errors = errors.toJS ? errors.toJS() : []\n\n if ( enumValue ) {\n const Select = getComponent(\"Select\")\n return (\n )\n }\n else {\n return (\n \n )\n }\n }\n}\n\nexport class JsonSchema_array extends PureComponent {\n\n static propTypes = JsonSchemaPropShape\n static defaultProps = JsonSchemaDefaultProps\n\n constructor(props, context) {\n super(props, context)\n this.state = { value: valueOrEmptyList(props.value), schema: props.schema}\n }\n\n UNSAFE_componentWillReceiveProps(props) {\n const value = valueOrEmptyList(props.value)\n if(value !== this.state.value)\n this.setState({ value })\n\n if(props.schema !== this.state.schema)\n this.setState({ schema: props.schema })\n }\n\n onChange = () => {\n this.props.onChange(this.state.value)\n }\n\n onItemChange = (itemVal, i) => {\n this.setState(({ value }) => ({\n value: value.set(i, itemVal)\n }), this.onChange)\n }\n\n removeItem = (i) => {\n this.setState(({ value }) => ({\n value: value.delete(i)\n }), this.onChange)\n }\n\n addItem = () => {\n const { fn } = this.props\n let newValue = valueOrEmptyList(this.state.value)\n this.setState(() => ({\n value: newValue.push(fn.getSampleSchema(this.state.schema.get(\"items\"), false, {\n includeWriteOnly: true\n }))\n }), this.onChange)\n }\n\n onEnumChange = (value) => {\n this.setState(() => ({\n value: value\n }), this.onChange)\n }\n\n render() {\n let { getComponent, required, schema, errors, fn, disabled } = this.props\n\n errors = errors.toJS ? errors.toJS() : Array.isArray(errors) ? errors : []\n const arrayErrors = errors.filter(e => typeof e === \"string\")\n const needsRemoveError = errors.filter(e => e.needRemove !== undefined)\n .map(e => e.error)\n const value = this.state.value // expect Im List\n const shouldRenderValue =\n !!(value && value.count && value.count() > 0)\n const schemaItemsEnum = schema.getIn([\"items\", \"enum\"])\n const schemaItems = schema.get(\"items\")\n const schemaItemsType = fn.getSchemaObjectType(schemaItems)\n const schemaItemsTypeLabel = fn.getSchemaObjectTypeLabel(schemaItems)\n const schemaItemsFormat = schema.getIn([\"items\", \"format\"])\n const schemaItemsSchema = schema.get(\"items\")\n let ArrayItemsComponent\n let isArrayItemText = false\n let isArrayItemFile = (schemaItemsType === \"file\" || (schemaItemsType === \"string\" && schemaItemsFormat === \"binary\"))\n if (schemaItemsType && schemaItemsFormat) {\n ArrayItemsComponent = getComponent(`JsonSchema_${schemaItemsType}_${schemaItemsFormat}`)\n } else if (schemaItemsType === \"boolean\" || schemaItemsType === \"array\" || schemaItemsType === \"object\") {\n ArrayItemsComponent = getComponent(`JsonSchema_${schemaItemsType}`)\n }\n\n if (List.isList(schemaItems?.get(\"type\")) && (schemaItemsType === \"array\" || schemaItemsType === \"object\")) {\n ArrayItemsComponent = getComponent(`JsonSchema_object`)\n }\n\n // if ArrayItemsComponent not assigned or does not exist,\n // use default schemaItemsType === \"string\" & JsonSchemaArrayItemText component\n if (!ArrayItemsComponent && !isArrayItemFile) {\n isArrayItemText = true\n }\n\n if ( schemaItemsEnum ) {\n const Select = getComponent(\"Select\")\n return ()\n }\n}\n\nexport class JsonSchema_boolean extends Component {\n static propTypes = JsonSchemaPropShape\n static defaultProps = JsonSchemaDefaultProps\n\n onEnumChange = (val) => this.props.onChange(val)\n render() {\n let { getComponent, value, errors, schema, required, disabled } = this.props\n errors = errors.toJS ? errors.toJS() : []\n let enumValue = schema && schema.get ? schema.get(\"enum\") : null\n let allowEmptyValue = !enumValue || !required\n let booleanValue = !enumValue && [\"true\", \"false\"]\n const Select = getComponent(\"Select\")\n\n return (\n \n }\n \n {\n errors.valueSeq().map( (error, key) => {\n return \n } )\n }\n \n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\n\nexport default class BasicAuth extends React.Component {\n static propTypes = {\n authorized: ImPropTypes.map,\n schema: ImPropTypes.map,\n getComponent: PropTypes.func.isRequired,\n onChange: PropTypes.func.isRequired,\n name: PropTypes.string.isRequired,\n errSelectors: PropTypes.object.isRequired,\n authSelectors: PropTypes.object.isRequired\n }\n\n constructor(props, context) {\n super(props, context)\n let { schema, name } = this.props\n\n let value = this.getValue()\n let username = value.username\n\n this.state = {\n name: name,\n schema: schema,\n value: !username ? {} : {\n username: username\n }\n }\n }\n\n getValue () {\n let { authorized, name } = this.props\n\n return authorized && authorized.getIn([name, \"value\"]) || {}\n }\n\n onChange =(e) => {\n let { onChange } = this.props\n let { value, name } = e.target\n\n let newValue = this.state.value\n newValue[name] = value\n\n this.setState({ value: newValue })\n\n onChange(this.state)\n }\n\n render() {\n let { schema, getComponent, name, errSelectors, authSelectors } = this.props\n const Input = getComponent(\"Input\")\n const Row = getComponent(\"Row\")\n const Col = getComponent(\"Col\")\n const AuthError = getComponent(\"authError\")\n const JumpToPath = getComponent(\"JumpToPath\", true)\n const Markdown = getComponent(\"Markdown\", true)\n const path = authSelectors.selectAuthPath(name)\n let username = this.getValue().username\n let errors = errSelectors.allErrors().filter( err => err.get(\"authId\") === name)\n\n return (\n
\n

Basic authorization

\n { username &&
Authorized
}\n \n \n \n \n \n {\n username ? { username } \n : \n \n \n }\n \n \n \n {\n username ? ****** \n : \n \n \n }\n \n {\n errors.valueSeq().map( (error, key) => {\n return \n } )\n }\n
\n )\n }\n\n}\n","/**\n * @prettier\n */\n\nimport React from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport { stringify } from \"core/utils\"\nimport { Map } from \"immutable\"\n\nexport default function Example(props) {\n const { example, showValue, getComponent } = props\n\n const Markdown = getComponent(\"Markdown\", true)\n const HighlightCode = getComponent(\"HighlightCode\", true)\n\n if (!example || !Map.isMap(example)) return null\n\n return (\n
\n {example.get(\"description\") ? (\n
\n
Example Description
\n

\n \n

\n
\n ) : null}\n {showValue && example.has(\"value\") ? (\n
\n
Example Value
\n {stringify(example.get(\"value\"))}\n
\n ) : null}\n
\n )\n}\n\nExample.propTypes = {\n example: ImPropTypes.map.isRequired,\n showValue: PropTypes.bool,\n getComponent: PropTypes.func.isRequired,\n}\n","/**\n * @prettier\n */\n\nimport React from \"react\"\nimport { Map } from \"immutable\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\n\nexport default class ExamplesSelect extends React.PureComponent {\n static propTypes = {\n examples: ImPropTypes.map.isRequired,\n onSelect: PropTypes.func,\n currentExampleKey: PropTypes.string,\n isModifiedValueAvailable: PropTypes.bool,\n isValueModified: PropTypes.bool,\n showLabels: PropTypes.bool,\n }\n\n static defaultProps = {\n examples: Map({}),\n onSelect: (...args) =>\n // eslint-disable-next-line no-console\n console.log(\n // FIXME: remove before merging to master...\n `DEBUG: ExamplesSelect was not given an onSelect callback`,\n ...args\n ),\n currentExampleKey: null,\n showLabels: true,\n }\n\n _onSelect = (key, { isSyntheticChange = false } = {}) => {\n if (typeof this.props.onSelect === \"function\") {\n this.props.onSelect(key, {\n isSyntheticChange,\n })\n }\n }\n\n _onDomSelect = (e) => {\n if (typeof this.props.onSelect === \"function\") {\n const element = e.target.selectedOptions[0]\n const key = element.getAttribute(\"value\")\n\n this._onSelect(key, {\n isSyntheticChange: false,\n })\n }\n }\n\n getCurrentExample = () => {\n const { examples, currentExampleKey } = this.props\n\n const currentExamplePerProps = examples.get(currentExampleKey)\n\n const firstExamplesKey = examples.keySeq().first()\n const firstExample = examples.get(firstExamplesKey)\n\n return currentExamplePerProps || firstExample || Map({})\n }\n\n componentDidMount() {\n // this is the not-so-great part of ExamplesSelect... here we're\n // artificially kicking off an onSelect event in order to set a default\n // value in state. the consumer has the option to avoid this by checking\n // `isSyntheticEvent`, but we should really be doing this in a selector.\n // TODO: clean this up\n // FIXME: should this only trigger if `currentExamplesKey` is nullish?\n const { onSelect, examples } = this.props\n\n if (typeof onSelect === \"function\") {\n const firstExample = examples.first()\n const firstExampleKey = examples.keyOf(firstExample)\n\n this._onSelect(firstExampleKey, {\n isSyntheticChange: true,\n })\n }\n }\n\n UNSAFE_componentWillReceiveProps(nextProps) {\n const { currentExampleKey, examples } = nextProps\n if (examples !== this.props.examples && !examples.has(currentExampleKey)) {\n // examples have changed from under us, and the currentExampleKey is no longer\n // valid.\n const firstExample = examples.first()\n const firstExampleKey = examples.keyOf(firstExample)\n\n this._onSelect(firstExampleKey, {\n isSyntheticChange: true,\n })\n }\n }\n\n render() {\n const {\n examples,\n currentExampleKey,\n isValueModified,\n isModifiedValueAvailable,\n showLabels,\n } = this.props\n\n return (\n
\n {showLabels ? (\n Examples: \n ) : null}\n \n {isModifiedValueAvailable ? (\n \n ) : null}\n {examples\n .map((example, exampleName) => {\n return (\n \n {(Map.isMap(example) && example.get(\"summary\")) ||\n exampleName}\n \n )\n })\n .valueSeq()}\n \n
\n )\n }\n}\n","/**\n * @prettier\n */\nimport React from \"react\"\nimport { Map, List } from \"immutable\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\n\nimport { stringify } from \"core/utils\"\n\n// This stateful component lets us avoid writing competing values (user\n// modifications vs example values) into global state, and the mess that comes\n// with that: tracking which of the two values are currently used for\n// Try-It-Out, which example a modified value came from, etc...\n//\n// The solution here is to retain the last user-modified value in\n// ExamplesSelectValueRetainer's component state, so that our global state can stay\n// clean, always simply being the source of truth for what value should be both\n// displayed to the user and used as a value during request execution.\n//\n// This approach/tradeoff was chosen in order to encapsulate the particular\n// logic of Examples within the Examples component tree, and to avoid\n// regressions within our current implementation elsewhere (non-Examples\n// definitions, OpenAPI 2.0, etc). A future refactor to global state might make\n// this component unnecessary.\n//\n// TL;DR: this is not our usual approach, but the choice was made consciously.\n\n// Note that `currentNamespace` isn't currently used anywhere!\n\nconst stringifyUnlessList = (input) =>\n List.isList(input) ? input : stringify(input)\n\nexport default class ExamplesSelectValueRetainer extends React.PureComponent {\n static propTypes = {\n examples: ImPropTypes.map,\n onSelect: PropTypes.func,\n updateValue: PropTypes.func, // mechanism to update upstream value\n userHasEditedBody: PropTypes.bool,\n getComponent: PropTypes.func.isRequired,\n currentUserInputValue: PropTypes.any,\n currentKey: PropTypes.string,\n currentNamespace: PropTypes.string,\n setRetainRequestBodyValueFlag: PropTypes.func.isRequired,\n // (also proxies props for Examples)\n }\n\n static defaultProps = {\n userHasEditedBody: false,\n examples: Map({}),\n currentNamespace: \"__DEFAULT__NAMESPACE__\",\n setRetainRequestBodyValueFlag: () => {\n // NOOP\n },\n onSelect: (...args) =>\n // eslint-disable-next-line no-console\n console.log(\n \"ExamplesSelectValueRetainer: no `onSelect` function was provided\",\n ...args\n ),\n updateValue: (...args) =>\n // eslint-disable-next-line no-console\n console.log(\n \"ExamplesSelectValueRetainer: no `updateValue` function was provided\",\n ...args\n ),\n }\n\n constructor(props) {\n super(props)\n\n const valueFromExample = this._getCurrentExampleValue()\n\n this.state = {\n // user edited: last value that came from the world around us, and didn't\n // match the current example's value\n // internal: last value that came from user selecting an Example\n [props.currentNamespace]: Map({\n lastUserEditedValue: this.props.currentUserInputValue,\n lastDownstreamValue: valueFromExample,\n isModifiedValueSelected:\n // valueFromExample !== undefined &&\n this.props.userHasEditedBody ||\n this.props.currentUserInputValue !== valueFromExample,\n }),\n }\n }\n\n componentWillUnmount() {\n this.props.setRetainRequestBodyValueFlag(false)\n }\n\n _getStateForCurrentNamespace = () => {\n const { currentNamespace } = this.props\n\n return (this.state[currentNamespace] || Map()).toObject()\n }\n\n _setStateForCurrentNamespace = (obj) => {\n const { currentNamespace } = this.props\n\n return this._setStateForNamespace(currentNamespace, obj)\n }\n\n _setStateForNamespace = (namespace, obj) => {\n const oldStateForNamespace = this.state[namespace] || Map()\n const newStateForNamespace = oldStateForNamespace.mergeDeep(obj)\n return this.setState({\n [namespace]: newStateForNamespace,\n })\n }\n\n _isCurrentUserInputSameAsExampleValue = () => {\n const { currentUserInputValue } = this.props\n\n const valueFromExample = this._getCurrentExampleValue()\n\n return valueFromExample === currentUserInputValue\n }\n\n _getValueForExample = (exampleKey, props) => {\n // props are accepted so that this can be used in UNSAFE_componentWillReceiveProps,\n // which has access to `nextProps`\n const { examples } = props || this.props\n return stringifyUnlessList(\n (examples || Map({})).getIn([exampleKey, \"value\"])\n )\n }\n\n _getCurrentExampleValue = (props) => {\n // props are accepted so that this can be used in UNSAFE_componentWillReceiveProps,\n // which has access to `nextProps`\n const { currentKey } = props || this.props\n return this._getValueForExample(currentKey, props || this.props)\n }\n\n _onExamplesSelect = (key, { isSyntheticChange } = {}, ...otherArgs) => {\n const { onSelect, updateValue, currentUserInputValue, userHasEditedBody } =\n this.props\n const { lastUserEditedValue } = this._getStateForCurrentNamespace()\n\n const valueFromExample = this._getValueForExample(key)\n\n if (key === \"__MODIFIED__VALUE__\") {\n updateValue(stringifyUnlessList(lastUserEditedValue))\n return this._setStateForCurrentNamespace({\n isModifiedValueSelected: true,\n })\n }\n\n if (typeof onSelect === \"function\") {\n onSelect(key, { isSyntheticChange }, ...otherArgs)\n }\n\n this._setStateForCurrentNamespace({\n lastDownstreamValue: valueFromExample,\n isModifiedValueSelected:\n (isSyntheticChange && userHasEditedBody) ||\n (!!currentUserInputValue && currentUserInputValue !== valueFromExample),\n })\n\n // we never want to send up value updates from synthetic changes\n if (isSyntheticChange) return\n\n if (typeof updateValue === \"function\") {\n updateValue(stringifyUnlessList(valueFromExample))\n }\n }\n\n UNSAFE_componentWillReceiveProps(nextProps) {\n // update `lastUserEditedValue` as new currentUserInput values come in\n\n const {\n currentUserInputValue: newValue,\n examples,\n onSelect,\n userHasEditedBody,\n } = nextProps\n\n const { lastUserEditedValue, lastDownstreamValue } =\n this._getStateForCurrentNamespace()\n\n const valueFromCurrentExample = this._getValueForExample(\n nextProps.currentKey,\n nextProps\n )\n\n const examplesMatchingNewValue = examples.filter(\n (example) =>\n Map.isMap(example) &&\n (example.get(\"value\") === newValue ||\n // sometimes data is stored as a string (e.g. in Request Bodies), so\n // let's check against a stringified version of our example too\n stringify(example.get(\"value\")) === newValue)\n )\n\n if (examplesMatchingNewValue.size) {\n let key\n if (examplesMatchingNewValue.has(nextProps.currentKey)) {\n key = nextProps.currentKey\n } else {\n key = examplesMatchingNewValue.keySeq().first()\n }\n onSelect(key, {\n isSyntheticChange: true,\n })\n } else if (\n newValue !== this.props.currentUserInputValue && // value has changed\n newValue !== lastUserEditedValue && // value isn't already tracked\n newValue !== lastDownstreamValue // value isn't what we've seen on the other side\n ) {\n this.props.setRetainRequestBodyValueFlag(true)\n this._setStateForNamespace(nextProps.currentNamespace, {\n lastUserEditedValue: nextProps.currentUserInputValue,\n isModifiedValueSelected:\n userHasEditedBody || newValue !== valueFromCurrentExample,\n })\n }\n }\n\n render() {\n const {\n currentUserInputValue,\n examples,\n currentKey,\n getComponent,\n userHasEditedBody,\n } = this.props\n const {\n lastDownstreamValue,\n lastUserEditedValue,\n isModifiedValueSelected,\n } = this._getStateForCurrentNamespace()\n\n const ExamplesSelect = getComponent(\"ExamplesSelect\")\n\n return (\n \n )\n }\n}\n","import parseUrl from \"url-parse\"\nimport Im from \"immutable\"\nimport { btoa, generateCodeVerifier, createCodeChallenge } from \"core/utils\"\nimport { sanitizeUrl } from \"core/utils/url\"\n\nexport default function authorize ( { auth, authActions, errActions, configs, authConfigs={}, currentServer } ) {\n let { schema, scopes, name, clientId } = auth\n let flow = schema.get(\"flow\")\n let query = []\n\n switch (flow) {\n case \"password\":\n authActions.authorizePassword(auth)\n return\n\n case \"application\":\n authActions.authorizeApplication(auth)\n return\n\n case \"accessCode\":\n query.push(\"response_type=code\")\n break\n\n case \"implicit\":\n query.push(\"response_type=token\")\n break\n\n case \"clientCredentials\":\n case \"client_credentials\":\n // OAS3\n authActions.authorizeApplication(auth)\n return\n\n case \"authorizationCode\":\n case \"authorization_code\":\n // OAS3\n query.push(\"response_type=code\")\n break\n }\n\n if (typeof clientId === \"string\") {\n query.push(\"client_id=\" + encodeURIComponent(clientId))\n }\n\n let redirectUrl = configs.oauth2RedirectUrl\n\n // todo move to parser\n if (typeof redirectUrl === \"undefined\") {\n errActions.newAuthErr( {\n authId: name,\n source: \"validation\",\n level: \"error\",\n message: \"oauth2RedirectUrl configuration is not passed. Oauth2 authorization cannot be performed.\"\n })\n return\n }\n query.push(\"redirect_uri=\" + encodeURIComponent(redirectUrl))\n\n let scopesArray = []\n if (Array.isArray(scopes)) {\n scopesArray = scopes\n } else if (Im.List.isList(scopes)) {\n scopesArray = scopes.toArray()\n }\n\n if (scopesArray.length > 0) {\n let scopeSeparator = authConfigs.scopeSeparator || \" \"\n\n query.push(\"scope=\" + encodeURIComponent(scopesArray.join(scopeSeparator)))\n }\n\n let state = btoa(new Date())\n\n query.push(\"state=\" + encodeURIComponent(state))\n\n if (typeof authConfigs.realm !== \"undefined\") {\n query.push(\"realm=\" + encodeURIComponent(authConfigs.realm))\n }\n\n if ((flow === \"authorizationCode\" || flow === \"authorization_code\" || flow === \"accessCode\") && authConfigs.usePkceWithAuthorizationCodeGrant) {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = createCodeChallenge(codeVerifier)\n\n query.push(\"code_challenge=\" + codeChallenge)\n query.push(\"code_challenge_method=S256\")\n\n // storing the Code Verifier so it can be sent to the token endpoint\n // when exchanging the Authorization Code for an Access Token\n auth.codeVerifier = codeVerifier\n }\n\n let { additionalQueryStringParams } = authConfigs\n\n for (let key in additionalQueryStringParams) {\n if (typeof additionalQueryStringParams[key] !== \"undefined\") {\n query.push([key, additionalQueryStringParams[key]].map(encodeURIComponent).join(\"=\"))\n }\n }\n\n const authorizationUrl = schema.get(\"authorizationUrl\")\n let sanitizedAuthorizationUrl\n if (currentServer) {\n // OpenAPI 3\n sanitizedAuthorizationUrl = parseUrl(\n sanitizeUrl(authorizationUrl),\n currentServer,\n true\n ).toString()\n } else {\n sanitizedAuthorizationUrl = sanitizeUrl(authorizationUrl)\n }\n let url = [sanitizedAuthorizationUrl, query.join(\"&\")].join(\n typeof authorizationUrl === \"string\" && !authorizationUrl.includes(\"?\")\n ? \"?\"\n : \"&\"\n )\n\n // pass action authorizeOauth2 and authentication data through window\n // to authorize with oauth2\n\n let callback\n if (flow === \"implicit\") {\n callback = authActions.preAuthorizeImplicit\n } else if (authConfigs.useBasicAuthenticationWithAccessCodeGrant) {\n callback = authActions.authorizeAccessCodeWithBasicAuthentication\n } else {\n callback = authActions.authorizeAccessCodeWithFormParams\n }\n\n authActions.authPopup(url, {\n auth: auth,\n state: state,\n redirectUrl: redirectUrl,\n callback: callback,\n errCb: errActions.newAuthErr\n })\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport oauth2Authorize from \"core/oauth2-authorize\"\n\nexport default class Oauth2 extends React.Component {\n static propTypes = {\n name: PropTypes.string,\n authorized: PropTypes.object,\n getComponent: PropTypes.func.isRequired,\n schema: PropTypes.object.isRequired,\n authSelectors: PropTypes.object.isRequired,\n authActions: PropTypes.object.isRequired,\n errSelectors: PropTypes.object.isRequired,\n oas3Selectors: PropTypes.object.isRequired,\n specSelectors: PropTypes.object.isRequired,\n errActions: PropTypes.object.isRequired,\n getConfigs: PropTypes.any\n }\n\n constructor(props, context) {\n super(props, context)\n let { name, schema, authorized, authSelectors } = this.props\n let auth = authorized && authorized.get(name)\n let authConfigs = authSelectors.getConfigs() || {}\n let username = auth && auth.get(\"username\") || \"\"\n let clientId = auth && auth.get(\"clientId\") || authConfigs.clientId || \"\"\n let clientSecret = auth && auth.get(\"clientSecret\") || authConfigs.clientSecret || \"\"\n let passwordType = auth && auth.get(\"passwordType\") || \"basic\"\n let scopes = auth && auth.get(\"scopes\") || authConfigs.scopes || []\n if (typeof scopes === \"string\") {\n scopes = scopes.split(authConfigs.scopeSeparator || \" \")\n }\n\n this.state = {\n appName: authConfigs.appName,\n name: name,\n schema: schema,\n scopes: scopes,\n clientId: clientId,\n clientSecret: clientSecret,\n username: username,\n password: \"\",\n passwordType: passwordType\n }\n }\n\n close = (e) => {\n e.preventDefault()\n let { authActions } = this.props\n\n authActions.showDefinitions(false)\n }\n\n authorize =() => {\n let { authActions, errActions, getConfigs, authSelectors, oas3Selectors } = this.props\n let configs = getConfigs()\n let authConfigs = authSelectors.getConfigs()\n\n errActions.clear({authId: name,type: \"auth\", source: \"auth\"})\n oauth2Authorize({\n auth: this.state,\n currentServer: oas3Selectors.serverEffectiveValue(oas3Selectors.selectedServer()),\n authActions,\n errActions,\n configs,\n authConfigs\n })\n }\n\n onScopeChange =(e) => {\n let { target } = e\n let { checked } = target\n let scope = target.dataset.value\n\n if ( checked && this.state.scopes.indexOf(scope) === -1 ) {\n let newScopes = this.state.scopes.concat([scope])\n this.setState({ scopes: newScopes })\n } else if ( !checked && this.state.scopes.indexOf(scope) > -1) {\n this.setState({ scopes: this.state.scopes.filter((val) => val !== scope) })\n }\n }\n\n onInputChange =(e) => {\n let { target : { dataset : { name }, value } } = e\n let state = {\n [name]: value\n }\n\n this.setState(state)\n }\n\n selectScopes =(e) => {\n if (e.target.dataset.all) {\n this.setState({\n scopes: Array.from((this.props.schema.get(\"allowedScopes\") || this.props.schema.get(\"scopes\")).keys())\n })\n } else {\n this.setState({ scopes: [] })\n }\n }\n\n logout =(e) => {\n e.preventDefault()\n let { authActions, errActions, name } = this.props\n\n errActions.clear({authId: name, type: \"auth\", source: \"auth\"})\n authActions.logoutWithPersistOption([ name ])\n }\n\n render() {\n let {\n schema, getComponent, authSelectors, errSelectors, name, specSelectors\n } = this.props\n const Input = getComponent(\"Input\")\n const Row = getComponent(\"Row\")\n const Col = getComponent(\"Col\")\n const Button = getComponent(\"Button\")\n const AuthError = getComponent(\"authError\")\n const JumpToPath = getComponent(\"JumpToPath\", true)\n const Markdown = getComponent(\"Markdown\", true)\n const InitializedInput = getComponent(\"InitializedInput\")\n\n const { isOAS3 } = specSelectors\n\n let oidcUrl = isOAS3() ? schema.get(\"openIdConnectUrl\") : null\n\n // Auth type consts\n const AUTH_FLOW_IMPLICIT = \"implicit\"\n const AUTH_FLOW_PASSWORD = \"password\"\n const AUTH_FLOW_ACCESS_CODE = isOAS3() ? (oidcUrl ? \"authorization_code\" : \"authorizationCode\") : \"accessCode\"\n const AUTH_FLOW_APPLICATION = isOAS3() ? (oidcUrl ? \"client_credentials\" : \"clientCredentials\") : \"application\"\n\n const path = authSelectors.selectAuthPath(name)\n\n let authConfigs = authSelectors.getConfigs() || {}\n let isPkceCodeGrant = !!authConfigs.usePkceWithAuthorizationCodeGrant\n\n let flow = schema.get(\"flow\")\n let flowToDisplay = flow === AUTH_FLOW_ACCESS_CODE && isPkceCodeGrant ? flow + \" with PKCE\" : flow\n let scopes = schema.get(\"allowedScopes\") || schema.get(\"scopes\")\n let authorizedAuth = authSelectors.authorized().get(name)\n let isAuthorized = !!authorizedAuth\n let errors = errSelectors.allErrors().filter( err => err.get(\"authId\") === name)\n let isValid = !errors.filter( err => err.get(\"source\") === \"validation\").size\n let description = schema.get(\"description\")\n\n return (\n
\n

{name} (OAuth2, { flowToDisplay })

\n { !this.state.appName ? null :
Application: { this.state.appName }
}\n { description && }\n\n { isAuthorized &&
Authorized
}\n\n { oidcUrl &&

OpenID Connect URL: { oidcUrl }

}\n { ( flow === AUTH_FLOW_IMPLICIT || flow === AUTH_FLOW_ACCESS_CODE ) &&

Authorization URL: { schema.get(\"authorizationUrl\") }

}\n { ( flow === AUTH_FLOW_PASSWORD || flow === AUTH_FLOW_ACCESS_CODE || flow === AUTH_FLOW_APPLICATION ) &&

Token URL: { schema.get(\"tokenUrl\") }

}\n

Flow: { flowToDisplay }

\n\n {\n flow !== AUTH_FLOW_PASSWORD ? null\n : \n \n \n {\n isAuthorized ? { this.state.username } \n : \n \n \n }\n \n {\n\n }\n \n \n {\n isAuthorized ? ****** \n : \n \n \n }\n \n \n \n {\n isAuthorized ? { this.state.passwordType } \n : \n \n \n }\n \n \n }\n {\n ( flow === AUTH_FLOW_APPLICATION || flow === AUTH_FLOW_IMPLICIT || flow === AUTH_FLOW_ACCESS_CODE || flow === AUTH_FLOW_PASSWORD ) &&\n ( !isAuthorized || isAuthorized && this.state.clientId) && \n \n {\n isAuthorized ? ****** \n : \n \n \n }\n \n }\n\n {\n ( (flow === AUTH_FLOW_APPLICATION || flow === AUTH_FLOW_ACCESS_CODE || flow === AUTH_FLOW_PASSWORD) && \n \n {\n isAuthorized ? ****** \n : \n \n \n }\n\n \n )}\n\n {\n !isAuthorized && scopes && scopes.size ?
\n

\n Scopes:\n select all\n select none\n

\n { scopes.map((description, name) => {\n return (\n \n
\n \n \n
\n
\n )\n }).toArray()\n }\n
: null\n }\n\n {\n errors.valueSeq().map( (error, key) => {\n return \n } )\n }\n
\n { isValid &&\n ( isAuthorized ? \n : \n )\n }\n \n
\n\n
\n )\n }\n}\n","import React, { Component } from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport default class Clear extends Component {\n\n onClick =() => {\n let { specActions, path, method } = this.props\n specActions.clearResponse( path, method )\n specActions.clearRequest( path, method )\n }\n\n render(){\n return (\n \n )\n }\n\n static propTypes = {\n specActions: PropTypes.object.isRequired,\n path: PropTypes.string.isRequired,\n method: PropTypes.string.isRequired,\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\n\nconst Headers = ( { headers } )=>{\n return (\n
\n
Response headers
\n
{headers}
\n
)\n}\nHeaders.propTypes = {\n headers: PropTypes.array.isRequired\n}\n\nconst Duration = ( { duration } ) => {\n return (\n
\n
Request duration
\n
{duration} ms
\n
\n )\n}\nDuration.propTypes = {\n duration: PropTypes.number.isRequired\n}\n\n\nexport default class LiveResponse extends React.Component {\n static propTypes = {\n response: ImPropTypes.map,\n path: PropTypes.string.isRequired,\n method: PropTypes.string.isRequired,\n displayRequestDuration: PropTypes.bool.isRequired,\n specSelectors: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired\n }\n\n shouldComponentUpdate(nextProps) {\n // BUG: props.response is always coming back as a new Immutable instance\n // same issue as responses.jsx (tryItOutResponse)\n return this.props.response !== nextProps.response\n || this.props.path !== nextProps.path\n || this.props.method !== nextProps.method\n || this.props.displayRequestDuration !== nextProps.displayRequestDuration\n }\n\n render() {\n const { response, getComponent, getConfigs, displayRequestDuration, specSelectors, path, method } = this.props\n const { showMutatedRequest, requestSnippetsEnabled } = getConfigs()\n\n const curlRequest = showMutatedRequest ? specSelectors.mutatedRequestFor(path, method) : specSelectors.requestFor(path, method)\n const status = response.get(\"status\")\n const url = curlRequest.get(\"url\")\n const headers = response.get(\"headers\").toJS()\n const notDocumented = response.get(\"notDocumented\")\n const isError = response.get(\"error\")\n const body = response.get(\"text\")\n const duration = response.get(\"duration\")\n const headersKeys = Object.keys(headers)\n const contentType = headers[\"content-type\"] || headers[\"Content-Type\"]\n\n const ResponseBody = getComponent(\"responseBody\")\n const returnObject = headersKeys.map(key => {\n var joinedHeaders = Array.isArray(headers[key]) ? headers[key].join() : headers[key]\n return {key}: {joinedHeaders} \n })\n const hasHeaders = returnObject.length !== 0\n const Markdown = getComponent(\"Markdown\", true)\n const RequestSnippets = getComponent(\"RequestSnippets\", true)\n const Curl = getComponent(\"curl\", true)\n\n return (\n
\n { curlRequest && requestSnippetsEnabled \n ? \n : \n }\n { url &&
\n
\n

Request URL

\n
{url}
\n
\n
\n }\n

Server response

\n \n \n \n \n \n \n \n \n \n \n \n \n \n
CodeDetails
\n { status }\n {\n notDocumented ?
\n Undocumented \n
\n : null\n }\n
\n {\n isError ? \n : null\n }\n {\n body ? \n : null\n }\n {\n hasHeaders ? : null\n }\n {\n displayRequestDuration && duration ? : null\n }\n
\n
\n )\n }\n}\n","import React from \"react\"\nimport URL from \"url-parse\"\n\nimport PropTypes from \"prop-types\"\nimport { requiresValidationURL } from \"core/utils\"\nimport { sanitizeUrl } from \"core/utils/url\"\nimport win from \"core/window\"\n\nexport default class OnlineValidatorBadge extends React.Component {\n static propTypes = {\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n specSelectors: PropTypes.object.isRequired\n }\n\n constructor(props, context) {\n super(props, context)\n let { getConfigs } = props\n let { validatorUrl } = getConfigs()\n this.state = {\n url: this.getDefinitionUrl(),\n validatorUrl: validatorUrl === undefined ? \"https://validator.swagger.io/validator\" : validatorUrl\n }\n }\n\n getDefinitionUrl = () => {\n // TODO: test this behavior by stubbing `window.location` in an Enzyme/JSDom env\n let { specSelectors } = this.props\n\n const urlObject = new URL(specSelectors.url(), win.location)\n return urlObject.toString()\n }\n\n UNSAFE_componentWillReceiveProps(nextProps) {\n let { getConfigs } = nextProps\n let { validatorUrl } = getConfigs()\n\n this.setState({\n url: this.getDefinitionUrl(),\n validatorUrl: validatorUrl === undefined ? \"https://validator.swagger.io/validator\" : validatorUrl\n })\n }\n\n render() {\n let { getConfigs } = this.props\n let { spec } = getConfigs()\n\n let sanitizedValidatorUrl = sanitizeUrl(this.state.validatorUrl)\n\n if ( typeof spec === \"object\" && Object.keys(spec).length) return null\n\n if (!this.state.url || !requiresValidationURL(this.state.validatorUrl)\n || !requiresValidationURL(this.state.url)) {\n return null\n }\n\n return (\n \n \n \n )\n }\n}\n\n\nclass ValidatorImage extends React.Component {\n static propTypes = {\n src: PropTypes.string,\n alt: PropTypes.string\n }\n\n constructor(props) {\n super(props)\n this.state = {\n loaded: false,\n error: false\n }\n }\n\n componentDidMount() {\n const img = new Image()\n img.onload = () => {\n this.setState({\n loaded: true\n })\n }\n img.onerror = () => {\n this.setState({\n error: true\n })\n }\n img.src = this.props.src\n }\n\n UNSAFE_componentWillReceiveProps(nextProps) {\n if (nextProps.src !== this.props.src) {\n const img = new Image()\n img.onload = () => {\n this.setState({\n loaded: true\n })\n }\n img.onerror = () => {\n this.setState({\n error: true\n })\n }\n img.src = nextProps.src\n }\n }\n\n render() {\n if (this.state.error) {\n return {\"Error\"}\n } else if (!this.state.loaded) {\n return null\n }\n return {this.props.alt}\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport default class Operations extends React.Component {\n\n static propTypes = {\n specSelectors: PropTypes.object.isRequired,\n specActions: PropTypes.object.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n oas3Selectors: PropTypes.func.isRequired,\n layoutSelectors: PropTypes.object.isRequired,\n layoutActions: PropTypes.object.isRequired,\n authActions: PropTypes.object.isRequired,\n authSelectors: PropTypes.object.isRequired,\n getConfigs: PropTypes.func.isRequired,\n fn: PropTypes.func.isRequired\n }\n\n render() {\n let {\n specSelectors,\n } = this.props\n\n const taggedOps = specSelectors.taggedOperations()\n\n if(taggedOps.size === 0) {\n return

No operations defined in spec!

\n }\n\n return (\n
\n { taggedOps.map(this.renderOperationTag).toArray() }\n { taggedOps.size < 1 ?

No operations defined in spec!

: null }\n
\n )\n }\n\n renderOperationTag = (tagObj, tag) => {\n const {\n specSelectors,\n getComponent,\n oas3Selectors,\n layoutSelectors,\n layoutActions,\n getConfigs,\n } = this.props\n const validOperationMethods = specSelectors.validOperationMethods()\n const OperationContainer = getComponent(\"OperationContainer\", true)\n const OperationTag = getComponent(\"OperationTag\")\n const operations = tagObj.get(\"operations\")\n return (\n \n
\n {\n operations.map(op => {\n const path = op.get(\"path\")\n const method = op.get(\"method\")\n const specPath = op.get(\"specPath\")\n\n if (validOperationMethods.indexOf(method) === -1) {\n return null\n }\n\n return (\n \n )\n }).toArray()\n }\n
\n \n )\n }\n\n}\n\nOperations.propTypes = {\n layoutActions: PropTypes.object.isRequired,\n specSelectors: PropTypes.object.isRequired,\n specActions: PropTypes.object.isRequired,\n layoutSelectors: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n fn: PropTypes.object.isRequired\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport Im from \"immutable\"\nimport { createDeepLinkPath, escapeDeepLinkPath, isFunc } from \"core/utils\"\nimport { safeBuildUrl, sanitizeUrl } from \"core/utils/url\"\n\n/* eslint-disable react/jsx-no-bind */\n\nexport default class OperationTag extends React.Component {\n\n static defaultProps = {\n tagObj: Im.fromJS({}),\n tag: \"\",\n }\n\n static propTypes = {\n tagObj: ImPropTypes.map.isRequired,\n tag: PropTypes.string.isRequired,\n\n oas3Selectors: PropTypes.func.isRequired,\n layoutSelectors: PropTypes.object.isRequired,\n layoutActions: PropTypes.object.isRequired,\n\n getConfigs: PropTypes.func.isRequired,\n getComponent: PropTypes.func.isRequired,\n\n specUrl: PropTypes.string.isRequired,\n\n children: PropTypes.element,\n }\n\n render() {\n const {\n tagObj,\n tag,\n children,\n oas3Selectors,\n layoutSelectors,\n layoutActions,\n getConfigs,\n getComponent,\n specUrl,\n } = this.props\n\n let {\n docExpansion,\n deepLinking,\n } = getConfigs()\n\n const Collapse = getComponent(\"Collapse\")\n const Markdown = getComponent(\"Markdown\", true)\n const DeepLink = getComponent(\"DeepLink\")\n const Link = getComponent(\"Link\")\n const ArrowUpIcon = getComponent(\"ArrowUpIcon\")\n const ArrowDownIcon = getComponent(\"ArrowDownIcon\")\n\n let tagDescription = tagObj.getIn([\"tagDetails\", \"description\"], null)\n let tagExternalDocsDescription = tagObj.getIn([\"tagDetails\", \"externalDocs\", \"description\"])\n let rawTagExternalDocsUrl = tagObj.getIn([\"tagDetails\", \"externalDocs\", \"url\"])\n let tagExternalDocsUrl\n if (isFunc(oas3Selectors) && isFunc(oas3Selectors.selectedServer)) {\n tagExternalDocsUrl = safeBuildUrl(rawTagExternalDocsUrl, specUrl, { selectedServer: oas3Selectors.selectedServer() })\n } else {\n tagExternalDocsUrl = rawTagExternalDocsUrl\n }\n\n let isShownKey = [\"operations-tag\", tag]\n let showTag = layoutSelectors.isShown(isShownKey, docExpansion === \"full\" || docExpansion === \"list\")\n\n return (\n
\n\n layoutActions.show(isShownKey, !showTag)}\n className={!tagDescription ? \"opblock-tag no-desc\" : \"opblock-tag\"}\n id={isShownKey.map(v => escapeDeepLinkPath(v)).join(\"-\")}\n data-tag={tag}\n data-is-open={showTag}\n >\n \n {!tagDescription ? :\n \n \n \n }\n\n {!tagExternalDocsUrl ? null :\n
\n \n e.stopPropagation()}\n target=\"_blank\"\n >{tagExternalDocsDescription || tagExternalDocsUrl}\n \n
\n }\n\n\n layoutActions.show(isShownKey, !showTag)}>\n\n {showTag ? : }\n \n \n\n \n {children}\n \n
\n )\n }\n}\n","import React, { PureComponent } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { getExtensions, escapeDeepLinkPath, getList } from \"core/utils\"\nimport { safeBuildUrl, sanitizeUrl } from \"core/utils/url\"\nimport { Iterable, List } from \"immutable\"\nimport ImPropTypes from \"react-immutable-proptypes\"\n\nimport RollingLoadSVG from \"core/assets/rolling-load.svg\"\n\nexport default class Operation extends PureComponent {\n static propTypes = {\n specPath: ImPropTypes.list.isRequired,\n operation: PropTypes.instanceOf(Iterable).isRequired,\n summary: PropTypes.string,\n response: PropTypes.instanceOf(Iterable),\n request: PropTypes.instanceOf(Iterable),\n\n toggleShown: PropTypes.func.isRequired,\n onTryoutClick: PropTypes.func.isRequired,\n onResetClick: PropTypes.func.isRequired,\n onCancelClick: PropTypes.func.isRequired,\n onExecute: PropTypes.func.isRequired,\n\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n authActions: PropTypes.object,\n authSelectors: PropTypes.object,\n specActions: PropTypes.object.isRequired,\n specSelectors: PropTypes.object.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n oas3Selectors: PropTypes.object.isRequired,\n layoutActions: PropTypes.object.isRequired,\n layoutSelectors: PropTypes.object.isRequired,\n fn: PropTypes.object.isRequired\n }\n\n static defaultProps = {\n operation: null,\n response: null,\n request: null,\n specPath: List(),\n summary: \"\"\n }\n\n render() {\n let {\n specPath,\n response,\n request,\n toggleShown,\n onTryoutClick,\n onResetClick,\n onCancelClick,\n onExecute,\n fn,\n getComponent,\n getConfigs,\n specActions,\n specSelectors,\n authActions,\n authSelectors,\n oas3Actions,\n oas3Selectors\n } = this.props\n let operationProps = this.props.operation\n\n let {\n deprecated,\n isShown,\n path,\n method,\n op,\n tag,\n operationId,\n allowTryItOut,\n displayRequestDuration,\n tryItOutEnabled,\n executeInProgress\n } = operationProps.toObject()\n\n const description = op.get(\"description\")\n const externalDocs = op.get(\"externalDocs\")?.toJS()\n const schemes = op.get(\"schemes\")?.toJS()\n\n const externalDocsUrl = externalDocs ? safeBuildUrl(externalDocs.url, specSelectors.url(), { selectedServer: oas3Selectors.selectedServer() }) : \"\"\n let operation = operationProps.getIn([\"op\"])\n let responses = operation.get(\"responses\")\n let parameters = getList(operation, [\"parameters\"])\n let operationScheme = specSelectors.operationScheme(path, method)\n let isShownKey = [\"operations\", tag, operationId]\n let extensions = getExtensions(operation)\n\n const Responses = getComponent(\"responses\", true)\n const Parameters = getComponent( \"parameters\", true )\n const Execute = getComponent( \"execute\" )\n const Clear = getComponent( \"clear\" )\n const Collapse = getComponent( \"Collapse\" )\n const Markdown = getComponent(\"Markdown\", true)\n const Schemes = getComponent( \"schemes\" )\n const OperationServers = getComponent( \"OperationServers\" )\n const OperationExt = getComponent( \"OperationExt\" )\n const OperationSummary = getComponent( \"OperationSummary\" )\n const Link = getComponent( \"Link\" )\n\n const { showExtensions } = getConfigs()\n\n // Merge in Live Response\n if(responses && response && response.size > 0) {\n let notDocumented = !responses.get(String(response.get(\"status\"))) && !responses.get(\"default\")\n response = response.set(\"notDocumented\", notDocumented)\n }\n\n let onChangeKey = [ path, method ] // Used to add values to _this_ operation ( indexed by path and method )\n\n const validationErrors = specSelectors.validationErrors([path, method])\n\n return (\n
\n \n \n
\n { (operation && operation.size) || operation === null ? null :\n \n }\n { deprecated &&

Warning: Deprecated

}\n { description &&\n
\n
\n \n
\n
\n }\n {\n externalDocsUrl ?\n
\n

Find more details

\n
\n {externalDocs.description &&\n \n \n \n }\n {externalDocsUrl}\n
\n
: null\n }\n\n { !operation || !operation.size ? null :\n \n }\n\n { !tryItOutEnabled ? null :\n \n }\n\n {!tryItOutEnabled || !allowTryItOut ? null : schemes && schemes.size ?
\n \n
: null\n }\n\n { !tryItOutEnabled || !allowTryItOut || validationErrors.length <= 0 ? null :
\n Please correct the following validation errors and try again.\n
    \n { validationErrors.map((error, index) =>
  • { error }
  • ) }\n
\n
\n }\n\n
\n { !tryItOutEnabled || !allowTryItOut ? null :\n\n \n }\n\n { (!tryItOutEnabled || !response || !allowTryItOut) ? null :\n \n }\n
\n\n {executeInProgress ?
: null}\n\n { !responses ? null :\n \n }\n\n { !showExtensions || !extensions.size ? null :\n \n }\n
\n
\n
\n )\n }\n\n}\n","import React, { PureComponent } from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport { opId } from \"swagger-client/es/helpers\"\nimport { Iterable, fromJS, Map } from \"immutable\"\n\nexport default class OperationContainer extends PureComponent {\n constructor(props, context) {\n super(props, context)\n\n const { tryItOutEnabled } = props.getConfigs()\n\n this.state = {\n tryItOutEnabled,\n executeInProgress: false\n }\n }\n\n static propTypes = {\n op: PropTypes.instanceOf(Iterable).isRequired,\n tag: PropTypes.string.isRequired,\n path: PropTypes.string.isRequired,\n method: PropTypes.string.isRequired,\n operationId: PropTypes.string.isRequired,\n showSummary: PropTypes.bool.isRequired,\n isShown: PropTypes.bool.isRequired,\n jumpToKey: PropTypes.string.isRequired,\n allowTryItOut: PropTypes.bool,\n displayOperationId: PropTypes.bool,\n isAuthorized: PropTypes.bool,\n displayRequestDuration: PropTypes.bool,\n response: PropTypes.instanceOf(Iterable),\n request: PropTypes.instanceOf(Iterable),\n security: PropTypes.instanceOf(Iterable),\n isDeepLinkingEnabled: PropTypes.bool.isRequired,\n specPath: ImPropTypes.list.isRequired,\n getComponent: PropTypes.func.isRequired,\n authActions: PropTypes.object,\n oas3Actions: PropTypes.object,\n oas3Selectors: PropTypes.object,\n authSelectors: PropTypes.object,\n specActions: PropTypes.object.isRequired,\n specSelectors: PropTypes.object.isRequired,\n layoutActions: PropTypes.object.isRequired,\n layoutSelectors: PropTypes.object.isRequired,\n fn: PropTypes.object.isRequired,\n getConfigs: PropTypes.func.isRequired\n }\n\n static defaultProps = {\n showSummary: true,\n response: null,\n allowTryItOut: true,\n displayOperationId: false,\n displayRequestDuration: false\n }\n\n mapStateToProps(nextState, props) {\n const { op, layoutSelectors, getConfigs } = props\n const { docExpansion, deepLinking, displayOperationId, displayRequestDuration, supportedSubmitMethods } = getConfigs()\n const showSummary = layoutSelectors.showSummary()\n const operationId = op.getIn([\"operation\", \"__originalOperationId\"]) || op.getIn([\"operation\", \"operationId\"]) || opId(op.get(\"operation\"), props.path, props.method) || op.get(\"id\")\n const isShownKey = [\"operations\", props.tag, operationId]\n const allowTryItOut = supportedSubmitMethods.indexOf(props.method) >= 0 && (typeof props.allowTryItOut === \"undefined\" ?\n props.specSelectors.allowTryItOutFor(props.path, props.method) : props.allowTryItOut)\n const security = op.getIn([\"operation\", \"security\"]) || props.specSelectors.security()\n\n return {\n operationId,\n isDeepLinkingEnabled: deepLinking,\n showSummary,\n displayOperationId,\n displayRequestDuration,\n allowTryItOut,\n security,\n isAuthorized: props.authSelectors.isAuthorized(security),\n isShown: layoutSelectors.isShown(isShownKey, docExpansion === \"full\" ),\n jumpToKey: `paths.${props.path}.${props.method}`,\n response: props.specSelectors.responseFor(props.path, props.method),\n request: props.specSelectors.requestFor(props.path, props.method)\n }\n }\n\n componentDidMount() {\n const { isShown } = this.props\n const resolvedSubtree = this.getResolvedSubtree()\n\n if(isShown && resolvedSubtree === undefined) {\n this.requestResolvedSubtree()\n }\n }\n\n componentDidUpdate(prevProps) {\n const { response, isShown } = this.props\n const resolvedSubtree = this.getResolvedSubtree()\n\n if (response !== prevProps.response) {\n this.setState({ executeInProgress: false })\n }\n\n if (isShown && resolvedSubtree === undefined) {\n this.requestResolvedSubtree()\n }\n }\n\n toggleShown =() => {\n let { layoutActions, tag, operationId, isShown } = this.props\n const resolvedSubtree = this.getResolvedSubtree()\n if(!isShown && resolvedSubtree === undefined) {\n // transitioning from collapsed to expanded\n this.requestResolvedSubtree()\n }\n layoutActions.show([\"operations\", tag, operationId], !isShown)\n }\n\n onCancelClick=() => {\n this.setState({tryItOutEnabled: !this.state.tryItOutEnabled})\n }\n\n onTryoutClick =() => {\n this.setState({tryItOutEnabled: !this.state.tryItOutEnabled})\n }\n\n onResetClick = (pathMethod) => {\n const defaultRequestBodyValue = this.props.oas3Selectors.selectDefaultRequestBodyValue(...pathMethod)\n const contentType = this.props.oas3Selectors.requestContentType(...pathMethod)\n\n if (contentType === \"application/x-www-form-urlencoded\" || contentType === \"multipart/form-data\") {\n const jsonRequestBodyValue = JSON.parse(defaultRequestBodyValue)\n Object.entries(jsonRequestBodyValue).forEach(([key, value]) => {\n if (Array.isArray(value)) {\n jsonRequestBodyValue[key] = jsonRequestBodyValue[key].map((val) => {\n if (typeof val === \"object\") {\n return JSON.stringify(val, null, 2)\n }\n return val\n })\n } else if (typeof value === \"object\") {\n jsonRequestBodyValue[key] = JSON.stringify(jsonRequestBodyValue[key], null, 2)\n }\n })\n this.props.oas3Actions.setRequestBodyValue({ value: fromJS(jsonRequestBodyValue), pathMethod })\n } else {\n this.props.oas3Actions.setRequestBodyValue({ value: defaultRequestBodyValue, pathMethod })\n }\n }\n\n onExecute = () => {\n this.setState({ executeInProgress: true })\n }\n\n getResolvedSubtree = () => {\n const {\n specSelectors,\n path,\n method,\n specPath\n } = this.props\n\n if(specPath) {\n return specSelectors.specResolvedSubtree(specPath.toJS())\n }\n\n return specSelectors.specResolvedSubtree([\"paths\", path, method])\n }\n\n requestResolvedSubtree = () => {\n const {\n specActions,\n path,\n method,\n specPath\n } = this.props\n\n\n if(specPath) {\n return specActions.requestResolvedSubtree(specPath.toJS())\n }\n\n return specActions.requestResolvedSubtree([\"paths\", path, method])\n }\n\n render() {\n let {\n op: unresolvedOp,\n tag,\n path,\n method,\n security,\n isAuthorized,\n operationId,\n showSummary,\n isShown,\n jumpToKey,\n allowTryItOut,\n response,\n request,\n displayOperationId,\n displayRequestDuration,\n isDeepLinkingEnabled,\n specPath,\n specSelectors,\n specActions,\n getComponent,\n getConfigs,\n layoutSelectors,\n layoutActions,\n authActions,\n authSelectors,\n oas3Actions,\n oas3Selectors,\n fn\n } = this.props\n\n const Operation = getComponent( \"operation\" )\n\n const resolvedSubtree = this.getResolvedSubtree() || Map()\n\n const operationProps = fromJS({\n op: resolvedSubtree,\n tag,\n path,\n summary: unresolvedOp.getIn([\"operation\", \"summary\"]) || \"\",\n deprecated: resolvedSubtree.get(\"deprecated\") || unresolvedOp.getIn([\"operation\", \"deprecated\"]) || false,\n method,\n security,\n isAuthorized,\n operationId,\n originalOperationId: resolvedSubtree.getIn([\"operation\", \"__originalOperationId\"]),\n showSummary,\n isShown,\n jumpToKey,\n allowTryItOut,\n request,\n displayOperationId,\n displayRequestDuration,\n isDeepLinkingEnabled,\n executeInProgress: this.state.executeInProgress,\n tryItOutEnabled: this.state.tryItOutEnabled\n })\n\n return (\n \n )\n }\n\n}\n","import React, { PureComponent } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { Iterable, List } from \"immutable\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport toString from \"lodash/toString\"\n\n\nexport default class OperationSummary extends PureComponent {\n\n static propTypes = {\n specPath: ImPropTypes.list.isRequired,\n operationProps: PropTypes.instanceOf(Iterable).isRequired,\n isShown: PropTypes.bool.isRequired,\n toggleShown: PropTypes.func.isRequired,\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n authActions: PropTypes.object,\n authSelectors: PropTypes.object,\n }\n\n static defaultProps = {\n operationProps: null,\n specPath: List(),\n summary: \"\"\n }\n\n render() {\n\n let {\n isShown,\n toggleShown,\n getComponent,\n authActions,\n authSelectors,\n operationProps,\n specPath,\n } = this.props\n\n let {\n summary,\n isAuthorized,\n method,\n op,\n showSummary,\n path,\n operationId,\n originalOperationId,\n displayOperationId,\n } = operationProps.toObject()\n\n const resolvedSummary = op.get(\"summary\")\n const security = operationProps.get(\"security\")\n\n const AuthorizeOperationBtn = getComponent(\"authorizeOperationBtn\", true)\n const OperationSummaryMethod = getComponent(\"OperationSummaryMethod\")\n const OperationSummaryPath = getComponent(\"OperationSummaryPath\")\n const JumpToPath = getComponent(\"JumpToPath\", true)\n const CopyToClipboardBtn = getComponent(\"CopyToClipboardBtn\", true)\n const ArrowUpIcon = getComponent(\"ArrowUpIcon\")\n const ArrowDownIcon = getComponent(\"ArrowDownIcon\")\n\n const hasSecurity = security && !!security.count()\n const securityIsOptional = hasSecurity && security.size === 1 && security.first().isEmpty()\n const allowAnonymous = !hasSecurity || securityIsOptional\n return (\n
\n \n \n
\n \n\n {!showSummary ? null :\n
\n {toString(resolvedSummary || summary)}\n
\n }\n
\n\n {displayOperationId && (originalOperationId || operationId) ? {originalOperationId || operationId} : null}\n \n \n {\n allowAnonymous ? null :\n {\n const applicableDefinitions = authSelectors.definitionsForRequirements(security)\n authActions.showDefinitions(applicableDefinitions)\n }}\n />\n }\n {/* TODO: use wrapComponents here, swagger-ui doesn't care about jumpToPath */}\n \n {isShown ? : }\n \n
\n )\n }\n}\n","import React, { PureComponent } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { Iterable } from \"immutable\"\n\nexport default class OperationSummaryMethod extends PureComponent {\n\n static propTypes = {\n operationProps: PropTypes.instanceOf(Iterable).isRequired,\n method: PropTypes.string.isRequired,\n }\n\n static defaultProps = {\n operationProps: null,\n }\n render() {\n\n let {\n method,\n } = this.props\n\n return (\n {method.toUpperCase()}\n )\n }\n}\n","import React, { PureComponent } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { Iterable } from \"immutable\"\nimport { createDeepLinkPath } from \"core/utils\"\nimport ImPropTypes from \"react-immutable-proptypes\"\n\nexport default class OperationSummaryPath extends PureComponent{\n\n static propTypes = {\n specPath: ImPropTypes.list.isRequired,\n operationProps: PropTypes.instanceOf(Iterable).isRequired,\n getComponent: PropTypes.func.isRequired,\n }\n\n render(){\n let {\n getComponent,\n operationProps,\n } = this.props\n\n\n let {\n deprecated,\n isShown,\n path,\n tag,\n operationId,\n isDeepLinkingEnabled,\n } = operationProps.toObject()\n\n /**\n * Add word-break elements between each segment, before the slash\n * to allow browsers an opportunity to break long paths into sensible segments.\n */\n const pathParts = path.split(/(?=\\/)/g)\n for (let i = 1; i < pathParts.length; i += 2) {\n pathParts.splice(i, 0, )\n }\n\n const DeepLink = getComponent( \"DeepLink\" )\n\n return(\n \n \n \n\n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport const OperationExt = ({ extensions, getComponent }) => {\n let OperationExtRow = getComponent(\"OperationExtRow\")\n return (\n
\n
\n

Extensions

\n
\n
\n\n \n \n \n \n \n \n \n \n {\n extensions.entrySeq().map(([k, v]) => )\n }\n \n
FieldValue
\n
\n
\n )\n}\nOperationExt.propTypes = {\n extensions: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired\n}\n\nexport default OperationExt\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport const OperationExtRow = ({ xKey, xVal }) => {\n const xNormalizedValue = !xVal ? null : xVal.toJS ? xVal.toJS() : xVal\n\n return (\n { xKey }\n { JSON.stringify(xNormalizedValue) }\n )\n}\nOperationExtRow.propTypes = {\n xKey: PropTypes.string,\n xVal: PropTypes.any\n}\n\nexport default OperationExtRow\n","/**\n * Replace invalid characters from a string to create an html-ready ID\n *\n * @param {string} id A string that may contain invalid characters for the HTML ID attribute\n * @param {string} [replacement=_] The string to replace invalid characters with; \"_\" by default\n * @return {string} Information about the parameter schema\n */\nexport default function createHtmlReadyId(id, replacement = \"_\") {\n return id.replace(/[^\\w-]/g, replacement)\n}\n","import React from \"react\"\nimport { fromJS, Iterable } from \"immutable\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport { defaultStatusCode, getAcceptControllingResponse, isExtension } from \"core/utils\"\nimport createHtmlReadyId from \"core/utils/create-html-ready-id\"\n\nexport default class Responses extends React.Component {\n static propTypes = {\n tryItOutResponse: PropTypes.instanceOf(Iterable),\n responses: PropTypes.instanceOf(Iterable).isRequired,\n produces: PropTypes.instanceOf(Iterable),\n producesValue: PropTypes.any,\n displayRequestDuration: PropTypes.bool.isRequired,\n path: PropTypes.string.isRequired,\n method: PropTypes.string.isRequired,\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n specSelectors: PropTypes.object.isRequired,\n specActions: PropTypes.object.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n oas3Selectors: PropTypes.object.isRequired,\n specPath: ImPropTypes.list.isRequired,\n fn: PropTypes.object.isRequired\n }\n\n static defaultProps = {\n tryItOutResponse: null,\n produces: fromJS([\"application/json\"]),\n displayRequestDuration: false\n }\n\n // These performance-enhancing checks were disabled as part of Multiple Examples\n // because they were causing data-consistency issues\n //\n // shouldComponentUpdate(nextProps) {\n // // BUG: props.tryItOutResponse is always coming back as a new Immutable instance\n // let render = this.props.tryItOutResponse !== nextProps.tryItOutResponse\n // || this.props.responses !== nextProps.responses\n // || this.props.produces !== nextProps.produces\n // || this.props.producesValue !== nextProps.producesValue\n // || this.props.displayRequestDuration !== nextProps.displayRequestDuration\n // || this.props.path !== nextProps.path\n // || this.props.method !== nextProps.method\n // return render\n // }\n\n\tonChangeProducesWrapper = ( val ) => this.props.specActions.changeProducesValue([this.props.path, this.props.method], val)\n\n onResponseContentTypeChange = ({ controlsAcceptHeader, value }) => {\n const { oas3Actions, path, method } = this.props\n if(controlsAcceptHeader) {\n oas3Actions.setResponseContentType({\n value,\n path,\n method\n })\n }\n }\n\n render() {\n let {\n responses,\n tryItOutResponse,\n getComponent,\n getConfigs,\n specSelectors,\n fn,\n producesValue,\n displayRequestDuration,\n specPath,\n path,\n method,\n oas3Selectors,\n oas3Actions,\n } = this.props\n let defaultCode = defaultStatusCode( responses )\n\n const ContentType = getComponent( \"contentType\" )\n const LiveResponse = getComponent( \"liveResponse\" )\n const Response = getComponent( \"response\" )\n\n let produces = this.props.produces && this.props.produces.size ? this.props.produces : Responses.defaultProps.produces\n\n const isSpecOAS3 = specSelectors.isOAS3()\n\n const acceptControllingResponse = isSpecOAS3 ?\n getAcceptControllingResponse(responses) : null\n\n const nonExtensionResponses = responses.filter((_, key) => !isExtension(key))\n const regionId = createHtmlReadyId(`${method}${path}_responses`)\n const controlId = `${regionId}_select`\n\n return (!nonExtensionResponses || !nonExtensionResponses.size) ? null : (\n
\n
\n

Responses

\n { specSelectors.isOAS3() ? null : }\n
\n
\n {\n !tryItOutResponse ? null\n :
\n \n

Responses

\n
\n\n }\n\n \n \n \n \n \n { specSelectors.isOAS3() ? : null }\n \n \n \n {\n nonExtensionResponses.entrySeq().map( ([code, response]) => {\n\n let className = tryItOutResponse && tryItOutResponse.get(\"status\") == code ? \"response_current\" : \"\"\n return (\n \n )\n }).toArray()\n }\n \n
CodeDescriptionLinks
\n
\n
\n )\n }\n}\n","export function canJsonParse(str) {\n try {\n let testValueForJson = JSON.parse(str)\n return testValueForJson ? true : false\n } catch (e) {\n // exception: string is not valid json\n return null\n }\n}\n\nexport function getKnownSyntaxHighlighterLanguage(val) {\n // to start, only check for json. can expand as needed in future\n const isValidJson = canJsonParse(val)\n return isValidJson ? \"json\" : null\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport cx from \"classnames\"\nimport { fromJS, Seq, Iterable, Map } from \"immutable\"\nimport { getExtensions, fromJSOrdered, stringify } from \"core/utils\"\nimport { getKnownSyntaxHighlighterLanguage } from \"core/utils/jsonParse\"\n\n\nconst getExampleComponent = ( sampleResponse, HighlightCode ) => {\n if (sampleResponse == null) return null\n\n const testValueForJson = getKnownSyntaxHighlighterLanguage(sampleResponse)\n const language = testValueForJson ? \"json\" : null\n\n return (\n
\n {stringify(sampleResponse)}\n
\n )\n}\n\nexport default class Response extends React.Component {\n constructor(props, context) {\n super(props, context)\n\n this.state = {\n responseContentType: \"\",\n }\n }\n\n static propTypes = {\n path: PropTypes.string.isRequired,\n method: PropTypes.string.isRequired,\n code: PropTypes.string.isRequired,\n response: PropTypes.instanceOf(Iterable),\n className: PropTypes.string,\n getComponent: PropTypes.func.isRequired,\n getConfigs: PropTypes.func.isRequired,\n specSelectors: PropTypes.object.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n specPath: ImPropTypes.list.isRequired,\n fn: PropTypes.object.isRequired,\n contentType: PropTypes.string,\n activeExamplesKey: PropTypes.string,\n controlsAcceptHeader: PropTypes.bool,\n onContentTypeChange: PropTypes.func\n }\n\n static defaultProps = {\n response: fromJS({}),\n onContentTypeChange: () => {}\n }\n\n _onContentTypeChange = (value) => {\n const { onContentTypeChange, controlsAcceptHeader } = this.props\n this.setState({ responseContentType: value })\n onContentTypeChange({\n value: value,\n controlsAcceptHeader\n })\n }\n\n getTargetExamplesKey = () => {\n const { response, contentType, activeExamplesKey } = this.props\n\n const activeContentType = this.state.responseContentType || contentType\n const activeMediaType = response.getIn([\"content\", activeContentType], Map({}))\n const examplesForMediaType = activeMediaType.get(\"examples\", null)\n\n const firstExamplesKey = examplesForMediaType.keySeq().first()\n return activeExamplesKey || firstExamplesKey\n }\n\n render() {\n let {\n path,\n method,\n code,\n response,\n className,\n specPath,\n fn,\n getComponent,\n getConfigs,\n specSelectors,\n contentType,\n controlsAcceptHeader,\n oas3Actions,\n } = this.props\n\n let { inferSchema, getSampleSchema } = fn\n let isOAS3 = specSelectors.isOAS3()\n const { showExtensions } = getConfigs()\n\n let extensions = showExtensions ? getExtensions(response) : null\n let headers = response.get(\"headers\")\n let links = response.get(\"links\")\n const ResponseExtension = getComponent(\"ResponseExtension\")\n const Headers = getComponent(\"headers\")\n const HighlightCode = getComponent(\"HighlightCode\", true)\n const ModelExample = getComponent(\"modelExample\")\n const Markdown = getComponent(\"Markdown\", true)\n const OperationLink = getComponent(\"operationLink\")\n const ContentType = getComponent(\"contentType\")\n const ExamplesSelect = getComponent(\"ExamplesSelect\")\n const Example = getComponent(\"Example\")\n\n\n var schema, specPathWithPossibleSchema\n\n const activeContentType = this.state.responseContentType || contentType\n const activeMediaType = response.getIn([\"content\", activeContentType], Map({}))\n const examplesForMediaType = activeMediaType.get(\"examples\", null)\n\n // Goal: find a schema value for `schema`\n if(isOAS3) {\n const oas3SchemaForContentType = activeMediaType.get(\"schema\")\n\n schema = oas3SchemaForContentType ? inferSchema(oas3SchemaForContentType.toJS()) : null\n specPathWithPossibleSchema = oas3SchemaForContentType\n ? specPath.push(\"content\", this.state.responseContentType, \"schema\")\n : specPath\n } else {\n schema = response.get(\"schema\")\n specPathWithPossibleSchema = response.has(\"schema\") ? specPath.push(\"schema\") : specPath\n }\n\n let mediaTypeExample\n let shouldOverrideSchemaExample = false\n let sampleSchema\n let sampleGenConfig = {\n includeReadOnly: true\n }\n\n // Goal: find an example value for `sampleResponse`\n if(isOAS3) {\n sampleSchema = activeMediaType.get(\"schema\")?.toJS()\n if(Map.isMap(examplesForMediaType) && !examplesForMediaType.isEmpty()) {\n const targetExamplesKey = this.getTargetExamplesKey()\n const targetExample = examplesForMediaType\n .get(targetExamplesKey, Map({}))\n const getMediaTypeExample = (targetExample) =>\n Map.isMap(targetExample) \n ? targetExample.get(\"value\") \n : undefined\n mediaTypeExample = getMediaTypeExample(targetExample)\n if(mediaTypeExample === undefined) {\n mediaTypeExample = getMediaTypeExample(examplesForMediaType.values().next().value)\n }\n shouldOverrideSchemaExample = true\n } else if(activeMediaType.get(\"example\") !== undefined) {\n // use the example key's value\n mediaTypeExample = activeMediaType.get(\"example\")\n shouldOverrideSchemaExample = true\n }\n } else {\n sampleSchema = schema\n sampleGenConfig = {...sampleGenConfig, includeWriteOnly: true}\n const oldOASMediaTypeExample = response.getIn([\"examples\", activeContentType])\n if(oldOASMediaTypeExample) {\n mediaTypeExample = oldOASMediaTypeExample\n shouldOverrideSchemaExample = true\n }\n }\n\n const sampleResponse = getSampleSchema(\n sampleSchema,\n activeContentType,\n sampleGenConfig,\n shouldOverrideSchemaExample ? mediaTypeExample : undefined\n )\n\n const example = getExampleComponent( sampleResponse, HighlightCode )\n\n return (\n \n \n { code }\n \n \n\n
\n \n
\n\n { !showExtensions || !extensions.size ? null : extensions.entrySeq().map(([key, v]) => )}\n\n {isOAS3 && response.get(\"content\") ? (\n
\n \n \n Media type\n \n \n {controlsAcceptHeader ? (\n \n Controls Accept header.\n \n ) : null}\n \n {Map.isMap(examplesForMediaType) && !examplesForMediaType.isEmpty() ? (\n
\n \n Examples\n \n \n oas3Actions.setActiveExamplesMember({\n name: key,\n pathMethod: [path, method],\n contextType: \"responses\",\n contextName: code\n })\n }\n showLabels={false}\n />\n
\n ) : null}\n
\n ) : null}\n\n { example || schema ? (\n \n ) : null }\n\n { isOAS3 && examplesForMediaType ? (\n \n ) : null}\n\n { headers ? (\n \n ) : null}\n\n \n {isOAS3 ? \n { links ?\n links.toSeq().entrySeq().map(([key, link]) => {\n return \n })\n : No links}\n : null}\n \n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport const ResponseExtension = ({ xKey, xVal }) => {\n return
{ xKey }: { String(xVal) }
\n}\nResponseExtension.propTypes = {\n xKey: PropTypes.string,\n xVal: PropTypes.any\n}\n\nexport default ResponseExtension\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport formatXml from \"xml-but-prettier\"\nimport toLower from \"lodash/toLower\"\nimport { extractFileNameFromContentDispositionHeader } from \"core/utils\"\nimport { getKnownSyntaxHighlighterLanguage } from \"core/utils/jsonParse\"\nimport win from \"core/window\"\n\nexport default class ResponseBody extends React.PureComponent {\n state = {\n parsedContent: null\n }\n\n static propTypes = {\n content: PropTypes.any.isRequired,\n contentType: PropTypes.string,\n getComponent: PropTypes.func.isRequired,\n headers: PropTypes.object,\n url: PropTypes.string\n }\n\n updateParsedContent = (prevContent) => {\n const { content } = this.props\n\n if(prevContent === content) {\n return\n }\n\n if(content && content instanceof Blob) {\n var reader = new FileReader()\n reader.onload = () => {\n this.setState({\n parsedContent: reader.result\n })\n }\n reader.readAsText(content)\n } else {\n this.setState({\n parsedContent: content.toString()\n })\n }\n }\n\n componentDidMount() {\n this.updateParsedContent(null)\n }\n\n componentDidUpdate(prevProps) {\n this.updateParsedContent(prevProps.content)\n }\n\n render() {\n let { content, contentType, url, headers={}, getComponent } = this.props\n const { parsedContent } = this.state\n const HighlightCode = getComponent(\"HighlightCode\", true)\n const downloadName = \"response_\" + new Date().getTime()\n let body, bodyEl\n url = url || \"\"\n\n if (\n (/^application\\/octet-stream/i.test(contentType) ||\n (headers[\"Content-Disposition\"] && /attachment/i.test(headers[\"Content-Disposition\"])) ||\n (headers[\"content-disposition\"] && /attachment/i.test(headers[\"content-disposition\"])) ||\n (headers[\"Content-Description\"] && /File Transfer/i.test(headers[\"Content-Description\"])) ||\n (headers[\"content-description\"] && /File Transfer/i.test(headers[\"content-description\"]))) &&\n (content.size > 0 || content.length > 0)\n ) {\n // Download\n\n if (\"Blob\" in window) {\n let type = contentType || \"text/html\"\n let blob = (content instanceof Blob) ? content : new Blob([content], {type: type})\n let href = window.URL.createObjectURL(blob)\n let fileName = url.substr(url.lastIndexOf(\"/\") + 1)\n let download = [type, fileName, href].join(\":\")\n\n // Use filename from response header,\n // First check if filename is quoted (e.g. contains space), if no, fallback to not quoted check\n let disposition = headers[\"content-disposition\"] || headers[\"Content-Disposition\"]\n if (typeof disposition !== \"undefined\") {\n let responseFilename = extractFileNameFromContentDispositionHeader(disposition)\n if (responseFilename !== null) {\n download = responseFilename\n }\n }\n\n if(win.navigator && win.navigator.msSaveOrOpenBlob) {\n bodyEl = \n } else {\n bodyEl = \n }\n } else {\n bodyEl =
Download headers detected but your browser does not support downloading binary via XHR (Blob).
\n }\n\n // Anything else (CORS)\n } else if (/json/i.test(contentType)) {\n // JSON\n let language = null\n let testValueForJson = getKnownSyntaxHighlighterLanguage(content)\n if (testValueForJson) {\n language = \"json\"\n }\n try {\n body = JSON.stringify(JSON.parse(content), null, \" \")\n } catch (error) {\n body = \"can't parse JSON. Raw result:\\n\\n\" + content\n }\n\n bodyEl = {body}\n\n // XML\n } else if (/xml/i.test(contentType)) {\n body = formatXml(content, {\n textNodesOnSameLine: true,\n indentor: \" \"\n })\n bodyEl = {body}\n\n // HTML or Plain Text\n } else if (toLower(contentType) === \"text/html\" || /text\\/plain/.test(contentType)) {\n bodyEl = {content}\n\n // CSV\n } else if (toLower(contentType) === \"text/csv\" || /text\\/csv/.test(contentType)) {\n bodyEl = {content}\n\n // Image\n } else if (/^image\\//i.test(contentType)) {\n if(contentType.includes(\"svg\")) {\n bodyEl =
{ content }
\n } else {\n bodyEl = \n }\n\n // Audio\n } else if (/^audio\\//i.test(contentType)) {\n bodyEl =
\n } else if (typeof content === \"string\") {\n bodyEl = {content}\n } else if ( content.size > 0 ) {\n // We don't know the contentType, but there was some content returned\n if(parsedContent) {\n // We were able to squeeze something out of content\n // in `updateParsedContent`, so let's display it\n bodyEl =
\n

\n Unrecognized response type; displaying content as text.\n

\n {parsedContent}\n
\n\n } else {\n // Give up\n bodyEl =

\n Unrecognized response type; unable to display.\n

\n }\n } else {\n // We don't know the contentType and there was no content returned\n bodyEl = null\n }\n\n return ( !bodyEl ? null :
\n
Response body
\n { bodyEl }\n
\n )\n }\n}\n","import React, { Component } from \"react\"\nimport PropTypes from \"prop-types\"\nimport { Map, List } from \"immutable\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport createHtmlReadyId from \"core/utils/create-html-ready-id\"\n\nexport default class Parameters extends Component {\n\n constructor(props) {\n super(props)\n this.state = {\n callbackVisible: false,\n parametersVisible: true,\n }\n }\n\n static propTypes = {\n parameters: ImPropTypes.list.isRequired,\n operation: PropTypes.object.isRequired,\n specActions: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n specSelectors: PropTypes.object.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n oas3Selectors: PropTypes.object.isRequired,\n fn: PropTypes.object.isRequired,\n tryItOutEnabled: PropTypes.bool,\n allowTryItOut: PropTypes.bool,\n onTryoutClick: PropTypes.func,\n onResetClick: PropTypes.func,\n onCancelClick: PropTypes.func,\n onChangeKey: PropTypes.array,\n pathMethod: PropTypes.array.isRequired,\n getConfigs: PropTypes.func.isRequired,\n specPath: ImPropTypes.list.isRequired,\n }\n\n\n static defaultProps = {\n onTryoutClick: Function.prototype,\n onCancelClick: Function.prototype,\n tryItOutEnabled: false,\n allowTryItOut: true,\n onChangeKey: [],\n specPath: [],\n }\n\n onChange = (param, value, isXml) => {\n let {\n specActions: { changeParamByIdentity },\n onChangeKey,\n } = this.props\n\n changeParamByIdentity(onChangeKey, param, value, isXml)\n }\n\n onChangeConsumesWrapper = (val) => {\n let {\n specActions: { changeConsumesValue },\n onChangeKey,\n } = this.props\n\n changeConsumesValue(onChangeKey, val)\n }\n\n toggleTab = (tab) => {\n if (tab === \"parameters\") {\n return this.setState({\n parametersVisible: true,\n callbackVisible: false,\n })\n } else if (tab === \"callbacks\") {\n return this.setState({\n callbackVisible: true,\n parametersVisible: false,\n })\n }\n }\n \n onChangeMediaType = ({ value, pathMethod }) => {\n let { specActions, oas3Selectors, oas3Actions } = this.props\n const userHasEditedBody = oas3Selectors.hasUserEditedBody(...pathMethod)\n const shouldRetainRequestBodyValue = oas3Selectors.shouldRetainRequestBodyValue(...pathMethod)\n oas3Actions.setRequestContentType({ value, pathMethod })\n oas3Actions.initRequestBodyValidateError({ pathMethod })\n if (!userHasEditedBody) {\n if(!shouldRetainRequestBodyValue) {\n oas3Actions.setRequestBodyValue({ value: undefined, pathMethod })\n }\n specActions.clearResponse(...pathMethod)\n specActions.clearRequest(...pathMethod)\n specActions.clearValidateParams(pathMethod)\n }\n }\n\n render() {\n\n let {\n onTryoutClick,\n onResetClick,\n parameters,\n allowTryItOut,\n tryItOutEnabled,\n specPath,\n fn,\n getComponent,\n getConfigs,\n specSelectors,\n specActions,\n pathMethod,\n oas3Actions,\n oas3Selectors,\n operation,\n } = this.props\n\n const ParameterRow = getComponent(\"parameterRow\")\n const TryItOutButton = getComponent(\"TryItOutButton\")\n const ContentType = getComponent(\"contentType\")\n const Callbacks = getComponent(\"Callbacks\", true)\n const RequestBody = getComponent(\"RequestBody\", true)\n\n const isExecute = tryItOutEnabled && allowTryItOut\n const isOAS3 = specSelectors.isOAS3()\n\n const regionId = createHtmlReadyId(`${pathMethod[1]}${pathMethod[0]}_requests`)\n const controlId = `${regionId}_select`\n\n const requestBody = operation.get(\"requestBody\")\n\n const groupedParametersArr = Object.values(parameters\n .reduce((acc, x) => {\n if (Map.isMap(x)) {\n const key = x.get(\"in\")\n acc[key] ??= []\n acc[key].push(x)\n }\n return acc\n }, {}))\n .reduce((acc, x) => acc.concat(x), [])\n\n const retainRequestBodyValueFlagForOperation = (f) => oas3Actions.setRetainRequestBodyValueFlag({ value: f, pathMethod })\n return (\n
\n
\n {isOAS3 ? (\n
\n
this.toggleTab(\"parameters\")}\n className={`tab-item ${this.state.parametersVisible && \"active\"}`}>\n

Parameters

\n
\n {operation.get(\"callbacks\") ?\n (\n
this.toggleTab(\"callbacks\")}\n className={`tab-item ${this.state.callbackVisible && \"active\"}`}>\n

Callbacks

\n
\n ) : null\n }\n
\n ) : (\n
\n

Parameters

\n
\n )}\n {allowTryItOut ? (\n onResetClick(pathMethod)}/>\n ) : null}\n
\n {this.state.parametersVisible ?
\n {!groupedParametersArr.length ?

No parameters

:\n
\n \n \n \n \n \n \n \n \n {\n groupedParametersArr.map((parameter, i) => (\n \n ))\n }\n \n
NameDescription
\n
\n }\n
: null}\n\n {this.state.callbackVisible ?
\n \n
: null}\n {\n isOAS3 && requestBody && this.state.parametersVisible &&\n
\n
\n

Request\n body

\n \n
\n
\n {\n this.props.oas3Actions.setActiveExamplesMember({\n name: key,\n pathMethod: this.props.pathMethod,\n contextType: \"requestBody\",\n contextName: \"requestBody\", // RBs are currently not stored per-mediaType\n })\n }\n }\n onChange={(value, path) => {\n if (path) {\n const lastValue = oas3Selectors.requestBodyValue(...pathMethod)\n const usableValue = Map.isMap(lastValue) ? lastValue : Map()\n return oas3Actions.setRequestBodyValue({\n pathMethod,\n value: usableValue.setIn(path, value),\n })\n }\n oas3Actions.setRequestBodyValue({ value, pathMethod })\n }}\n onChangeIncludeEmpty={(name, value) => {\n oas3Actions.setRequestBodyInclusion({\n pathMethod,\n value,\n name,\n })\n }}\n contentType={oas3Selectors.requestContentType(...pathMethod)} />\n
\n
\n }\n
\n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport const ParameterExt = ({ xKey, xVal }) => {\n return
{ xKey }: { String(xVal) }
\n}\nParameterExt.propTypes = {\n xKey: PropTypes.string,\n xVal: PropTypes.any\n}\n\nexport default ParameterExt\n","import React, { Component } from \"react\"\nimport cx from \"classnames\"\nimport PropTypes from \"prop-types\"\n\n\nconst noop = () => { }\n\nconst ParameterIncludeEmptyPropTypes = {\n isIncluded: PropTypes.bool.isRequired,\n isDisabled: PropTypes.bool.isRequired,\n isIncludedOptions: PropTypes.object,\n onChange: PropTypes.func.isRequired,\n}\n\nconst ParameterIncludeEmptyDefaultProps = {\n onChange: noop,\n isIncludedOptions: {},\n}\nexport default class ParameterIncludeEmpty extends Component {\n static propTypes = ParameterIncludeEmptyPropTypes\n static defaultProps = ParameterIncludeEmptyDefaultProps\n\n componentDidMount() {\n const { isIncludedOptions, onChange } = this.props\n const { shouldDispatchInit, defaultValue } = isIncludedOptions\n if (shouldDispatchInit) {\n onChange(defaultValue)\n }\n }\n\n onCheckboxChange = e => {\n const { onChange } = this.props\n onChange(e.target.checked)\n }\n\n render() {\n let { isIncluded, isDisabled } = this.props\n\n return (\n
\n \n
\n )\n }\n}\n","/**\n * @prettier\n */\n\nimport { List } from \"immutable\"\n\nexport const parseParameterArrayValue = (value) => {\n if (List.isList(value)) {\n return value\n }\n\n if (typeof value !== \"string\") {\n return null\n }\n\n try {\n const parsed = JSON.parse(value)\n\n return Array.isArray(parsed) ? List(parsed) : null\n } catch {\n return null\n }\n}\n","import React, { Component } from \"react\"\nimport { Map, List, fromJS } from \"immutable\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport win from \"core/window\"\nimport { getExtensions, getCommonExtensions, numberToString, stringify, isEmptyValue } from \"core/utils\"\nimport getParameterSchema from \"core/utils/get-parameter-schema.js\"\nimport { parseParameterArrayValue } from \"core/utils/parse-parameter-array-value\"\n\nexport default class ParameterRow extends Component {\n static propTypes = {\n onChange: PropTypes.func.isRequired,\n param: PropTypes.object.isRequired,\n rawParam: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n fn: PropTypes.object.isRequired,\n isExecute: PropTypes.bool,\n onChangeConsumes: PropTypes.func.isRequired,\n specSelectors: PropTypes.object.isRequired,\n specActions: PropTypes.object.isRequired,\n pathMethod: PropTypes.array.isRequired,\n getConfigs: PropTypes.func.isRequired,\n specPath: ImPropTypes.list.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n oas3Selectors: PropTypes.object.isRequired,\n }\n\n constructor(props, context) {\n super(props, context)\n\n this.setDefaultValue()\n }\n\n UNSAFE_componentWillReceiveProps(props) {\n let { specSelectors, pathMethod, rawParam } = props\n let isOAS3 = specSelectors.isOAS3()\n\n let parameterWithMeta = specSelectors.parameterWithMetaByIdentity(pathMethod, rawParam) || new Map()\n // fallback, if the meta lookup fails\n parameterWithMeta = parameterWithMeta.isEmpty() ? rawParam : parameterWithMeta\n\n let enumValue\n\n if(isOAS3) {\n let { schema } = getParameterSchema(parameterWithMeta, { isOAS3 })\n enumValue = schema ? schema.get(\"enum\") : undefined\n } else {\n enumValue = parameterWithMeta ? parameterWithMeta.get(\"enum\") : undefined\n }\n let paramValue = parameterWithMeta ? parameterWithMeta.get(\"value\") : undefined\n\n let value\n\n if ( paramValue !== undefined ) {\n value = paramValue\n } else if ( rawParam.get(\"required\") && enumValue && enumValue.size ) {\n value = enumValue.first()\n }\n\n if ( value !== undefined && value !== paramValue ) {\n this.onChangeWrapper(numberToString(value))\n }\n // todo: could check if schema here; if not, do not call. impact?\n this.setDefaultValue()\n }\n\n onChangeWrapper = (value, isXml = false) => {\n let { onChange, rawParam } = this.props\n let valueForUpstream\n\n // Coerce empty strings and empty Immutable objects to null\n if(value === \"\" || (value && value.size === 0)) {\n valueForUpstream = null\n } else {\n valueForUpstream = value\n }\n\n return onChange(rawParam, valueForUpstream, isXml)\n }\n\n _onExampleSelect = (key, /* { isSyntheticChange } = {} */) => {\n this.props.oas3Actions.setActiveExamplesMember({\n name: key,\n pathMethod: this.props.pathMethod,\n contextType: \"parameters\",\n contextName: this.getParamKey()\n })\n }\n\n onChangeIncludeEmpty = (newValue) => {\n let { specActions, param, pathMethod } = this.props\n const paramName = param.get(\"name\")\n const paramIn = param.get(\"in\")\n return specActions.updateEmptyParamInclusion(pathMethod, paramName, paramIn, newValue)\n }\n\n setDefaultValue = () => {\n let { specSelectors, pathMethod, rawParam, oas3Selectors, fn } = this.props\n const isOAS3 = specSelectors.isOAS3()\n\n const paramWithMeta = specSelectors.parameterWithMetaByIdentity(pathMethod, rawParam) || Map()\n let { schema } = getParameterSchema(paramWithMeta, { isOAS3 })\n const parameterMediaType = paramWithMeta\n .get(\"content\", Map())\n .keySeq()\n .first()\n\n // getSampleSchema could return null\n const generatedSampleValue = schema ? fn.getSampleSchema(schema.toJS(), parameterMediaType, {\n\n includeWriteOnly: true\n }) : null\n\n if (!paramWithMeta || paramWithMeta.get(\"value\") !== undefined) {\n return\n }\n\n if( paramWithMeta.get(\"in\") !== \"body\" ) {\n let initialValue\n\n //// Find an initial value\n\n if (specSelectors.isSwagger2()) {\n initialValue =\n paramWithMeta.get(\"x-example\") !== undefined\n ? paramWithMeta.get(\"x-example\")\n : paramWithMeta.getIn([\"schema\", \"example\"]) !== undefined\n ? paramWithMeta.getIn([\"schema\", \"example\"])\n : (schema && schema.getIn([\"default\"]))\n } else if (isOAS3) {\n schema = this.composeJsonSchema(schema)\n\n const currentExampleKey = oas3Selectors.activeExamplesMember(...pathMethod, \"parameters\", this.getParamKey())\n initialValue =\n paramWithMeta.getIn([\"examples\", currentExampleKey, \"value\"]) !== undefined\n ? paramWithMeta.getIn([\"examples\", currentExampleKey, \"value\"])\n : paramWithMeta.getIn([\"content\", parameterMediaType, \"example\"]) !== undefined\n ? paramWithMeta.getIn([\"content\", parameterMediaType, \"example\"])\n : paramWithMeta.get(\"example\") !== undefined\n ? paramWithMeta.get(\"example\")\n : (schema && schema.get(\"example\")) !== undefined\n ? (schema && schema.get(\"example\"))\n : (schema && schema.get(\"default\")) !== undefined\n ? (schema && schema.get(\"default\"))\n : paramWithMeta.get(\"default\") // ensures support for `parameterMacro`\n }\n\n //// Process the initial value\n\n if(initialValue !== undefined && !List.isList(initialValue)) {\n // Stringify if it isn't a List\n initialValue = stringify(initialValue)\n }\n\n //// Dispatch the initial value\n\n const schemaObjectType = fn.getSchemaObjectType(schema)\n const schemaItemsType = fn.getSchemaObjectType(schema?.get(\"items\"))\n const hasMultipleTypes = List.isList(schema?.get(\"type\"))\n\n // Discard invalid array initial values (non-array, non-stringified-array)\n if (isOAS3 && schemaObjectType === \"array\" && !hasMultipleTypes && initialValue !== undefined) {\n const parsedValue = parseParameterArrayValue(initialValue)\n\n this.onChangeWrapper(parsedValue)\n return\n }\n\n if(initialValue !== undefined) {\n this.onChangeWrapper(initialValue)\n } else if(\n schemaObjectType === \"object\"\n && generatedSampleValue\n && !paramWithMeta.get(\"examples\")\n ) {\n // Object parameters get special treatment.. if the user doesn't set any\n // default or example values, we'll provide initial values generated from\n // the schema.\n // However, if `examples` exist for the parameter, we won't do anything,\n // so that the appropriate `examples` logic can take over.\n this.onChangeWrapper(\n List.isList(generatedSampleValue) ? (\n generatedSampleValue\n ) : (\n stringify(generatedSampleValue)\n )\n )\n }\n else if (\n schemaObjectType === \"array\"\n && schemaItemsType === \"object\"\n && generatedSampleValue\n && !paramWithMeta.get(\"examples\")\n ) {\n const parsedValue = parseParameterArrayValue(generatedSampleValue)\n \n this.onChangeWrapper(parsedValue)\n }\n }\n }\n\n\n\n onExampleValueUpdate = (value) => {\n const { specSelectors, pathMethod, rawParam, fn } = this.props\n\n const paramWithMeta = specSelectors.parameterWithMetaByIdentity(pathMethod, rawParam) || Map()\n let { schema } = getParameterSchema(paramWithMeta, { isOAS3: true })\n \n if (schema) {\n schema = this.composeJsonSchema(schema)\n }\n\n const schemaObjectType = fn.getSchemaObjectType(schema)\n const hasMultipleTypes = List.isList(schema?.get(\"type\"))\n\n if (schemaObjectType === \"array\" && !hasMultipleTypes) {\n const parsedValue = parseParameterArrayValue(value)\n\n this.onChangeWrapper(parsedValue)\n } else {\n this.onChangeWrapper(value)\n }\n }\n\n getParamKey() {\n const { param } = this.props\n\n if(!param) return null\n\n return `${param.get(\"name\")}-${param.get(\"in\")}`\n }\n\n composeJsonSchema(schema) {\n const { fn } = this.props\n const oneOf = schema.get(\"oneOf\")?.get(0)?.toJS()\n const anyOf = schema.get(\"anyOf\")?.get(0)?.toJS()\n return fromJS(fn.mergeJsonSchema(schema.toJS(), oneOf ?? anyOf ?? {}))\n }\n\n render() {\n let {param, rawParam, getComponent, getConfigs, isExecute, fn, onChangeConsumes, specSelectors, pathMethod, specPath, oas3Selectors} = this.props\n\n let isOAS3 = specSelectors.isOAS3()\n\n const { showExtensions, showCommonExtensions } = getConfigs()\n\n if(!param) {\n param = rawParam\n }\n\n if(!rawParam) return null\n\n // const onChangeWrapper = (value) => onChange(param, value)\n const JsonSchemaForm = getComponent(\"JsonSchemaForm\")\n const ParamBody = getComponent(\"ParamBody\")\n let inType = param.get(\"in\")\n let bodyParam = inType !== \"body\" ? null\n : \n\n const ModelExample = getComponent(\"modelExample\")\n const Markdown = getComponent(\"Markdown\", true)\n const ParameterExt = getComponent(\"ParameterExt\")\n const ParameterIncludeEmpty = getComponent(\"ParameterIncludeEmpty\")\n const ExamplesSelectValueRetainer = getComponent(\"ExamplesSelectValueRetainer\")\n const Example = getComponent(\"Example\")\n\n let { schema } = getParameterSchema(param, { isOAS3 })\n let paramWithMeta = specSelectors.parameterWithMetaByIdentity(pathMethod, rawParam) || Map()\n const parameterMediaType = paramWithMeta\n .get(\"content\", Map())\n .keySeq()\n .first()\n\n if (isOAS3) {\n schema = this.composeJsonSchema(schema)\n }\n\n let format = schema ? schema.get(\"format\") : null\n let isFormData = inType === \"formData\"\n let isFormDataSupported = \"FormData\" in win\n let required = param.get(\"required\")\n\n const schemaObjectType = fn.getSchemaObjectType(schema)\n const schemaItemsType = fn.getSchemaObjectType(schema?.get(\"items\"))\n const schemaObjectTypeLabel = fn.getSchemaObjectTypeLabel(schema)\n const isObject = !bodyParam && schemaObjectType === \"object\"\n const isArrayOfObjects = !bodyParam && schemaItemsType === \"object\"\n\n let value = paramWithMeta ? paramWithMeta.get(\"value\") : \"\"\n let commonExt = showCommonExtensions ? getCommonExtensions(schema) : null\n let extensions = showExtensions ? getExtensions(param) : null\n\n let paramItems // undefined\n let paramEnum // undefined\n let paramDefaultValue // undefined\n let paramExample // undefined\n let isDisplayParamEnum = false\n\n if ( param !== undefined && schema ) {\n paramItems = schema.get(\"items\")\n }\n\n if (paramItems !== undefined) {\n paramEnum = paramItems.get(\"enum\")\n paramDefaultValue = paramItems.get(\"default\")\n } else if (schema) {\n paramEnum = schema.get(\"enum\")\n }\n\n if ( paramEnum && paramEnum.size && paramEnum.size > 0) {\n isDisplayParamEnum = true\n }\n\n // Default and Example Value for readonly doc\n if ( param !== undefined ) {\n if (schema) {\n paramDefaultValue = schema.get(\"default\")\n }\n if (paramDefaultValue === undefined) {\n paramDefaultValue = param.get(\"default\")\n }\n paramExample = param.get(\"example\")\n if (paramExample === undefined) {\n paramExample = param.get(\"x-example\")\n }\n }\n\n const jsonSchemaForm = bodyParam ? null\n : \n\n return (\n \n \n
\n { param.get(\"name\") }\n { !required ? null :  * }\n
\n
\n { schemaObjectTypeLabel }\n { format && (${format})}\n
\n
\n { isOAS3 && param.get(\"deprecated\") ? \"deprecated\": null }\n
\n
({ param.get(\"in\") })
\n \n\n \n { param.get(\"description\") ? : null }\n\n { (bodyParam || !isExecute) && isDisplayParamEnum ?\n Available values : \" + paramEnum.map(function(item) {\n return item\n }).toArray().map(String).join(\", \")}/>\n : null\n }\n\n { (bodyParam || !isExecute) && paramDefaultValue !== undefined ?\n Default value : \" + paramDefaultValue}/>\n : null\n }\n\n { (bodyParam || !isExecute) && paramExample !== undefined ?\n Example : \" + paramExample}/>\n : null\n }\n\n {(isFormData && !isFormDataSupported) &&
Error: your browser does not support FormData
}\n\n {\n isOAS3 && param.get(\"examples\") ? (\n
\n \n
\n ) : null\n }\n\n { (isObject || isArrayOfObjects) ? (\n \n ) : jsonSchemaForm\n }\n\n {\n bodyParam && schema ? \n : null\n }\n\n {\n !bodyParam && isExecute && param.get(\"allowEmptyValue\") ?\n \n : null\n }\n\n {\n isOAS3 && param.get(\"examples\") ? (\n \n ) : null\n }\n\n { !showCommonExtensions || !commonExt.size ? null : commonExt.entrySeq().map(([key, v]) => )}\n { !showExtensions || !extensions.size ? null : extensions.entrySeq().map(([key, v]) => )}\n\n \n\n \n )\n\n }\n\n}\n","import React, { Component } from \"react\"\nimport PropTypes from \"prop-types\"\n\nexport default class Execute extends Component {\n\n static propTypes = {\n specSelectors: PropTypes.object.isRequired,\n specActions: PropTypes.object.isRequired,\n operation: PropTypes.object.isRequired,\n path: PropTypes.string.isRequired,\n method: PropTypes.string.isRequired,\n oas3Selectors: PropTypes.object.isRequired,\n oas3Actions: PropTypes.object.isRequired,\n onExecute: PropTypes.func,\n disabled: PropTypes.bool\n }\n\n handleValidateParameters = () => {\n let { specSelectors, specActions, path, method } = this.props\n specActions.validateParams([path, method])\n return specSelectors.validateBeforeExecute([path, method])\n }\n\n handleValidateRequestBody = () => {\n let { path, method, specSelectors, oas3Selectors, oas3Actions } = this.props\n let validationErrors = {\n missingBodyValue: false,\n missingRequiredKeys: []\n }\n // context: reset errors, then (re)validate\n oas3Actions.clearRequestBodyValidateError({ path, method })\n let oas3RequiredRequestBodyContentType = specSelectors.getOAS3RequiredRequestBodyContentType([path, method])\n let oas3RequestBodyValue = oas3Selectors.requestBodyValue(path, method)\n let oas3ValidateBeforeExecuteSuccess = oas3Selectors.validateBeforeExecute([path, method])\n let oas3RequestContentType = oas3Selectors.requestContentType(path, method)\n\n if (!oas3ValidateBeforeExecuteSuccess) {\n validationErrors.missingBodyValue = true\n oas3Actions.setRequestBodyValidateError({ path, method, validationErrors })\n return false\n }\n if (!oas3RequiredRequestBodyContentType) {\n return true\n }\n let missingRequiredKeys = oas3Selectors.validateShallowRequired({\n oas3RequiredRequestBodyContentType,\n oas3RequestContentType,\n oas3RequestBodyValue\n })\n if (!missingRequiredKeys || missingRequiredKeys.length < 1) {\n return true\n }\n missingRequiredKeys.forEach((missingKey) => {\n validationErrors.missingRequiredKeys.push(missingKey)\n })\n oas3Actions.setRequestBodyValidateError({ path, method, validationErrors })\n return false\n }\n\n handleValidationResultPass = () => {\n let { specActions, operation, path, method } = this.props\n if (this.props.onExecute) {\n // loading spinner\n this.props.onExecute()\n }\n specActions.execute({ operation, path, method })\n }\n\n handleValidationResultFail = () => {\n let { specActions, path, method } = this.props\n // deferred by 40ms, to give element class change time to settle.\n specActions.clearValidateParams([path, method])\n setTimeout(() => {\n specActions.validateParams([path, method])\n }, 40)\n }\n\n handleValidationResult = (isPass) => {\n if (isPass) {\n this.handleValidationResultPass()\n } else {\n this.handleValidationResultFail()\n }\n }\n\n onClick = () => {\n let paramsResult = this.handleValidateParameters()\n let requestBodyResult = this.handleValidateRequestBody()\n let isPass = paramsResult && requestBodyResult\n this.handleValidationResult(isPass)\n }\n\n onChangeProducesWrapper = ( val ) => this.props.specActions.changeProducesValue([this.props.path, this.props.method], val)\n\n render(){\n const { disabled } = this.props\n return (\n \n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport Im from \"immutable\"\n\nconst propClass = \"header-example\"\n\nexport default class Headers extends React.Component {\n static propTypes = {\n headers: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired\n }\n\n render() {\n let { headers, getComponent } = this.props\n\n const Property = getComponent(\"Property\")\n const Markdown = getComponent(\"Markdown\", true)\n\n if ( !headers || !headers.size )\n return null\n\n return (\n
\n

Headers:

\n \n \n \n \n \n \n \n \n \n {\n headers.entrySeq().map( ([ key, header ]) => {\n if(!Im.Map.isMap(header)) {\n return null\n }\n\n const description = header.get(\"description\")\n const type = header.getIn([\"schema\"]) ? header.getIn([\"schema\", \"type\"]) : header.getIn([\"type\"])\n const schemaExample = header.getIn([\"schema\", \"example\"])\n\n return (\n \n \n \n )\n }).toArray()\n }\n \n
NameDescriptionType
{ key }{\n !description ? null : \n }{ type } { schemaExample ? : null }
\n
\n )\n }\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport { List } from \"immutable\"\n\nexport default class Errors extends React.Component {\n\n static propTypes = {\n editorActions: PropTypes.object,\n errSelectors: PropTypes.object.isRequired,\n layoutSelectors: PropTypes.object.isRequired,\n layoutActions: PropTypes.object.isRequired,\n getComponent: PropTypes.func.isRequired,\n }\n\n render() {\n let { editorActions, errSelectors, layoutSelectors, layoutActions, getComponent } = this.props\n\n const Collapse = getComponent(\"Collapse\")\n\n if(editorActions && editorActions.jumpToLine) {\n var jumpToLine = editorActions.jumpToLine\n }\n\n let errors = errSelectors.allErrors()\n\n // all thrown errors, plus error-level everything else\n let allErrorsToDisplay = errors.filter(err => err.get(\"type\") === \"thrown\" ? true :err.get(\"level\") === \"error\")\n\n if(!allErrorsToDisplay || allErrorsToDisplay.count() < 1) {\n return null\n }\n\n let isVisible = layoutSelectors.isShown([\"errorPane\"], true)\n let toggleVisibility = () => layoutActions.show([\"errorPane\"], !isVisible)\n\n let sortedJSErrors = allErrorsToDisplay.sortBy(err => err.get(\"line\"))\n\n return (\n
\n        
\n

Errors

\n \n
\n \n
\n { sortedJSErrors.map((err, i) => {\n let type = err.get(\"type\")\n if(type === \"thrown\" || type === \"auth\") {\n return \n }\n if(type === \"spec\") {\n return \n }\n }) }\n
\n
\n
\n )\n }\n}\n\nconst ThrownErrorItem = ( { error, jumpToLine } ) => {\n if(!error) {\n return null\n }\n let errorLine = error.get(\"line\")\n\n return (\n
\n { !error ? null :\n
\n

{ (error.get(\"source\") && error.get(\"level\")) ?\n toTitleCase(error.get(\"source\")) + \" \" + error.get(\"level\") : \"\" }\n { error.get(\"path\") ? at {error.get(\"path\")}: null }

\n \n { error.get(\"message\") }\n \n
\n { errorLine && jumpToLine ? Jump to line { errorLine } : null }\n
\n
\n }\n
\n )\n }\n\nconst SpecErrorItem = ( { error, jumpToLine = null } ) => {\n let locationMessage = null\n\n if(error.get(\"path\")) {\n if(List.isList(error.get(\"path\"))) {\n locationMessage = at { error.get(\"path\").join(\".\") }\n } else {\n locationMessage = at { error.get(\"path\") }\n }\n } else if(error.get(\"line\") && !jumpToLine) {\n locationMessage = on line { error.get(\"line\") }\n }\n\n return (\n
\n { !error ? null :\n
\n

{ toTitleCase(error.get(\"source\")) + \" \" + error.get(\"level\") } { locationMessage }

\n { error.get(\"message\") }\n
\n { jumpToLine ? (\n Jump to line { error.get(\"line\") }\n ) : null }\n
\n
\n }\n
\n )\n }\n\nfunction toTitleCase(str) {\n return (str || \"\")\n .split(\" \")\n .map(substr => substr[0].toUpperCase() + substr.slice(1))\n .join(\" \")\n}\n\nThrownErrorItem.propTypes = {\n error: PropTypes.object.isRequired,\n jumpToLine: PropTypes.func\n}\n\nSpecErrorItem.propTypes = {\n error: PropTypes.object.isRequired,\n jumpToLine: PropTypes.func\n}\n","import React from \"react\"\nimport PropTypes from \"prop-types\"\nimport ImPropTypes from \"react-immutable-proptypes\"\nimport { fromJS } from \"immutable\"\n\nconst noop = ()=>{}\n\nexport default class ContentType extends React.Component {\n static propTypes = {\n ariaControls: PropTypes.string,\n contentTypes: PropTypes.oneOfType([ImPropTypes.list, ImPropTypes.set, ImPropTypes.seq]),\n controlId: PropTypes.string,\n value: PropTypes.string,\n onChange: PropTypes.func,\n className: PropTypes.string,\n ariaLabel: PropTypes.string\n }\n\n static defaultProps = {\n onChange: noop,\n value: null,\n contentTypes: fromJS([\"application/json\"]),\n }\n\n componentDidMount() {\n // Populate the form initially\n const { contentTypes, onChange } = this.props\n if (contentTypes && contentTypes.size) {\n onChange(contentTypes.first())\n }\n }\n\n componentDidUpdate() {\n const { contentTypes, value, onChange } = this.props\n\n if (!contentTypes || !contentTypes.size) {\n return\n }\n\n if (!contentTypes.includes(value)) {\n onChange(contentTypes.first())\n }\n }\n\n onChangeWrapper = e => this.props.onChange(e.target.value)\n\n render() {\n let { ariaControls, ariaLabel, className, contentTypes, controlId, value } = this.props\n\n if ( !contentTypes || !contentTypes.size )\n return null\n\n return (\n
\n \n
\n )\n }\n \n}","import React from \"react\"\nimport PropTypes from \"prop-types\"\n\nfunction xclass(...args) {\n return args.filter(a => !!a).join(\" \").trim()\n}\n\nexport class Container extends React.Component {\n render() {\n let { fullscreen, full, ...rest } = this.props\n // Normal element\n\n if(fullscreen)\n return
\n\n let containerClass = \"swagger-container\" + (full ? \"-full\" : \"\")\n return (\n
\n )\n }\n}\n\nContainer.propTypes = {\n fullscreen: PropTypes.bool,\n full: PropTypes.bool,\n className: PropTypes.string\n}\n\nconst DEVICES = {\n \"mobile\": \"\",\n \"tablet\": \"-tablet\",\n \"desktop\": \"-desktop\",\n \"large\": \"-hd\"\n}\n\nexport class Col extends React.Component {\n\n render() {\n const {\n hide,\n keepContents,\n /* we don't want these in the `rest` object that passes to the final component,\n since React now complains. So we extract them */\n /* eslint-disable no-unused-vars */\n mobile,\n tablet,\n desktop,\n large,\n /* eslint-enable no-unused-vars */\n ...rest\n } = this.props\n\n if(hide && !keepContents)\n return \n\n let classesAr = []\n\n for (let device in DEVICES) {\n if (!Object.prototype.hasOwnProperty.call(DEVICES, device)) {\n continue\n }\n let deviceClass = DEVICES[device]\n if(device in this.props) {\n let val = this.props[device]\n\n if(val < 1) {\n classesAr.push(\"none\" + deviceClass)\n continue\n }\n\n classesAr.push(\"block\" + deviceClass)\n classesAr.push(\"col-\" + val + deviceClass)\n }\n }\n\n if (hide) {\n classesAr.push(\"hidden\")\n }\n\n let classes = xclass(rest.className, ...classesAr)\n\n return (\n
\n )\n }\n\n}\n\nCol.propTypes = {\n hide: PropTypes.bool,\n keepContents: PropTypes.bool,\n mobile: PropTypes.number,\n tablet: PropTypes.number,\n desktop: PropTypes.number,\n large: PropTypes.number,\n className: PropTypes.string\n}\n\nexport class Row extends React.Component {\n\n render() {\n return
\n }\n\n}\n\nRow.propTypes = {\n className: PropTypes.string\n}\n\nexport class Button extends React.Component {\n\n static propTypes = {\n className: PropTypes.string\n }\n\n static defaultProps = {\n className: \"\"\n }\n\n render() {\n return